text:
Q: counter is not resetting at end of the each iteration of the loop controller in jmeter I want to reset my counter at end of the each iteration of the loop. I implemented solution in my script like in the page
Jmeter - Loop counter in while loop not resetting on exit
but given solution is not working for me . I am using apache jmeter 5.1.1 version I added below code in JSR223 sampler out side the while controller within transaction controller
def counter=vars.get("counter"); ${__groovy(vars.put('counter'\, '2'),)}

Counter

Counter value is resetting but updated counter value not carrying to second iteration
logs: 2019-10-24 14:53:53,281 INFO o.a.j.p.j.s.J.JSR223 Sampler: counter value-----2

Placed JSR223 Sampler outside while controller/trasaction controller/loop controller.. In all the ways it is giving same response like below

I need result as
xrequest-1

xrequest-2

xrequest-3

xrequest-4

xrequest-5

xrequest-6

xrequest-7

xrequest-8 . . .

yrequest-1

yrequest-2

yrequest-3

yrequest-4

yrequest-5

yrequest-6 . . .

Please help me if i am missing anything.

A: You don't even need any Counter there.
Since JMeter 5.0 While Controller exposes a special JMeter Variable which looks like:
${__jm__While Controller__idx}

where While Controller needs to match the While Controller label.
So if you need to count iterations - you can just refer this variable. It's zero-based, to wit the value will be 0 at the first iteration, if you need the iteration number to start with 1 - go for __intSum() function like:
${__intSum(${__jm__While Controller__idx},1,)}

Demo:


text:
Q: Python Pandas dataFrame - Columns selection I have a Pandas dataFrame object train_df with say a column called "ColA" and a column "ColB". It has been loaded from a csv file with columns header using read_csv
I obtain the same results when I code:
pd.crosstab(train_df['ColA'], train_df['ColB'])
or
pd.crosstab(train_df.ColA, train_df.ColB)
Is there any difference in these 2 ways of selecting columns?
When I request to print the type it's the same : pandas.core.series.Series

A: No difference
pd.crosstab(train_df['ColA'], train_df['ColB']) is recommended to prevent possible errors.
For example, if you have a column named count and if you type train_df.count it will give an error. train_df['count'] won't give an error.

A: If you only want to select a single column, there is no difference between the two ways.
However, the dot notation doesn't allow you to select multiple columns, whereas you can use dataframe[['col1', 'col2']] to select multiple columns (which returns a pandas.core.frame.DataFrame instead of a pandas.core.series.Series).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can one get grid data from a VSFlexGrid window using the WinAPI? WinAPI can get text from particular windows. However, VSFlexGrids are resistant to this since their grid data don't seem contained in easily-accessible child windows.
I've used Spy++ to analyze the VSFlexGrid in question, and it has no children. Yet, when I click a particular grid cell, a new child window seems to be dynamically created.
Question: Given this behavior, is there an easy way to get grid data from a VSFlexGrid using the Windows API, or some other "efficient" method? I'd like not to have to scrape screenshots or click each grid cell individually, as those methods would be slower than a WinAPI call (if a WinAPI method actually exists).


text:
Q: Uncaught ReferenceError: jquery is not defined in Wordpress Can anyone help me out from this issue. I have added a JS to my WordPress site externally. It doesn't produce the output and throws an error in the following code.
Please help me out and get over it.
var clock;

jquery(document).ready(function() {
    var currentDate = new Date();
    // Set some date in the past. In this case, it's always been since Jan 1
    var pastDate  = new Date(currentDate.getFullYear(), - 3, 4, 3);
    // Calculate the difference in seconds between the future and current date
    var diff = currentDate.getTime() / 1000 - pastDate.getTime() / 1000;

    clock = jquery('.clock').FlipClock(diff, {
        clockFace: 'MinuteCounter'
    });
});

A: JavaScript is case sensitive. Use jQuery instead of jquery:
jQuery(document).ready(function() {
    .
    .
    .

    clock = jQuery('.clock').FlipClock(diff, {
        clockFace: 'MinuteCounter'
    });
});


text:
Q: Underscore.js how to countBy I'm new to the underscore.js library, and a novice still at javascript.  I have successfully used the countBy method to summarize my responses.  But how do you use a countBy to count things that are not there vs some predefined buckets?  Or should I be using a different method altogether?
Consider the following example, here is the JSFiddle http://jsfiddle.net/itchesavvy/bfmhtp5e/2/
var data = [{
    questionData: {
        type: 'multiple choice',
        content: {
            text: 'This is the question?',
            answers: [{
                _id: 'id1',
                value: 'First answer'
            }, {
                _id: 'id2',
                value: 'Second answer'
            }, {
                _id: 'id3',
                value: 'Third answer'
            }, {
                _id: 'id4',
                value: 'Fourth answer'
            }]
        }
    },
    responses: [{
        answer: 'id1',
        timestamp: 1
    }, {
        answer: 'id2',
        timestamp: 4
    }, {
        answer: 'id1',
        timestamp: 10
    }, {
        answer: 'id3',
        timestamp: 15
    }, {
        answer: 'id3',
        timestamp: 16
    }, {
        answer: 'id1',
        timestamp: 25
    }, {
        answer: 'id2',
        timestamp: 35
    }, {
        answer: 'id3',
        timestamp: 42
    }, {
        answer: 'id1',
        timestamp: 44
    }, {
        answer: 'id1',
        timestamp: 50
    }, {
        answer: 'id2',
        timestamp: 70
    }, {
        answer: 'id3',
        timestamp: 80
    }, {
        answer: 'id2',
        timestamp: 81
    }]
}];

var b = _.countBy(data[0].responses,'answer');
console.log(b);

This results in the following object {id1:5, id2:4, id3:4}
I would like to know how to get {id1:5, id2:4, id3:4, id4:0} using the data from questionData.content.answers
Even more so, I would like to know how to get {'First answer':5, 'Second answer':4, 'Third answer':4, 'Fourth answer':0} again probably using the data from questionData.content.answers in the value fields.

A: Not sure you need to use underscore at all.

var data=[{questionData:{type:"multiple choice",content:{text:"This is the question?",answers:[{_id:"id1",value:"First answer"},{_id:"id2",value:"Second answer"},{_id:"id3",value:"Third answer"},{_id:"id4",value:"Fourth answer"}]},responses:[{answer:"id1",timestamp:1},{answer:"id2",timestamp:4},{answer:"id1",timestamp:10},{answer:"id3",timestamp:15},{answer:"id3",timestamp:16},{answer:"id1",timestamp:25},{answer:"id2",timestamp:35},{answer:"id3",timestamp:42},{answer:"id1",timestamp:44},{answer:"id1",timestamp:50},{answer:"id2",timestamp:70},{answer:"id3",timestamp:80},{answer:"id2",timestamp:81}]}}];

    //Simplify your object traversal
var questionData = data[0].questionData;
    responses = questionData.responses,
    content = questionData.content,
    //Stage your counters
    i = 0,
    l = content.answers.length,
    //Will hold your answers array as key value pairs for easier lookups
    answers = {},
    //Will hold the final results
    results = {};

//Iterate over your answers collection
for(; i < l; i++){
    //The value of each answer will be used as keys to look up counts in our results object
    var key = content.answers[i].value;
    //We will cross reference 'id#' values with the results keys
    answers[content.answers[i]._id] = key;
    //Start each possible result with a count of zero.
    results[key] = 0;
}

//Output our answers (cross reference object)
console.log(answers);

//Reset our counters to the responses collection
i = 0;
l = responses.length;

//Iterate over the responses
for(; i < l; i++){
    //Use the answer within each response to look up the appropriate results key from our answers object.
    var key = answers[responses[i].answer];
    //Increment the result value.
    results[key]++;
}

//Output the counts of each answer.
console.log(results);

A: This may not be the most efficient way, but it is arguably the most readable (when using Underscore).
var questions = {};
var defaults = {};

// Build a map of 'id1' to 'First answer', etc.
// Build default value of 0 for all questions.
_.each(data[0].questionData.content.answers, function (e) {
    questions[e._id] = e.value;
    defaults[e._id] = 0;
});

// Calculate results by id: {id1: 5, ...}
var resById = _.defaults(_.countBy(data[0].responses, "answer"), defaults);
var results = {};

// Remap ids to strings: 'id1' to 'First answer', etc.
_.each(resById, function (v, k) {
    results[questions[k]] = v;
});

console.log(results);


text:
Q: Is it possible to use lxml extension functions in xpath predicates in xslt stylesheet? An extension function works in xpath evaluation, but not in xslt transform. Is such use not supported at all or do I miss something?
root = etree.XML('HaegarBaegar')
doc = etree.ElementTree(root)

def match_class(context, arg):
    return 'class' in context.context_node.attrib and context.context_node.attrib['class'] == arg

ns = etree.FunctionNamespace('http://example.com/myother/functions')
ns.prefix = 'css'
ns['class'] = match_class

result = root.xpath("//*[css:class('true')]")
assert result[0].text == "Haegar"

xslt = etree.XSLT(etree.XML('''

'''))

result = xslt(doc)
assert str(result) == "Haegar"

The first assert passes.
But the call to xslt(doc) resuts in lxml.etree.XSLTApplyError: Failed to evaluate the 'select' expression., or lxml.etree.XSLTApplyError: Error applying stylesheet if to put the xpath into some template match.

A: I think you use the wrong namespace declaration:
xmlns:es="http://example.com/functions"

You should change in:
xmlns:css="http://example.com/myother/functions"

EDIT
The following example works perfectly:
from lxml import etree

root = etree.XML(u'HaegarBaegar')
doc = etree.ElementTree(root)

def match_class(context, arg):
    return 'class' in context.context_node.attrib and context.context_node.attrib['class'] == arg

ns = etree.FunctionNamespace('http://example.com/myother/functions')
ns.prefix = 'css'
ns['class'] = match_class

result = root.xpath("//*[css:class('true')]")
assert result[0].text == "Haegar"

xslt = etree.XSLT(etree.XML(u'''\

'''))

result = xslt(doc)
assert str(result) == "Haegar"

Tested with Python 2.7 and lxml == 3.8.0


text:
Q: c# jquery issues with limit characters I've got a problem. I have a Gridview filled with a Datatable. When I display the result, I limit the number of characters (300) per rows. I put a button, when you click on it, it opens a pop-up and should display the whole result with no characters limitation. But the problem is that it doesn't display the whole result and I don't know how to do that, I tried to make an invisible datagridview to get its result but I think I'm doing it wrong 'cause it's like I didn't create it
Code html :

           <Columns>

               <asp:TemplateField HeaderText="Aggregation">
                   <ItemTemplate><%# Eval("Aggregation") %></ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="DerniereSolution">
                   <ItemTemplate><%# Eval("DerniereSolution") %></ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="DescriptionDemande">
                   <ItemTemplate><%# Eval("DescriptionDemande") %></ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="NomContact">
                   <ItemTemplate><%# Eval("NomContact") %></ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="Numero">
                   <ItemTemplate><%# Eval("Numero") %></ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="SousRubrique">
                   <ItemTemplate><%# Eval("SousRubrique") %></ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="TitreDemande">
                   <ItemTemplate><%# Eval("TitreDemande") %></ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField>
               <ItemTemplate>
                   Select
               </ItemTemplate>
           </asp:TemplateField>

           </Columns>

       </asp:GridView>

Code Jquery :
jQuery.noConflict();

 jQuery(document).ready(function($){

       $(".select").click(function () {
           ClearBackgroundColourOfRows();
           var tr = $(this).parent().parent();
           $(tr).css('background-color', '#A1DCF2');

           <%  %>

           var children = $(tr).children();
           var agg = $(children[0]).html();
           var lastSol = $(children[1]).html();
           var descr = $(children[2]).html();
           var contact = $(children[3]).html();
           var num = $(children[4]).html();
           var rub = $(children[5]).html();
           var title = $(children[6]).html();

           var message = "Titre Demande
" + title + "

" + "Aggregation
" + agg + "

" + "Dernière Solution
" + lastSol + "

" + "Description Demande
" + descr + "

" + "Nom Contact
" + contact + "

" + "Numéro
" + num + "

" + "Sous-Rubrique
" + rub;

           $(".modal-body").empty();
           $(".modal-body").html(message);
           $('#myModal').modal('show');
       });

       function ClearBackgroundColourOfRows() {
           $('#gvData tr').each(function () {
               $(this).css('background-color', 'transparent');
           });
       }

       $(".btn").click(function () {
           ClearBackgroundColourOfRows();
       });

   });

Code c# :
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
       {

           if (e.Row.RowType == DataControlRowType.DataRow)
           {

               e.Row.Cells[2].Text = ((DataRowView)e.Row.DataItem).Row[2].ToString().Replace(tbSearch.Text, "
" + tbSearch.Text + "
");
               e.Row.Cells[6].Text = ((DataRowView)e.Row.DataItem).Row[6].ToString().Replace(tbSearch.Text, "
" + tbSearch.Text + "
");//highlight words

               e.Row.Cells[0].Text = ((DataRowView)e.Row.DataItem).Row[0].ToString().Substring(0, 300) + "...";//limit characters
               e.Row.Cells[1].Text = ((DataRowView)e.Row.DataItem).Row[1].ToString().Substring(0, 300) + "...";
               e.Row.Cells[2].Text = ((DataRowView)e.Row.DataItem).Row[2].ToString().Substring(0, 300) + "...";

       }

Any ideas ?

A: Remove gvData_RowDataBound completely and use jQuery for limiting characters and displaying the full cell text in popup.Hope the example below helps you
Code behind:
public partial class CharacterLimitationExample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            GetData();
    }

    private void GetData()
    {
        var d1 = new Data { Aggregation = "Row 1", DerniereSolution = "Row 1 really really long data", DescriptionDemande = "Row 1", NomContact = "Row 1", Numero = "Row 1", SousRubrique = "Row 1", TitreDemande = "Row 1" };
        var d2 = new Data { Aggregation = "Row 2", DerniereSolution = "Row 2 really really long data", DescriptionDemande = "Row 2", NomContact = "Row 2", Numero = "Row 2", SousRubrique = "Row 2", TitreDemande = "Row 2" };

        gvData.DataSource = new List<Data> { d1, d2 };
        gvData.DataBind();
    }
}
public class Data
{
    public string Aggregation { get; set; }
    public string DerniereSolution { get; set; }
    public string DescriptionDemande { get; set; }
    public string NomContact { get; set; }
    public string Numero { get; set; }
    public string SousRubrique { get; set; }
    public string TitreDemande { get; set; }
}

.ASPX:

    <title></title>

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

    <form id="form1" runat="server">
        <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="Aggregation">
                    <ItemTemplate>
                        <span data-fulltext='<%# Eval("Aggregation") %>'>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="DerniereSolution">
                    <ItemTemplate>
                        <span data-fulltext='<%# Eval("DerniereSolution") %>'>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="DescriptionDemande">
                    <ItemTemplate>
                        <span data-fulltext='<%# Eval("DescriptionDemande") %>'>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="NomContact">
                    <ItemTemplate>
                        <%# Eval("NomContact") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Numero">
                    <ItemTemplate>
                        <%# Eval("Numero") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="SousRubrique">
                    <ItemTemplate>
                        <%# Eval("SousRubrique") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="TitreDemande">
                    <ItemTemplate>
                        <%# Eval("TitreDemande") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        Select
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Details

                        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>

    </form>

Output:


text:
Q: Shell Find and Replace Domain in all files and its folder, sub folder I have a domain
https://account.oldomain.com

I now migrate to a new domain
https://account.newdomain.com

I wanna replace all occurance of account.olddomain.com with account.newdomain.com
How do I do it
I know I can use something like
sed -i 's/account.oldomain.com/account.newdomain.com/g' /hello

But sed: couldn't edit /hello: not a regular file
How do I replace all the files inside current directory, and its directory , sub directory of directory , as in all the files and folders of the current folder
with containing the text account.oldomain.com with account.newdomain.com

Thanks!!

A: try:
find /hello -type f|xargs sed -i 's#\(account[.]\)oldomain\([.]com\)#\1newdomain\2#g'

I change your . -> [.], to match exactly dot, not any char.


text:
Q: PHP variable won't print before defining it I'm using a portable WAMP package "USB web server". It is giving error if i try to echo some variable directly, for example
<?php
echo $abc;
?>

The error i get is: "Notice: Undefined variable: abc "
This will work fine:
<?php
$abc = "foo";
echo $abc;
?>

Is it possible to fix this error?
I am bound to use portable WAMP package as I do no thave administrator privileges, so i can not install any other package.

A: Well, apart from why I don't know why you would want to echo something that is not defined, you're not getting an error, you're getting a notice.
If you want to do this, you've got to ignore notices in your production environment, like you can read here works like this:
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

A: What should it print if it is not defined?
You can check if it is defined before you try to print it
if(isset($abc))
{
    echo $abc;
}

You can also suppress the error by appending an @ sign in front of the line
@echo $abc;

But that is not recommended and can be slower.

A: to remove notice and warning
write
error_reporting(E_ALL ^ E_NOTICE); at the top of the page

A: The variable is indeed not defined. What exactly would you like to happen?
If you don't want to see the error, then define it.
<?php
$abc = '';
echo $abc;
?>

A: Well, the answer is to fix the code so you aren't accessing variables that have not been defined.  If you need to prevent it from printing errors which is not the correct solution (*), then you can switch off notices in your error reporting:
error_reporting(E_ALL ^ E_NOTICE);

The correct solution is to fix the code.

A: Check if it exists before echoing it
if( isset($abc) )
{
   echo $abc
}

A: you could of course also just check if the variable exists.
<?php if (isset($myvar)) echo $myvar; ?>

cu
Roman

A: You could also suppress the warning on the echo command. Disabling warnings in general is dangerous.
<?php
    @echo $abc;
?>

A: One of the earliest principle you learn in programming is to declare your variables. Therefore, to fix this error, declare your variables.
However, it may happen in multiple cases that you don't know if the variable has been defined or not, but still want to avoid the error.
In those cases, check for its existence first:
// print $abc if set, or print an empty string/nothing
echo isset($abc) ? $abc : '';
isset($abc) && print $abc;
if (isset($abc)) echo $abc;

The three lines above will give the exact same result one another.


text:
Q: What's happened to Monospace in Android Lollipop? I have a style to use "monospace" in my Android App:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Base application theme. -->
    <style name="AppTheme"  parent="Theme.AppCompat.Light.DarkActionBar" >
        <!-- Customize your theme here. -->
        <item name="android:windowNoTitle">true</item>
        <item name="android:typeface">monospace</item>
        <item name="android:textColorPrimary">@android:color/white</item>
        <item name="android:itemTextAppearance">@style/MenuText</item>
   </style>

   <style name="M13Text">
        <item name="android:typeface">monospace</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textColorLink">@android:color/holo_red_light</item>
   </style>

   <style name="MenuText">
       <item name="android:typeface">monospace</item>
       <item name="android:textColor">@android:color/black</item>
   </style>
</resources>

All was fine until Lollipop arrived when it doesn't seem use the Monospace font anymore and I can see it change when I flip APIs from 19 to 21 in Android Studio.
I've googled and not found anything and I appreciate it is just a cosmetic issue but anyone got any ideas as to why?

A: The Material text appearances specify the android:fontFamily attribute rather than android:typeface so that they can use sans-serif-light, sans-serif-medium, etc. This attribute takes precedence over typeface, so you will need to either override or clear the fontFamily value.
<style name="MenuText">
    <item name="android:fontFamily">monospace</item>
    ...
</style>


text:
Q: Insert data from Excel into oracle database using JAVA I have 7 columns in my Excel sheet. I created an empty  table in database with respective column names.
So, How can I insert all the data in Excel into database table.
please help me, thanks.

A: You can use POI to do so.Sample code is as below.For detail you can refer this.
   /* Create Connection objects */
            Class.forName ("oracle.jdbc.OracleDriver");
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe", "hr", "hr");
            PreparedStatement sql_statement = null;
            String jdbc_insert_sql = "INSERT INTO XLS_POI"
                            + "(KEYWORD, TOTAL_COUNT) VALUES"
                            + "(?,?)";
            sql_statement = conn.prepareStatement(jdbc_insert_sql);
            /* We should now load excel objects and loop through the worksheet data */
            FileInputStream input_document = new FileInputStream(new File("xls_to_oracle.xls"));
            /* Load workbook */
            HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document);
            /* Load worksheet */
            HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0);
            // we loop through and insert data
            Iterator<Row> rowIterator = my_worksheet.iterator();
            while(rowIterator.hasNext()) {
                    Row row = rowIterator.next();
                    Iterator<Cell> cellIterator = row.cellIterator();
                            while(cellIterator.hasNext()) {
                                    Cell cell = cellIterator.next();
                                    switch(cell.getCellType()) {
                                    case Cell.CELL_TYPE_STRING: //handle string columns
                                            sql_statement.setString(1, cell.getStringCellValue());
                                            break;
                                    case Cell.CELL_TYPE_NUMERIC: //handle double data
                                            sql_statement.setDouble(2,cell.getNumericCellValue() );
                                            break;
                                    }

                            }
            //we can execute the statement before reading the next row
            sql_statement.executeUpdate();
            }
            /* Close input stream */
            input_document.close();
            /* Close prepared statement */
            sql_statement.close();
            /* COMMIT transaction */
            conn.commit();
            /* Close connection */
            conn.close();


text:
Q: uml class diagram association I'm beginning with UML and i'm trying to create a class diagram for a simple online shopping application. I would like to know if i should create an association beetween the following classes:

*

*Card: A payment card

*CardVerificator.

The responsability of the CardVerificator class is to check with the payment system if a card is valid or not.  This class has one method with the following signature: verifyCard(Card):void (The method raises an exception when the given card is not valid).
(Sorry for my bad english)
Thank you.

A: You don't need an association here, only a dependency between those classes.
Association comes in the action, when you need a permanent, long-term link between the corresponding objects. In code is this situation often reflected through data members. Here we speak about a short-term limited contact that should even not be persisted (a simple method parameter instead of a data member).
CardVerificator should of course "know" the "Card" concept in order to be able to verify it, but this is nicely explained with a simple generic dependency:


text:
Q: How do I access the onTextLayout event within a React Native Text component? I have a React Native Text component that contains a user profile's information and has a max NumberOfLines at 2. I also have a TouchableOppacity button that says "Read More.." on it that clears the max NumberOfLines of the component. I don't want the "Read More" button to show if there the NumberOfLine is already 2 or less.
In the documentation it says that the onTextLayout event would return an array with a TextLayout objects for each line but when I try to access it I never have anything returned. I've tried to access the onLayout event and I can get info from that event but it doesn't have the info that I need. Has anyone had this problem?
<Text numberOfLines={2} onTextLayout={onInfoLayout}>
            test text test text test text test text
            test text test text test text test text
</Text> }

const onInfoLayout = React.useCallback((e:any) =>{
   console.log("this is how long the text is", e);
}, []);

The code above displays nothing in the console but if I were to change onTextLayout to just onLayout it would log the object.. but again that event doesn't have the info I need.
Any help is super appreciated!

A: The correct prop is onLayout according react native documentation here:
https://reactnative.dev/docs/text#onlayout

A: Just came across this issue. It seems you can't log the entire event object in the console because it has self-referential fields. See this answer.


text:
Q: PHP - Does MySQL query won't work if database is in MS SQL Server? I was wondering why MySQL Queryis not working on my localhost(XAMPP), it was like a simple LIMIT and Offset clause not working. So I try to check deep on my code and I notice that my Database is in a MS SQL Server. Now I try to use TOP keyword instead of LIMIT and it work. My question is does connecting to a MS SQL Database wouldn't allow me to use MySQL query? If so is there any possible way to use MySQL query on my case? Because I'm having a hard time on my query using SQL Query. I really need an answer on this, any answers is appreciated. Thanks

A: Every brand real-world SQL database server system has its own dialect of the query language. It's a rare and carefully crafted query that works cross-brand.
And, pretty much no query with a LIMIT or TOP clause works cross-brand.
Welcome to the world of full employment for SQL coders!


text:
Q: Icon set on an Outlook folder with MAPIFolder.SetCustomIcon does not scale properly on high DPI screen I am trying to set an icon to a folder from VSTO Outlook add-in using approach similar to what described here:
How to programmatically set a custom icon on an Outlook search folder? (i.e. Outlook Folder SetCustomIcon)
It is working, but fail in Outlook365/Windows11 setup with high-DPI screen. With scaling set to 250% icon of any size for some reason takes only top-left part and looks like this:

And when I drag Outlook window on external display with 125% scale it becomes this:

On 100% screen same approach working without issues.
Is it Outlook bug or there is a way to make it respect DPI settings?
In Windows10/Outlook 365 16.0.15601.20148 32-bit it is working even with 200% scaling, but only if one monitor is present in the system.


text:
Q: How can I launch gitahed from terminal? I enjoy using gitahed, and I would like to add a shortcut to lauch it, with github desktop I use github-desktop, but I can do the same with GA?
How can I launch gitahed from terminal?

A: GitAhead has a Terminal panel at Tools->Options. It has a button to install command line tools. It really just creates a symlink to the GitAhead binary in /usr/local/bin. If that doesn't work for some reason, you can create the symlink yourself or an alias. See command line options by running with the --help flag. There are only a few at the moment.


text:
Q: Rails 4.2: How to forcefully reload (engine's) route? How to absolutely force to reload the routes in before_action? Rails.application.reload_routes! reloads the routes only if there is change in routes.rb.
Here is the chapter in ActionDispatch::Routing about how to reload the route:
Reloading routes

You can reload routes if you feel you must:

Rails.application.reload_routes!

This will clear all named routes and reload routes.rb if the file has been modified from last load. To absolutely force reloading, use reload!.

There is no detail about how to force to reload except mentioning reload!. Tried Rails.application.reload! in before_action and it did not work. In application controller:
before_action :reload_route

def reload_route
  Rails.application.reload_routes!
end

If the engine name is MyEngine, what's the right way to force to reload its route?

A: config.paths["config/routes.rb"] << YOUR_ROUTE_FILE


text:
Q: EMNIST dataset training high loss I've been trying to train a model with the EMNIST dataset (as I also need letters) using tensorflow.
Here's where I'm getting the data: https://www.tensorflow.org/datasets/catalog/emnist
My code for the model:
import tensorflow as tf
import tensorflow_datasets as tfds

train_ds, test_ds = tfds.load('emnist', split=['train', 'test'], shuffle_files=True)

x_train = train_ds.map(lambda i: i['image'])
y_train = train_ds.map(lambda l: l['label'])
x_test = test_ds.map(lambda x: x['image'])
y_test = test_ds.map(lambda y: y['label'])

def train():

    model = tf.keras.models.Sequential()
    model.add(tf.keras.layers.Flatten(input_shape=(28, 28, 1)))
    model.add(tf.keras.layers.Dense(256, activation='relu'))
    model.add(tf.keras.layers.Dense(256, activation='relu'))
    model.add(tf.keras.layers.Dense(62, activation='softmax'))

    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    model.fit(tf.data.Dataset.zip((x_train, y_train)).batch(32), epochs=8)

But the training output is:
Epoch 1/8
21811/21811 [==============================] - 126s 6ms/step - loss: 3.8161 - accuracy: 0.0527
Epoch 2/8
21811/21811 [==============================] - 130s 6ms/step - loss: 3.6866 - accuracy: 0.0539
Epoch 3/8
21811/21811 [==============================] - 117s 5ms/step - loss: 3.6854 - accuracy: 0.0544
Epoch 4/8
21811/21811 [==============================] - 127s 6ms/step - loss: 3.6851 - accuracy: 0.0545
Epoch 5/8
21811/21811 [==============================] - 125s 6ms/step - loss: 3.6850 - accuracy: 0.0546
Epoch 6/8
21811/21811 [==============================] - 126s 6ms/step - loss: 3.6849 - accuracy: 0.0546
Epoch 7/8
21811/21811 [==============================] - 133s 6ms/step - loss: 3.6849 - accuracy: 0.0547
Epoch 8/8
 9537/21811 [============>.................] - ETA: 1:07 - loss: 3.6862 - accuracy: 0.0543

Given this incredibly high loss, I can't really think that I'm doing this correctly. I'm wondering if there's something I'm doing wrong here.
Thanks

A: You can load the full dataset as a single Tensor or NumPy array by using batch_size=-1 to batch all examples in a single tf.Tensor. Then use tfds.as_numpy for the conversion from tf.Tensor to np.array as below.
(img_train, label_train), (img_test, label_test) = tfds.as_numpy(tfds.load(
    'emnist',
    split=['train', 'test'],
    batch_size=-1,
    as_supervised=True,
))

Then use the Conv2D layer for better model training because you are using an image dataset.
def train():
    model = tf.keras.models.Sequential()
    model.add(tf.keras.layers.Conv2D(32, (3,3), input_shape=(28, 28, 1), activation='relu'))
    model.add(tf.keras.layers.MaxPool2D(2,2))
    model.add(tf.keras.layers.BatchNormalization())
    model.add(tf.keras.layers.Flatten())
    model.add(tf.keras.layers.Dense(32, activation='relu'))
    model.add(tf.keras.layers.Dense(32, activation='relu'))
    model.add(tf.keras.layers.Dense(62, activation='softmax'))

    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    model.fit(img_train, label_train, epochs=8)

Output:(You can see the result below. The model loss decreased and accuracy increased comparatively)
Epoch 1/20
21811/21811 [==============================] - 72s 3ms/step - loss: 0.5864 - accuracy: 0.8078
Epoch 2/20
21811/21811 [==============================] - 71s 3ms/step - loss: 0.4661 - accuracy: 0.8376
Epoch 3/20
21811/21811 [==============================] - 71s 3ms/step - loss: 0.4411 - accuracy: 0.8441
Epoch 4/20
21811/21811 [==============================] - 71s 3ms/step - loss: 0.4252 - accuracy: 0.8483
Epoch 5/20
21811/21811 [==============================] - 71s 3ms/step - loss: 0.4145 - accuracy: 0.8515
Epoch 6/20
21811/21811 [==============================] - 71s 3ms/step - loss: 0.4064 - accuracy: 0.8536
Epoch 7/20
21811/21811 [==============================] - 71s 3ms/step - loss: 0.3998 - accuracy: 0.8555
Epoch 8/20
21811/21811 [==============================] - 71s 3ms/step - loss: 0.3939 - accuracy: 0.8570
Epoch 9/20
21811/21811 [==============================] - 71s 3ms/step - loss: 0.3894 - accuracy: 0.8582
Epoch 10/20
21811/21811 [==============================] - 71s 3ms/step - loss: 0.3857 - accuracy: 0.8591

For more details, please refer to the TensorFlow Datasets's performance tips.


text:
Q: Where did the Sharing Options from nautilus go? Today I wanted to share trough my home network some files with my father's laptop who happens to be running windows.
I remember there was a 'Sharing Options' in nautilus when right clicking on a folder but I must have removed some packaged that removed it as well.
How can I restore it?

A: This is how I resolved this:
I had removed the nautilus-share package.

Now, I have reinstalled it now and it works.


text:
Q: JPA2.0 & Hibernate: Removing Child table rows with Parent entity merge (On removing entries from parent's child entity set) I am using JPA2.O with Hibernate. I have one to many relationship between User and Address and I have below configuration with this relationship:
cascade = CascadeType.ALL, fetch = FetchType.LAZY,

For example I have below entries in database tables:
User Table
Column: UserID | UserName
row1:    User1 | UserName

Address Table
Column: AddressId| UserID | Address

row1:   Address1 | User1  | Actual Address

row2:   Address2 | User1  | Actual Address

I can fetch User entity using find by userId:
User user = entityManager.find(User.class, userId);

And also can fetch Answers using user.getAddresses(). Code for getAddressess() is like below:
public class User{
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
    public Set<Address> getAddresses() {
       return this.addresses;
    }
}

Now what I am trying to do, I am fetching the set of addresses and removing one entry. Let say I fetched addressess set first time I have address 1 and 2. I removed address 2 entity from set of addresses. Now User entity is pointing to the Set which is having only 1 entry that is for Address1.
Now If I merge user entity using below method, I think, row for address 2 should be deleted from address table. But it is not happening. Am I missing any thing or it is not a way to do it. Please suggest.
entityManager.merge(user);

A: Just want to add more detail as I got this working.
I added orphanRemoval = true with @OneToMany relationship:
public class User{
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "user")
    public Set<Address> getAddresses() {
       return this.addresses;
    }
}

After changing my code I re-tested it and got below error:
Caused by: org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance:

This link helped me to solve above problem:
Now I can delete the child entities from database, if those are disconnected(removed) from defined collection in parent entity.


text:
Q: How can I use python pdb when running a package directly? I have a nested python package structure that I can install and run different parts of.  For example, to start the Tornado/Flask web server, I execute the following:
python3 -m mytool.web -c myconfig.yaml

Where the web package contains both an __init__.py and a __main__.py.  I use this structure in several other components, so once the package is installed it's easy to run, which I do in containers.
My issue is when I'm trying to debug with pdb.  Since pdb is started a similar way I start my package components, i.e. python3 -m pdb /path/to/debuging/file.py, I don't know how I can use the pdb tool to debug something else that is ran directly as a package.
python3 -m pdb mytool.web -c myconfig.yaml doesn't work.
Any suggestions?

A: ipython --pdb -m mytool.web -- -c myconfig.yaml
This form also works for regular script invocation without the -m
(you need the -- in both forms to make ipython stop consuming args
and pass them to your module/script)


text:
Q: Tailwind CSS : Is there a way to target next sibling? I have a radio input with a label like below.  input is hidden and label is used to make a visually appealing circle on which user can click.
<input id="choice-yes" type="radio" class="opacity-0 w-0 fixed"/>
Yes

When user clicked on the label input get checked. I'm trying to figure out how to target that, so I could give the label a different style.
This can be achieved in pure css using next sibling selector.
input[type="radio"]:checked + label {
  background-color: #bfb !important;
  border-color: #4c4 !important;
}

Is there something similar in tailwind.css that I could use instead?

A: There isn't anything built into Tailwind presently.  The closest feature would be Pseudo-Class Variants of which there is a "checked" prefix.  But that would only apply to the radio itself.  In order to target siblings you'd need to write your own complex variant and then you could do something like
<input id="choice-yes" type="radio"/>
Yes

A: For those looking to implement this, since introduction of just-in-time mode (Tailwind CSS v2.1+) sibling selector variant is available.

A: Here's a complex variant I wrote for this purpose (tested with tailwindcss 2.0.1)
// tailwind.config.js

const plugin = require("tailwindcss/plugin");

const focusedSiblingPlugin = plugin(function ({ addVariant, e }) {
  addVariant("focused-sibling", ({ container }) => {
    container.walkRules((rule) => {
      rule.selector = `:focus + .focused-sibling\\:${rule.selector.slice(1)}`;
    });
  });
});

module.exports = {
  // ...
  plugins: [focusedSiblingPlugin],
  variants: {
    extend: {
      backgroundColor: ["focused-sibling"],
    },
  },
};

A: So, I've been wondering the same and since I've created my own variants since my Tailwind debut, I thought I could create a quick one for you.
My problem with previous answers is that the class is focused on the sibling. The class should be appended to the first item and used as such :
<input id="choice-yes" type="radio" class="nextOnChecked:bg-blue-500 nextOnChecked:border-blue-800"/>

The code for the variant should be something like :
const plugin = require("tailwindcss/plugin");

const nextOnChecked = plugin(function ({ addVariant, e }) {
  addVariant('nextOnChecked', ({ modifySelectors, separator }) => {
    modifySelectors(({ className }) => {
      return `.${e(`nextOnChecked${separator}${className}`)}:checked + *`;
    })
  });
});
module.exports = {
  variants: {
    extend:{
      border: ['nextOnChecked'],
      backgroundColor: ['nextOnChecked'],
    },
  },
  plugins: [
    nextOnChecked
  ],
};

This part .${e('nextOnChecked${separator}${className}')}:checked + * will be used, in the context of this example, as the following :
.nextOnChecked\:bg-blue-500:checked + *{
   background-color: ...;
}

That's how I build most of my variants, from the DOM that changes the state to the DOM that is being re-styled.

A: You can use group-hover for this situation.
https://tailwindcss.com/docs/hover-focus-and-other-states

A: Since Tailwind v2.1 the JIT engine supports the peer variant, who works similarly to group, but is based on state of direct sibling.
Ex.:
<input id="choice-yes" type="radio" class="peer opacity-0 w-0 fixed"/>
Yes
Source: https://v2.tailwindcss.com/docs/just-in-time-mode#sibling-selector-variants


text:
Q: Set Identity as (11 - 2) in sql table I have a issue,
I want to set the ID column, where the ID should start from 11-2 then it should auto- increment by 1 like
11-3, 11-4.
I am using sql-server 2008 R2. Please help

A: Use an IDENTITY column for the incrementing ID value, then prefix it with 11- as a computed column.
CREATE TABLE [Table2]
    (
    ID int IDENTITY(1,1),
    ID_pretty AS ('11-' + CAST(ID AS nvarchar))
    CONSTRAINT pk_ID PRIMARY KEY (ID))
GO


text:
Q: Jupyter Looping Newtons Method I seem to have some trouble with a loops in Jupyter Notebook. The code I created reads in an initial guess(p0) and solves the iterations from there. Instead, I would like to loop the initial guess until it finds the first positive root. How would I go about this?
#find the first positive root to the problem below with accuracy within 10^{-5}
#x^4+5x^3-9x^2-85x-136
def newt(p):
    maxIt = 1000
    tol = 1e-5
    for i in range(maxIt):
        fp = p**4 + 5*p**3 - 9*p**2 - 85*p - 136
        fprimep = 4*p**3 + 15*p**2 - 18*p - 85 #derivative of fp
        p_new = p - fp/fprimep
        if abs (p - p_new) < tol:
            return p
        p = p_new

#p0 = 3 #first postive root after 6 iterations?
p = newt(p0)
print(p)


text:
Q: Swift / Refactoring of element attributes I have several elements of a UICollectionView with the following code:
    cell.eventsImageView.clipsToBounds = true
    cell.eventsImageView.layer.cornerRadius = 10.0
    cell.eventsImageView.layer.borderWidth = 4.0
    cell.eventsImageView.layer.borderColor = UIColor.uIColorFromHex(0xE90289).CGColor

What's the best practise to refactor that?
I want to do something like:
    class refactoredXY (Bool, Double, Double, CGColor) {
        clipsToBounds = Bool
        cornerRadius = Double
        borderWidth = Double
        borderColor = CGColor
    }

To call:
    cell.eventsImageView.refactoredXY(true, 10.0, 4.0, UIColor.uIColorFromHex(0xE90289))

A: Since you're actually modifying UIImageView properties, you can go for Extension, where you will add function, that do what you need. Like this
extension UIImageView {
    func setDesiredProperties(clipsToBounds clipToBounds : Bool, layerCornerRadius : CGFloat, layerBorderWidth : CGFloat, layerBorderColor : UIColor) {
        self.clipsToBounds = clipToBounds;
        self.layer.cornerRadius = layerCornerRadius;
        self.layer.borderWidth = layerBorderWidth;
        self.layer.borderColor = layerBorderColor.CGColor;
     }
}

Then you can simply call it like this
cell.eventsImageView.setDesiredProperties(true, 10.0, 4.0, UIColor.uIColorFromHex(0xE90289));

Also, if you you want this function be available only for you cells not all UIImageViews, you can make it this way
extension YourCollectionViewCellClass {
    func setDesiredProperties(clipsToBounds clipToBounds : Bool, layerCornerRadius : CGFloat, layerBorderWidth : CGFloat, layerBorderColor : UIColor) {
        self.eventsImageView.clipsToBounds = clipToBounds;
        self.eventsImageView.layer.cornerRadius = layerCornerRadius;
        self.eventsImageView.layer.borderWidth = layerBorderWidth;
        self.eventsImageView.layer.borderColor = layerBorderColor.CGColor;
     }
}

and apply it this way
cell.setDesiredProperties(true, 10.0, 4.0, UIColor.uIColorFromHex(0xE90289));


text:
Q: How to set ratings individually with localstorage? Okay so as you can tell,I am building a recipe app where in each recipe detail page, I can rate the the recipe...but now the problem is that when I rate one recipe now, the same rating is set for all the other recipes as well. Any idea how to fix that? Apreciate any advice...thanks so much :))
Details.js
import { useParams } from 'react-router-dom';
import './Details.css';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Image from './vitaminDfood-1132105308-770x553.jpg';
import {Link} from 'react-router-dom'
import ReactStars from 'react-rating-stars-component'
 import { RecipeContext } from './RecipeContext';
 import { useContext } from 'react';

function Details() {
  const [details, setDetails] = useState([]);
  const { recipeId } = useParams();
  const{recipes,setRecipes}=useContext(RecipeContext)
  const initialRatings = JSON.parse(localStorage.getItem("rating") || "[]");
  const[rating,setRating]=useState(initialRatings)
  useEffect(() => {
    axios
      .get(`https://cookbook.ack.ee/api/v1/recipes/${recipeId}`)
      .then((res) => setDetails(res.data));

  });
  useEffect(() => {
    localStorage.setItem("rating", JSON.stringify(rating));
  }, [rating])

  const ratingChanged = (newRating) => {

    var rate={
      score:newRating

    }
   setRating(newRating)
    axios.post(`https://cookbook.ack.ee/api/v1/recipes/${recipeId}/ratings`,rate)
    .then((res) => {
     console.log(res.data)
      setRecipes(recipes)

    })

  };

  return (
    <>

      <Link to="/"> </Link>

{details.name}

        {new Array(rating).fill(null).map(() => (

        ))}

{details.duration}min.

{details.info}

Ingredience

{details.ingredients}

Příprava

{details.description}

      <ReactStars
      classNames="star"
      size={48}
      onChange={ratingChanged}
      count={5}
      value={1}
      edit
      />

    </>
  );
}

export default Details;

A: You have a couple options:

*

*Store a different localStorage key for each recipe

*Just have one large "ratings" key in localStorage and make that an object keyed off of your recipeId.

I think the first option is the most straightforward and can be accomplished with these minor modifications:
const initialRatings = JSON.parse(localStorage.getItem(`ratings-${recipeId}`) || "[]");

useEffect(() => {
  localStorage.setItem(`ratings-${recipeId}`, JSON.stringify(rating));
}, [rating, recipeId])


text:
Q: Is there any style framework for react-native similar to bootstrap for web? Ionic is awesome, but if you want to stay in the React-native world, I haven't found anything comparable and compatible. Let me know if you have any suggestions?

A: Disclaimer: I own NativeBase.io and Native Starter Pro.
My team built Native Start Pro - Premium React Native starter kit to quickly get off the ground on your next mobile app projects.
It includes

*

*Customizable variables just like Bootstrap

*Components like Contact list, Login screen, Simple forms, Slide-in menu, Inbox view, Compose Email, View Email

It also comes with a detailed documentation.

We Open-Sourced many components from Native Starter Pro as NativeBase.io which is getting huge popularity on ProductHunt

A: The closest thing is going to be material design https://github.com/xinthink/react-native-material-kit which is pretty great. At this time there is no bootstrap for react native, not to say that it isn't coming down the pipeline one day.

A: This project is aiming toward this direction:
https://github.com/react-native-community/react-native-elements


text:
Q: Create class objects from a database How do you create a new class object and add data to it from a database?
I have a table(tblCars) in a database and would like to loop through each row(Using sqldatareader?) and create a new object named after the primary key(Registration number), then add data to it from the other columns.
So instead of this:
carClass car1 = new carClass();
car1.registration = "RT11 HWY";
car1.make = "Ford";

It would be something like:
//connection and reader stuff
carClass <registration> = new carClass();
<registration>.registration = column1;
<registration>.make = column2;

A: You can use some lightweight ORM for this kind of mapping. Take a look here, there are many free solutions for this. There are also at least two made by Microsoft, LINQ to SQL and Entity Framework


text:
Q: Gunicorn: No module named '/path/to/my/django/project' I was using gunicorn with nginx on Ubuntu 16.04 system to deploy a django project and want to create a systemd service for gunicorn. In /lib/systemd/system/gunicorn-mywebsite.service, I write following codes:
ExecStart=/home/myusername/sites/pythonEnv/bin/gunicorn --bind unix:/tmp/mywebsite.socket /path/to/my/django/project.wsgi:application

But when I ran service gunicorn-mywebsite start, there was problem No module named '/path/to/my/django/project'.
If I run the same command my django project directory with relative path of my wsgi:application, it will work.
How can I fix this problem?

A: You can't give gunicorn a path to a file, it needs to be a module path, with application entry point name. So just project.wsgi:application. If the directory containing project is not in your path, then use the --pythonpath to gunicorn to tell it where it is.


text:
Q: How expensive is calling size() on List or Map in Java? How expensive is calling size() on List or Map in Java? or it is better to save size()'s value in a variable if accessed frequently?

A: for ArrayList the implementation is like
   public int size() {
       return lastIndex - firstIndex;
   }

So  not over head
You can check the source code for detailed info for your required Impl.
Note: The source given is from openjdk

A: List and Map are interfaces, so it's impossible to say. For the implementations in the Java Standard API, the size is generally kept in a field and thus not performance-relevant.

A: For most Collections, calling size() is a constant-time operation. There are however some exceptions. One is ConcurrentLinkedQueue. From the Javadoc of the size() method:

Beware that, unlike in most collections, this method is NOT a constant-time operation. Because of the asynchronous nature of these queues, determining the current number of elements requires an O(n) traversal.

So I'm afraid there's no generic answer, you have to check the documentation of the individual collection you are using.

A: Implement it, then test it. If it is slow, take a closer look.
"Premature optimisation is the root of all evil." - D. Knuth
Also: You should not require certain implementation features, especially if they are black-boxed. What happens if you replace that list with a concurrent list at a later date? What happens if Oracle decides to rewrite List? Will it still be fast? You just don't know.

A: The answer is that it depends on the actual implementation class.  For some Map and Collection classes, size() is a cheap constant-time operation.  For others, it may entail counting the members.
The Java Collections Cheatsheet (V2) is normally a good source for this kind of information, but the host server is currently a bit sick.
The "coderfriendly.com" domain is no more, but I tracked down a copy of the cheat-sheet on scribd.com.
The cost of size() will also be obvious from looking at the source code.  (And this is an "implementation detail" that is pretty much guaranteed to not change ... for the standard collection classes.)
FOLLOWUP
Unfortunately, the cheatsheet only documents the complexity of size for queue implementations.  I think that's because it is O(1) for all other collections; see @seanizer's answer.

A: You don't have to worry much about that. The list implementations keep track of size. The cost of the call is just O(1). If you are very curious, you can read the source code for the implementations of Collection's concrete classes and see the size() method there.

A: Implementation gets it from a private pre-computed variable so it's not expensive.

A: No need to store.Its not at all expensive.Check the source of ArrayList and HashMap.

A: I think some implementations of LinkedList count the total for each call.  The call to a method itself can be a little taxing, but only if we're talking about large iterations or driver coding for hardware would that really be an issue.
In either case, if you save it to a local variable, there won't be any problems.


text:
Q: soup.find_all and find_elements_by_class return no elements found I have tried two methods to find betting odd values with no results. I get nothing.
Here's the code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import pandas as pd

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://www.optibet.lv/sport/wcg/CS:GO-5541")

odds = driver.find_elements_by_class('event-block-row__odd event-block-row__odd_clickable event-block-row__odd_without-middle-odd')

if odds is not None:
    print('found odds element')
    print(odds)

This didn't work. It just prints 'found odds element'. I then tried to change the class name to odds = driver.find_elements_by_class('odd__value') to no avail.
After that I tried to use BeautifulSoup:
from selenium import webdriver
from bs4 import BeautifulSoup

url = "https://www.optibet.lv/sport/wcg/CS:GO-5541"
driver = webdriver.Chrome()
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')

containers = soup.find_all("div", class_="event-block-row__odd event-block-row__odd_clickable event-block-row__odd_without-middle-odd")
print (len(containers))

This returns '0'. I'm out of ideas and not very experienced. Any help?

A: Switch to the iframe prior to getting the class. Then loop the list.
driver.get("https://www.optibet.lv/sport/wcg/CS:GO-5541")
driver.implicitly_wait(10)
driver.switch_to.frame(driver.find_element_by_css_selector("#iFrameResizer0"))
odds = driver.find_elements_by_class_name('odd__value')

if odds is not None:
    print('found odds element')
    for odd in odds:
        print(odd.text)

A: Many sites have a scraper protection and in a second place your site is very heavy. You can try this but BeautifulSoup has limitations:
from bs4 import BeautifulSoup
import urllib.request
import bs4 as bs

url_1 = 'https://www.optibet.lv/sport/wcg/CS:GO-5541'
sauce_1  = urllib.request.urlopen(url_1).read()
soup_1 = bs.BeautifulSoup(sauce_1, 'lxml')

for table in soup_1.find('div', class_='event-block-row__odd event-block-row__odd_clickable event-block-row__odd_without-middle-odd'):
    print(table.text)


text:
Q: Getting database error while using django-paypal Im using Mongodb (djongo engine) for the database for my django project, I can't work out I always get this error when paypal posts to my website:
    [13/Dec/2021 15:59:44] "POST /paypal/ HTTP/1.1" 500 28196
Internal Server Error: /paypal/
Traceback (most recent call last):
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse
    return handler(self, statement)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 933, in _select
    return SelectQuery(self.db, self.connection_properties, sm, self._params)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 116, in __init__
    super().__init__(*args)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__
    self.parse()
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 152, in parse
    self.where = WhereConverter(self, statement)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\converters.py", line 27, in __init__
    self.parse()
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\converters.py", line 119, in parse
    self.op = WhereOp(
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 475, in __init__
    self._statement2ops()
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 428, in _statement2ops
    op = self._token2op(tok, statement)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 405, in _token2op
    op = ParenthesisOp(SQLStatement(tok), self.query)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 493, in __init__
    self._statement2ops()
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 428, in _statement2ops
    op = self._token2op(tok, statement)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 405, in _token2op
    op = ParenthesisOp(SQLStatement(tok), self.query)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 493, in __init__
    self._statement2ops()
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 438, in _statement2ops
    if prev_op.lhs is None:
AttributeError: 'NoneType' object has no attribute 'lhs'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\cursor.py", line 51, in execute
    self.result = Query(
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__
    self._query = self.parse()
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 885, in parse
    raise exe from e
djongo.exceptions.SQLDecodeError:

        Keyword: None
        Sub SQL: None
        FAILED SQL: SELECT "paypal_ipn"."id", "paypal_ipn"."business", "paypal_ipn"."charset", "paypal_ipn"."custom", "paypal_ipn"."notify_version", "paypal_ipn"."parent_txn_id", "paypal_ipn"."receiver_email", "paypal_ipn"."receiver_id", "paypal_ipn"."residence_country", "paypal_ipn"."test_ipn", "paypal_ipn"."txn_id", "paypal_ipn"."txn_type", "paypal_ipn"."verify_sign", "paypal_ipn"."address_country", "paypal_ipn"."address_city", "paypal_ipn"."address_country_code", "paypal_ipn"."address_name", "paypal_ipn"."address_state", "paypal_ipn"."address_status", "paypal_ipn"."address_street", "paypal_ipn"."address_zip", "paypal_ipn"."contact_phone", "paypal_ipn"."first_name", "paypal_ipn"."last_name", "paypal_ipn"."payer_business_name", "paypal_ipn"."payer_email", "paypal_ipn"."payer_id", "paypal_ipn"."auth_amount", "paypal_ipn"."auth_exp", "paypal_ipn"."auth_id", "paypal_ipn"."auth_status", "paypal_ipn"."exchange_rate", "paypal_ipn"."invoice", "paypal_ipn"."item_name", "paypal_ipn"."item_number", "paypal_ipn"."mc_currency", "paypal_ipn"."mc_fee", "paypal_ipn"."mc_gross", "paypal_ipn"."mc_handling", "paypal_ipn"."mc_shipping", "paypal_ipn"."memo", "paypal_ipn"."num_cart_items", "paypal_ipn"."option_name1", "paypal_ipn"."option_name2", "paypal_ipn"."option_selection1", "paypal_ipn"."option_selection2", "paypal_ipn"."payer_status", "paypal_ipn"."payment_date", "paypal_ipn"."payment_gross", "paypal_ipn"."payment_status", "paypal_ipn"."payment_type", "paypal_ipn"."pending_reason", "paypal_ipn"."protection_eligibility", "paypal_ipn"."quantity", "paypal_ipn"."reason_code", "paypal_ipn"."remaining_settle", "paypal_ipn"."settle_amount", "paypal_ipn"."settle_currency", "paypal_ipn"."shipping", "paypal_ipn"."shipping_method", "paypal_ipn"."tax", "paypal_ipn"."transaction_entity", "paypal_ipn"."auction_buyer_id", "paypal_ipn"."auction_closing_date", "paypal_ipn"."auction_multi_item", "paypal_ipn"."for_auction", "paypal_ipn"."amount", "paypal_ipn"."amount_per_cycle", "paypal_ipn"."initial_payment_amount", "paypal_ipn"."next_payment_date", "paypal_ipn"."outstanding_balance", "paypal_ipn"."payment_cycle", "paypal_ipn"."period_type", "paypal_ipn"."product_name", "paypal_ipn"."product_type", "paypal_ipn"."profile_status", "paypal_ipn"."recurring_payment_id", "paypal_ipn"."rp_invoice_id", "paypal_ipn"."time_created", "paypal_ipn"."amount1", "paypal_ipn"."amount2", "paypal_ipn"."amount3", "paypal_ipn"."mc_amount1", "paypal_ipn"."mc_amount2", "paypal_ipn"."mc_amount3", "paypal_ipn"."password", "paypal_ipn"."period1", "paypal_ipn"."period2", "paypal_ipn"."period3", "paypal_ipn"."reattempt", "paypal_ipn"."recur_times", "paypal_ipn"."recurring", "paypal_ipn"."retry_at", "paypal_ipn"."subscr_date", "paypal_ipn"."subscr_effective", "paypal_ipn"."subscr_id", "paypal_ipn"."username", "paypal_ipn"."mp_id", "paypal_ipn"."case_creation_date", "paypal_ipn"."case_id", "paypal_ipn"."case_type", "paypal_ipn"."receipt_id", "paypal_ipn"."currency_code", "paypal_ipn"."handling_amount", "paypal_ipn"."transaction_subject", "paypal_ipn"."ipaddress", "paypal_ipn"."flag", "paypal_ipn"."flag_code", "paypal_ipn"."flag_info", "paypal_ipn"."query", "paypal_ipn"."response", "paypal_ipn"."created_at", "paypal_ipn"."updated_at", "paypal_ipn"."from_view" FROM "paypal_ipn" WHERE ("paypal_ipn"."txn_id" = %(0)s AND NOT ("paypal_ipn"."id" IS NULL) AND NOT ("paypal_ipn"."flag")) ORDER BY "paypal_ipn"."created_at" DESC LIMIT 1
        Params: ('5JV347551H953243B',)
        Version: 1.3.6

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\cursor.py", line 59, in execute
    raise db_exe from e
djongo.database.DatabaseError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\views\decorators\http.py", line 40, in inner
    return func(request, *args, **kwargs)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\paypal\standard\ipn\views.py", line 101, in ipn
    ipn_obj.verify()
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\paypal\standard\models.py", line 362, in verify
    if duplicate_txn_id(self):
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\paypal\standard\helpers.py", line 34, in duplicate_txn_id
    if len(similars) > 0:
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\models\query.py", line 262, in __len__
    self._fetch_all()
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\models\query.py", line 51, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\backends\utils.py", line 79, in _execute
    with self.db.wrap_database_errors:
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\utils.py",
line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\cursor.py", line 59, in execute
    raise db_exe from e
django.db.utils.DatabaseError

Any ideas how I can fix this, it happens when I try to migrate as well
a note my ipn signals are also not firing but paypal can succesfully redirect to my payment failed or payment successful pages


text:
Q: How to solve transfer function of a bandpass filter with Butterworth approximation? How can I calculate the transfer function of this bandpass filter characteristic with Butterworth approximation?

*

*\$A_{max}\$ = 0,9 dB

*\$A_{min}\$ = 6,5 dB

*\$\omega\$3 = 100

*\$\omega\$1 = 300

*\$\omega\$2 = 1100

*\$\omega\$4 = 3300

Which steps do I have to take and what are some good resources for learning these kinds of filter design problems?

A: Volki, be aware that the design will be rather involved.
Here is a short summary of the main steps (active filter design):

*

*Based on the given values (center frequency, bandwidth, midband gain, attenuation values) you must use existing formulas for the bandpass-lowpass transformation. As a result, you have corresponding lowpass requirements and you can calculate the corresponding lowpass order (n=2,3,..).

*Applying again corresponding equations you can transform the lowpss poles back to the bandpass poles.

*Now you have two alternatives for pole allocation (depending on the required filter order):

*

*Series connection of active lowpass and highpass sections

*Active bandpass stage (or series connection of several stages).

For passive topologies, you must rely on filter catalogues. In any case - I strongly recommend to make use from filter design programs which are available. For example:
Passive: AADE;
Active: Filter Free, FilterLab, FilterPro


text:
Q: tshark - filtering by webservice's name I'm trying to use tshark to record each request sent to a WebService called myservice.
When I use below command, I can see in output file every request sent on port 8280 (Tomcat) :
tshark -n -i eth1 port 8280 -w output.pcap

Considering I have a lot of WebServices in that Tomcat instance, I would like to filter by service name, something like that :
tshark -n -i eth1 port 8280 -w output.pcap -R 'http.request.uri contains "myservice"'

According to man, it looks like I should rather use -f (capture filter) than -R (display filter) since you can't use -R with -w :

tshark: Read filters aren't supported when capturing and saving the captured packets.

I took a look at documentation about capture filters but I can't see a way to do that. I also tried with tcpdump without success.

A: You can use ngrep for this
sudo ngrep -O output.pcap -i -d eth0 'myservice'

Although you might get some false positive depending on whether or not 'myservice' is found on an irrelevant packet that was not intended for your application. To avoid this, you might want to apply a bpf filter to grep only traffic that was directed to your service/app
sudo ngrep -O output.pcap -i -d eth0 'myservice' 'tcp dst port 8280'


text:
Q: How to resize root partition on aws ec2 rhel7 ami? I created a t2.micro instance from rhel7 ami-f7f03d80 ami, with a 39gb gp2 xfs_ebs storage, and have a 6gb / xfs filesystem, and a 24gb of free space. I am trying to use xfs_growfs -d / for resizing a partition, and it says data size unchanged, skipping. when i'm specifying -D 2572864 to xfs_growfs, it says data size 2572864 too large, maximum is 1572864. looks like i need to resize a partition first, and then resize a filesystem, but i can't do that on a mounted fs. I could pack fdisk and xfs_growfs to initrd, and boot from it, but it seems too hard) It seems like i missed something, and it could be done other way. Thanks.

A: It'll feel a little scary (take a snapshot first) but:
fdisk /dev/YOURDEVICE

delete your partition, create a new partition taking the whole disk, write changes, reboot.
You should see the whole drive after that.

A: I have incressed my root partion space by gdisk on RHEL 7
1) yum -y install gdisk
2) sudo gdisk /dev/xvda
Delete all the partions
3)
Command (? for help): o
This option deletes all partitions and creates a new protective MBR.
Proceed? (Y/N): Y
4)
Use the n command to create a new partition entry for each partition on the device.
Command (? for help): n
Partition number (1-128, default 1): 1
First sector (34-209715166, default = 2048) or {+-}size{KMGTP}:  2048
Last sector (2048-209715166, default = 209715166) or {+-}size{KMGTP}: 4095
Current type is 'Linux filesystem'
Hex code or GUID (L to show codes, Enter = 8300): EF02
Changed type of partition to 'BIOS boot partition'
Command (? for help): n
Partition number (2-128, default 2): 2
First sector (34-209715166, default = 4096) or {+-}size{KMGTP}: 4096
Last sector (4096-209715166, default = 209715166) or {+-}size{KMGTP}: 209715166
Current type is 'Linux filesystem'
Hex code or GUID (L to show codes, Enter = 8300): 0700
Changed type of partition to 'Microsoft basic data'
5) Use the w command to write the changes to the device and exit.

Expert command (? for help): w
Final checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING
PARTITIONS!!
Do you want to proceed? (Y/N): Y
OK; writing new GUID partition table (GPT) to /dev/xvda.
The operation has completed successfully.
6) Reboot the system
7) After reboot you can see your /root partion size increassed


text:
Q: Why is my WPF Validation Error not getting displayed? I have defined a control template for showing Validation Errors:
<ControlTemplate x:Key="validationTemplate">
                    <DockPanel LastChildFill="True">
                        <TextBlock DockPanel.Dock="Right"
                                   Background="Red"
                                   TextWrapping="Wrap">
                            <TextBlock.Text>
                                <Binding Path="(Validation.Errors)[0].ErrorContent"
        RelativeSource="{x:Static RelativeSource.Self}">
                                </Binding>
                            </TextBlock.Text>
                        </TextBlock>
                        <AdornedElementPlaceholder ></AdornedElementPlaceholder>
                    </DockPanel>
</ControlTemplate>

I have defined a TextBox as follows:
<TextBox Text="{Binding Text}" PreviewTextInput="textBox1_PreviewTextInput"
      Validation.ErrorTemplate="{StaticResource validationTemplate}" />

I am setting the validation from code behind as follows:
    private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        TextBox txtBox = (TextBox)sender;
     ....
     ....

     ValidationError validationError = new ValidationError(new DummyValidator(),
            txtBox.GetBindingExpression(TextBox.TextProperty));
        Validation.MarkInvalid(txtBox.GetBindingExpression(TextBox.TextProperty), validationError);
        validationError.ErrorContent = "This is wrong input";
        e.Handled = true;
    }

Now the problem is The Validation is getting fired and a red strip is shown but the error message inside that is not getting displayed!!
May be I am wrong with this  It is throwing some exception in console (index out of bounds exception)
<Binding Path="(Validation.Errors)[0].ErrorContent"
        RelativeSource="{x:Static RelativeSource.Self}">

Please guide me regarding Where am I going wrong?

A: <Binding Path="(Validation.Errors)[0].ErrorContent"
    RelativeSource="{x:Static RelativeSource.Self}">

Your RelativeSource is wrong
<Binding Path="(Validation.Errors)[0].ErrorContent"
    RelativeSource="{RelativeSource Self}">


text:
Q: How to encode NDEF message This is the first time, I am working NFC based feature. I am facing a problem regarding encoding NDEF message.
we tried 2 apps to write data into NFC tag, names are NDEF and TagWriter. I am writing my data into text format.This is what my data
{name:myTag,tagDetails:{name:"myOrganization",addess:"xxxxx"}}

What I understand, both apps are encoding and injecting data into tag.The problem was while reading time.
Once I read tag, I am converting bytes to String like nfcEvent.tag.ndefMessage[0].payload.
What are the tags written by NDEF App, after converting exact data coming what I written into tag.
The problem with TagWritter, After converting this tags data, it's coming in this format.
 "en"{name:myTag,tagDetails:{name:"myOrganization",addess:"xxxxx"}}""

Regarding this, I did some research What I found TagWritter App converting data into UTF-8 format.
I think because of this it's happening. may be I might wrong.
how can I solve this issue.
Note : I am using Apache cordova to build android application.
Thanks.

A: If you see something like "en" (actually a non-pritable character + a language code) prepended to your data, this suggests that your tag writer app placed the text string into an NFC Forum Text record (you can get the specification from the NFC Forum's website).
The record consists of a status byte, a language code (in US-ASCII) followed by the actual text. The upper bit (b7) of the status byte indicates if the text is encoded in UTF-8 (b7 = 0) or UTF-16 (b7 = 1). The lower 6 bits (b5..0) indicate the length of the language code in bytes.
So as long as the language code is 2 bytes, your solution of trimming the first three bytes will work.
However, the NFC Forum Text record type is specifically intended for human-readable text and you should probably avoid using it to store JSON objects. It would be better to use an NFC Forum external type record (or a custom MIME type record) to store your data.

A: I seen the plugin documentation,what I am using to read(chariotsolutions/phonegap-nfc). They itself suggesting to remove unnecessary characters. So we have to write code thi format.
   nfc.bytesToString(nfcEvent.tag.ndefMessage[0].payload).substring(3);

This is the link, I seen


text:
Q: Direction of current using superposition method I have to calculate the current I and the voltage between a and b using the superposition theorem.
I can solve this directly by calculating the voltage between points, but I have to do it with that theorem. Problem is that I can't figure out where does the current go in each case (shorting the $6V$ source or the $20V$ source), and everything I've tried gives me the wrong results.
If I short the $20V$ source, I'm pretty sure the current goes up from the $6V$ source, then right past the $5 \ \Omega$ resistor, then clockwise through the short circuit, then passes from $b$ to $a$ through the $2 \ \Omega$ resistor and back to the $6 V$ source. So I calculate the current as $ I'=\frac{6 V}{2 \Omega}=3A $ and $ V_{ab} = 6 V $. Easy but not sure if correct.
Now when I short the $6V$ source instead, I think the current goes down from the source, then to the right, then counterclockwise right past the $5 \ \Omega$ resistor, down to the node $a$, where it splits in two: one part goes through the $2 \ \Omega$ resistor and then reaches the source through the negative side, while the other part goes through the $3 \ \Omega$ resistor and then reaches the source through the positive side. Is this correct? I tried to apply Kirchhoff's laws but I got the wrong result (I need $I''$ to be equal to $12 A$ so that $ I = 12A - 3A = 9A $, which is the correct result).
It's been a long time since I last saw this topic, I may be too rusty and overlooking something trivial.

Edit: I drew the paths of the current I described above: when the $20V$ source is shorted on the left, and when the $6V$ source is shorted on the right. If I understand correctly, the current will go through the short circuit only whenever there is another branch.

A: Where you are going wrong is trying to intuit the direction of unknown currents and then write the equations as such without having the math figure it for you. But this basically requires you to already know what is going in the circuit. You should be using a consistent, formulaic approach like nodal or mesh analysis and then keeping your sign conventions consistent.
Write your nodal or mesh equations for both versions of the circuit assuming the same current directions for unknown currents in both cases.
UPDATE after loop drawings added:
You don't draw loops like that. The way you drew the loops makes it seem like you think you can solve for only the parts of the circuit you care about. You can't do that since every part of the circuit affects every other part. You need to solve for the entire circuit and then pick out what you want.
Every part of your circuit must be taken into account by your equations. Every loop has an equation associated with it. These MULTIPLE loop equations, for each version of the circuit, are then solved simultaneously.
Each version of your circuit requires 3 loops and 3 equations. Loops need not be independent, and if convenient (or sometimes necessary), smaller loops may be enclosed in larger loops (aka supermeshes). But you need every part of the circuit to be accounted for somewhere.
It seems as though you've completely forgotten mesh analysis so I advise you to look up simple two-loop examples and review their solutions. If there is only one source in those examples, do not simplify resistors to solve. If there are two sources, you need not use superposition. I mean...you can use superposition but you don't need to. You can do it all with one set of loop equations (which you can also do in your problem). It should come back flooding to you unless you haven't touched it for 30 years.

A: The problem lies on your second picture. Teh current has also splitted in the $5\Omega$ resistor, so the current that arrives to point $a$ is smaller. Then, at point $A$ it splits again.


text:
Q: Converse of the one-dimensional maximum principle If a positive function $u:[0,1]\to \mathbb{R}^+$ is known to be continuous and twice differentiable, and to have no local maxima in $(0,1)$ (i.e. $u$ is maximised on the boundary $\{0,1\}$), is it possible to find bounded $g(x)$ and negative $h(x)$ such that the one-dimensional maximum principle applies
$$u''+g(x)u'+h(x)u\geq 0$$
and if so, is there a way to construct such $g,h$?

A: No, in general this is not possible. If $u$ has a critical point $x_0$ with $u'(x_0) = u''(x_0) = 0$, then the left-hand side at $x_0$ is $h(x_0)u(x_0)<0$. As an example, take $u(x) = 1 + (x-1/2)^3$ and $x_0 = 1/2$.
However, if all critical points are non-degenerate, then your assumption implies that $u''(x_0)>0$ for every $x_0$ with $u'(x_0) = 0$. In this case you can take $g(x) = C u'(x)$ for a large constant $C>0$, and $h(x) = -\epsilon$ for a small constant $\epsilon > 0$ and check that the condition is satisfied.


text:
Q: ERROR: Content Element type "templavoila_pi1" has no rendering definition I had an issue with CSS styled content on my typo3 site. This is why I disabled CSC, enabled it again and included the static template.
However now I am getting the error message: "ERROR: Content Element type "templavoila_pi1" has no rendering definition!"
I found out that the error message does only appear when I am using flexible content elements. On pages without flexible content elements there is no errow message...
This is the site: http://web182.theta.ibone.ch/vbl/home.html

A: The problem here is not CSC, it's TemplaVoilà. It seems as if the static template of TemplaVoila is not included or the ordering is wrong. It should be:

*

*CSS Styled Content

*(Static Info Tables)

*TemplaVoilà

Please check this in your root TS template.

A: I installed TemplaVoila again (without uninstalling) and now it works...


text:
Q: Why /etc/portage/package.use lines do not work installing Openshot? On Funtoo Linux I has no sense how to solve requirements. I added lines but again and again I cannot run openshot installation
 # tail -n 5 /etc/portage/package.use
>=x11-libs/libXcursor-1.1.14 abi_x86_32

>=media-video/openshot-2.2.0 dbus opengl svg gui network printsupport widgets opengl webkit sql positioning webchannel python_targets_python3_4
>=dev-python/PyQt5-5.8.2 dbus opengl svg python_targets_python3_4

 # emerge openshot
Calculating dependencies... done!

!!! The ebuild selected to satisfy "dev-python/PyQt5[svg,webkit,python_targets_python3_4(-)?,python_targets_python3_5(-)?,-python_single_target_jython2_7(-),-python_single_target_pypy(-),-python_single_target_pypy3(-),-python_single_target_python2_7(-),-python_single_target_python3_6(-),python_single_target_python3_4(+)?,python_single_target_python3_5(+)?]" has unmet requirements.
- dev-python/PyQt5-5.8.2::python-kit USE="dbus opengl svg -bluetooth -debug -declarative -designer -doc -examples -gles2 -gui -help -location -multimedia -network -positioning -printsupport -sensors -serialport -sql -testlib -webchannel -webengine -webkit -websockets -widgets -x11extras -xmlpatterns" PYTHON_TARGETS="python2_7 python3_4 -python3_5 -python3_6"

  The following REQUIRED_USE flag constraints are unsatisfied:
    opengl? ( gui widgets ) svg? ( gui widgets ) webkit? ( gui network printsupport widgets )

  The above constraints are a subset of the following complete expression:
    any-of ( python_targets_python2_7 python_targets_python3_4 python_targets_python3_5 python_targets_python3_6 ) bluetooth? ( gui ) declarative? ( gui network ) designer? ( widgets ) help? ( gui widgets ) location? ( positioning ) multimedia? ( gui network ) opengl? ( gui widgets ) positioning? ( gui ) printsupport? ( gui widgets ) sensors? ( gui ) serialport? ( gui ) sql? ( widgets ) svg? ( gui widgets ) testlib? ( gui widgets ) webchannel? ( network ) webengine? ( network widgets? ( webchannel ) ) webkit? ( gui network printsupport widgets ) websockets? ( network ) widgets? ( gui ) xmlpatterns? ( network )

(dependency required by "media-video/openshot-2.2.0::media-kit" [ebuild])
(dependency required by "openshot" [argument])

Please. I've read manuals but I cannot understand what to do.

A: Try this:
Edit /etc/portage/package.use
and add gui network printsupport widgets:
dev-python/PyQt5 svg webkit gui network printsupport widgets


text:
Q: Having problems running script getting error: if event.type == pygame.QUIT: syntax Error So I'm following this tutorial:
https://www.youtube.com/watch?v=Vg83OtRkevE
and  I've done everything the  tutorial told me to but I'm still getting this error message when I run it:
if event.type == pygame.QUIT:

syntax Error

(this was made in repl.it)
my code is:
import sys

WIN_WIDTH = 800
WIN_HEIGHT = 600
TILESIZE = 32
FPS = 60

class Spritesheet:
  def __init__(self, file):
    self.sheet = pygame.image.load(file).convert()

    def get_sprite(self, x, y, width, height):
      sprite = pygame.Surface([width, height])
      sprite.blit(self.sheet, (0, 0), (x, y, width, height))
      return sprite

class Ground(pygame.sprite.sprite):
  def __init__(self, game, x, y):
    self.game = game
    self._layer  = 1
    self.groups = self.game.all_sprites
    pygame.sprite.Sprite.__init__(self, self.groups)

    self.x = x * TILESIZE
    self.y = y * TILESIZE
    self.width, self.height = TILESIZE, TILESIZE
    self.image = self.gane.terainsheet.get_sprite(0, 96, self.width, self.height)
    self.rect = self.image.get_rect()
    self.rect.x, self.rect.y = self.x, self.y

def build_map(self, tilemap):
  for i, row in enumerate(tilemp):
    for j, column in enumerate(row):
      Ground(self, j, i)

class Game:
  def __init__(self):
    self.screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    self.clock = pygame.time.Clock()
    self.running = True
    self.terrainsheet = spritesheet(('terrain1.png'))

    def createTilemap(self, tilemap):
      build_map(self, tilemap)
      def new(self, tilemap):
        self.playing = True
        self.all_sprites = pygame.sprite.LayeredUpdates()
        self.createTilemap(tilemap)

        def events(self):

          for event in pygame.event.get():
            if eve nt.type == pygame.QUIT:
            self.playing = False
            self.running = False

  def update(self):
    self.all_sprites.update()

    def draw(self):
      self.screen.fill('black')
      self.all_sprites.draw(self.screen)
      self.clock.tick(FPS)

      pygame.display.update()

  def main(self):
    while self.playing:
      self.Events()
      self.updates()
      self.draw()

    TILEMAP = [
        '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',
      '............................',

    ]
    game = game()
    game.new(TILEMAP)
    while game.running:
      game.main
      pygame.quit
      sys.exit()

At first it was some other syntax error I had to fix, If anyone is able to help please do!
I'm a newbie to pygame so sorry if my question seems stupid.

A: Python needs indentation in order to know the scope of each section (eg. if, while, for, function, etc.). Here is comprehensive guide how to do it properly: https://peps.python.org/pep-0008/. If your code is indented as in your question. There is a problem here:
          for event in pygame.event.get():
            if event.type == pygame.QUIT:  # This If is empty
            self.playing = False # this
            self.running = False # and this does not belong to that If

it must be indented according:
          for event in pygame.event.get():
            if event.type == pygame.QUIT:
              self.playing = False
              self.running = False


text:
Q: Animate ListView item to full screen in Flutter I would like to have my list items perform this animation (mp4) when tapped. I tried using AnimatedCrossFade but it requires its two children to be at the same level, e.g. the detail view cross-fades with the ListView not the tapped item. In fact it seems a Hero animation is the only one that can animate across widgets.
I'm having trouble using Hero. Should it wrap the list item? Does it matter if the Widget subtree is significantly different in the Hero source/destination? Also, can Hero animations be used with LocalHistoryRoutes or staggered animations?
Edit
It's now looking like what I need to do is use an Overlay, the hard part there is that I need to add the selected item to the overlay at the same position on screen where it was tapped, then the animation part would be easy. Possibly of use here is a target/follower pattern e.g. CompositedTransformTarget

A: You can just use Hero widget to make that kind of animation. Here's my example:

and the source code:
import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new FirstPage(title: 'Color Palette'),
    );
  }
}

class FirstPage extends StatefulWidget {
  FirstPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _FirstPageState createState() => new _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  final palette = [
    {'#E53935': 0xFFE53935},
    {'#D81B60': 0xFFD81B60},
    {'#8E24AA': 0xFF8E24AA},
    {'#5E35B1': 0xFF5E35B1},
    {'#3949AB': 0xFF3949AB},
    {'#1E88E5': 0xFF1E88E5},
    {'#039BE5': 0xFF039BE5},
    {'#00ACC1': 0xFF00ACC1},
    {'#00897B': 0xFF00897B},
    {'#43A047': 0xFF43A047},
    {'#7CB342': 0xFF7CB342},
    {'#C0CA33': 0xFFC0CA33},
  ];

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Container(
        child: new ListView.builder(
            itemCount: palette.length,
            itemBuilder: (context, index) => new Hero(
                  tag: palette[index].keys.first,
                  child: new GestureDetector(
                    onTap: () {
                      Navigator
                          .of(context)
                          .push(new ColorPageRoute(palette[index]));
                    },
                    child: new Container(
                      height: 64.0,
                      width: double.infinity,
                      color: new Color(palette[index].values.first),
                      child: new Center(
                        child: new Hero(
                          tag: 'text-${palette[index].keys.first}',
                          child: new Text(
                            palette[index].keys.first,
                            style: Theme.of(context).textTheme.title.copyWith(
                                  color: Colors.white,
                                ),
                          ),
                        ),
                      ),
                    ),
                  ),
                )),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  final Map<String, int> color;

  SecondPage({this.color});

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Color'),
      ),
      body: new Hero(
        tag: color.keys.first,
        child: new Container(
          color: new Color(color.values.first),
          child: new Center(
            child: new Hero(
              tag: 'text-${color.keys.first}',
              child: new Text(
                color.keys.first,
                style:
                    Theme.of(context).textTheme.title.copyWith(color: Colors.white),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class ColorPageRoute extends MaterialPageRoute {
  ColorPageRoute(Map<String, int> color)
      : super(
            builder: (context) => new SecondPage(
                  color: color,
                ));

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation, Widget child) {
    return FadeTransition(opacity: animation, child: child);
  }
}

A: Someone wrote an amazing dart-package for just this purpose: https://pub.dev/packages/morpheus#-readme-tab-
All you then need to do is use the MorpheusPageRoute and the package handles the rest.
...
Navigator.push(
  context,
  MorpheusPageRoute(
    builder: (context) => MyWidget(title: title),
  ),
);
...

A: I'd just cheat and wrap the whole thing in a Stack - bottom layer would be a page with the AppBar, and the top layer would be transparent until painted on.
onTap, duplicate ListTile onto the top surface, and then a Hero animation would fill the full screen.  It's not very elegant, but the framework  doesn't (yet) provide for covering the AppBar easily, so having a canvas ready to be painted on for other tricky animations might be resourceful.

A: I'm unable to comment or edit Lucas' post (new account) but you also need to provide the parentKey of the widget where the animation is to begin:
final widgetKey = GlobalKey();
...
ListTile(
  key: widgetKey,
  title: Text('My ListItem'),
  onTap: () => Navigator.push(
    context,
    MorpheusPageRoute(
      builder: (context) => MyNewPage(),
      parentKey: widgetKey,
    ),
  ),
),

https://pub.dev/packages/morpheus


text:
Q: Python - Accept input from bash and send by query string I am new to Python and trying to my script to send the output of this command 'ibeacon_scan -b' to be sent to a web server by query string or any other efficient way to send data continuously. Here is what the output looks like for 'ibeacon_scan -b'
iBeacon Scan ...
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 1 4 -71 -69
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 6 2 -71 -63
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 1 4 -71 -69
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 5 7 -71 -64
...keeps updating

I am piping the command to my Python script
ibeacon scan -b | stdin.py

Here is my code for the my script 'stdin.py'
#!/usr/bin/python
import fileinput
import httplib
import urllib

for line in fileinput.input():
   urllib.urlencode({"UUID": {"Major":{"Minor":RSSI}}})
   headers = {"Content-type": "application/x-www-formurlencoded","Accept": "text/plain"}
   conn = httplib.HTTPConnection("67.205.14.22")
   conn.request("POST", "post.php", params, headers)
   response = conn.getrespone()
   print response.status, respone.reason
   data = respone.read()
   print data
   conn.close()

I'm getting these errors.
Traceback (most recent call last):
  File "./stdin.py", line 7, in <module>
    for line in fileinput.input():
  File "/usr/lib/python2.7/fileinput.py", line 253, in next
    line = self.readline()
  File "/usr/lib/python2.7/fileinput.py", line 346, in readline
    self._buffer = self._file.readlines(self._bufsize)
KeyboardInterrupt

Is my script even getting the data correctly from the pipe? Is the formatting correct for the query string?

A: As @TheSoundDefense pointed, it must be some KeyboardInterrupt character in the ibeacon's output:
A fast check shows that piping in linux actually works:
>>> cat tmp.txt | python -c "import fileinput; print [line for line in fileinput.input()]"
['a\n', 'b\n', 'c\n', 'd\n']

Where tmp.txt contains 4 lines with a, b, c and d.

A: Do you need to have it pipe in? Because if not, you can do something like this all in your python script (thanks oliver13 for the idea):
popen = subprocess.Popen(["ibeacon scan -b"], stdout=subprocess.PIPE)
for line in iter(popen.stdout.readline, ""):
   urllib.urlencode({"UUID": {"Major":{"Minor":RSSI}}})
   headers = {"Content-type": "application/x-www-formurlencoded","Accept": "text/plain"}
   conn = httplib.HTTPConnection("67.205.14.22")
   conn.request("POST", "post.php", params, headers)
   response = conn.getrespone()
   print response.status, respone.reason
   data = respone.read()
   print data
   conn.close()