text:
Q: PHP Loop not working for CSV output using MySQL variable I created a variable from a MySQL query that gives a total number value of photos available for a record. This along with a few other variables from the query I can use to construct a dynamic URL in a CSV file I am exporting.
This works great:
  foreach($rowr as $name => $value)

  {
      if($name=='MatrixImage') {$jpg_name=$value;}
      if($name=='PhotoCount') {$count_name=$value;}
      if($name != 'estate_property_gallery')
            $csv_output .= $value."|";

      if($name == 'estate_property_gallery')
    {
      $csv_output .= "http://url/feeds/".$value."/rets_images/".$jpg_name."_".$count_name.".jpg";
    }

  }

I need to be able to loop through and create multiple URLs using this PhotoCount variable starting from 1 to the final value found in PhotoCount seperated by a comma but I can't seem to get it right.
Not working:
  foreach($rowr as $name => $value)

  {
      if($name=='MatrixImage') {$jpg_name=$value;}
      if($name=='PhotoCount') {$count_name=$value;}
      if($name != 'estate_property_gallery')
            $csv_output .= $value."|";

      if($name == 'estate_property_gallery')
    {
      //$csv_output .= "http://url/feeds/".$value."/rets_images/".$jpg_name."_".$count_name.".jpg";
      for( $pic_start=1; $pic_start<=$count_name; $pic_start++ ){
    echo '$csv_output .= "http://url/feeds/' . $value . '/rets_images/' . $jpg_name . '_' . $pic_start . '.jpg,"';
}
    }

  }

The example above outputs the entire line including the $csv_output to the screen instead of putting each URL into the column of the CSV and delimiting with a comma.
To clarify: I need to be able to write this echo into the $csv_output .= portion of the code successfully so I can write multiple URLs separated by a comma within that column in my csv output:
echo 'http://www.myagentsbuddy.com/feeds/' . $value . '/rets_images/' . $jpg_name . '_' . $count_name . '.jpg';

A: If the first example you showed works great, and does not include an echo, and the second example you showed (with an echo) does not work, it seems like it could be fixed by removing the echo and going back to just appending the URLs to the $csv_output like you're doing in the working example.
if($name == 'estate_property_gallery') {
    $comma = '';
    for( $pic_start=1; $pic_start<=$count_name; $pic_start++ ) {
        $csv_output .= $comma.'http://url/feeds/'.$value.'/rets_images/'
                      .$jpg_name.'_'.$pic_start.'.jpg';
        // doing the comma like this will prevent a trailing comma after the last entry
        $comma = ',';
    }
}


text:
Q: How to terminate a thread from threadpoolexecutor that import another python file? The code defines a function that import another file using importlib. And I want to import multiple files using for loops and making all imports as threads, but I came into the problem of killing those threads.
Here's my main file:
from concurrent import futures
import importlib
thread_pool_executor = futures.ThreadPoolExecutor(max_workers=10)
def flexable_import(file):
    importlib.import_module(file)
file_list = ["file1","file2","file3"]
pool_list = []
for filename in file_list:
    pool_list.append(thread_pool_executor.submit(flexable_import,filename))
for i in range(len(pool_list)):
    #I want some code that can alternate the self.terminate in a class attribute from another file in another thread

Here's an example of a imported file in a thread:
import time
class SomeClass:

    def __init__(self):
        self.terminate = False #flag variable
        self.run()

    def run(self):
        while True:
            #some operation
            time.sleep(1)
            if self.terminate:
                return

a = SomeClass()

I wonder if there's a way to change a class attribute from another thread that imports another file, or if there's another way to staight up kill a future object. Thank you!

A: You need to change your design.  Define your interface so that every add-in module has a function with a known name.  Consider:
import time
class SomeClass:
    def __init__(self):
        self.terminate = False #flag variable
        self.run()

    def run(self):
        while True:
            #some operation
            time.sleep(1)
            if self.terminate:
                return

def execute():
    return SomeClass()

Now you can do:
addins = []
def flexable_import(file):
    mod = importlib.import_module(file)
    addins.append( mod.execute() )

def stop_it():
    for o in addins:
        o.terminate = True

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using vs Utilizing My question is, which of the below sentences is more correct?

*

*1) Precise Mapping Using Unmanned Aerial Vehicle (UAV) data.

*2) Precise Mapping Utilizing Unmanned Aerial Vehicle (UAV) data.

And,

*

*1) Modern mapping utilizing laser scanners.

*2) Modern mapping using laser scanners.

I know both are correct, but as it would be a Thesis title, so in my opinion here as I am using a Sensor or Machine, therefore utilizing looks more correct, but I need to be sure about it.

A: Using.
If there is a difference it is presumably that use means make use of while utilize means make useful, i.e. turn something into a tool.
But the overlap in the Venn diagram you could draw for those meanings would be large. Many things become useful the moment you use them.
That, combined with popular hypercorrection of use to utilize (i.e. using the longer word for a perceived improvement over the shorter one), has made their current usage nearly indistinguishable.
But it's actually usually a safe bet that use will work, and it's much easier to say and write even if it's only a threepenny word.


text:
Q: Evaluate the complex integral $\int_C\ \frac{e^z}{(z-1)(z-2)}dz$ in $|z-1-i|<2$. The integral in question is

$$\int_C\ \frac{e^z}{(z-1)(z-2)}dz$$
  Where $C$ is a circle with radius $2$ centered at $1+i$.

Sketch: The key idea is use partial fraction decomposition and apply cauchy integral to each summands
Attempt:
After decomposition we obtained
$\int_C \frac{e^z}{z-2}dz - \int_C \frac{e^z}{z-1}dz$
Apply Cauchy integral to each seperate integral and we obtain $2\pi i(e^2-e)$
I want to check if my attempt is correct (please point out my mistakes if I made any),
also there is a follow up question where the integral is the same, just that $C$ is a circle centered at 0 with radius 3. Using the same argument I arrived at the same answer, is that correct ?


text:
Q: Can't vertically align text in animated div I am trying to get my header that shrinks when I scroll to display my text vertically centered. For the life of me, I can't figure it out for some reason.
Here is a link to the site http://work.nickmoyer.net. I am using Bootstrap 3. I know it is something stupid that I am overlooking but I can't put my finger on it.
Thanks for any help!
CODE BELOW
Navbar

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

            </button>

Home

Services

<a href="<?php bloginfo('url'); ?>/portfolio/" class="smoothScroll">Portfolio

<a href="<?php bloginfo('url'); ?>/blog/" class="smoothScroll">Blog

About

Contact

Javascript to make div shrink
$(function(){
  $('#header_nav').data('size','big');
});

$(window).scroll(function(){
  if($(document).scrollTop() > 0)
{
    if($('#header_nav').data('size') == 'big')
    {
        $('#header_nav').data('size','small');
        $('#header_nav').stop().animate({
            height:'30px'
        },600);
    }
}
else
  {
    if($('#header_nav').data('size') == 'small')
      {
        $('#header_nav').data('size','big');
        $('#header_nav').stop().animate({
            height:'60px'
        },600);
      }
  }
});

CSS
#header_nav .navbar-default {
    background-color:transparent !important;
    border-color:transparent !important;
}

.navbar-default {
    border-color:transparent !important;
}

#header_nav {
    width:100%;
    height:60px;
    position:fixed;
    background-color: rgb(248, 248, 248);
    top:0;
    left:0;
    z-index:10;
}

#header_nav li {
}

A: I'd do this:
http://jsfiddle.net/isherwood/Ak42Z/
$('#header_nav').stop().animate({
    height: '30px'
}, 600).find('a.smoothScroll').stop().animate({
    padding: '5px 15px 0'
}, 600);

A: This was my code when it was all said and done in the js file
$(function(){
  $('#header_nav').data('size','big');
});

$(window).scroll(function(){
  if($(document).scrollTop() > 0)
{
    if($('#header_nav').data('size') == 'big')
    {
        $('#header_nav').data('size','small');
        $('#header_nav').stop().animate({
            height: '30px'
        }, 600).find('a.smoothScroll').stop().animate({
            padding: '5px 15px 0'
        }, 600);
    }
}
else
  {
    if($('#header_nav').data('size') == 'small')
      {
        $('#header_nav').data('size','big');
        $('#header_nav').stop().animate({
            height:'60px'
        },600).find('a.smoothScroll').stop().animate({
            padding: '15px 15px 0'
        }, 600);
      }
  }
});

$

It works for me anyway!


text:
Q: Update a property in all Vertices in Gremlin I want to update the value of a property in all vertices of one label.
g.AddV('car').property('id','1').property('name','Benz')
g.AddV('car').property('id','2').property('name','BMW')
g.AddV('car').property('id','3').property('name','Audi')
g.AddV('car').property('id','4').property('name','Nissan')

Like that there are 1000s of vertices. I want to update the name value to lowercase in all those vertices. It needs to run on Azure Cosmos Graph DB.

A: Since gremlin doesn't have string manipulation functions.
And as far as I know, CosmosDb does not support lambda steps.
I think you will have to fetch all the names and ids:
g.V().has('name').project('id', 'name').by(id).by('name')

then lowercase every name in your code. and then update it like this:
g.V(id).property(single, 'name', lowercaseName)

Or all in one query:
g.inject(1).union(
.V(id1).property(single, 'name', lowercaseName1),
.V(id2).property(single, 'name', lowercaseName2)
.V(id3).property(single, 'name', lowercaseName3)
....
)

example: https://gremlify.com/pizsh5s293/1


text:
Q: "What do you do on Sundays?" vs "What are you doing on Sunday?" "What do you do on Sundays?" vs "What are you doing on Sunday?"
In the first one, the question asks what I do in general on the 7th day of the week. While in the second one, I am asked what my plans are for this upcoming Sunday.
I understand the difference in the meaning, but what grammar rule can I cite to explain why it is What do... in one and What are... in the other.

A: When forming questions, the word order is changed, an auxiliary verb is often introduced, and a question pronoun such as "what" or "who" is used.
"I do things on Sundays." is changed into "What do you do on Sundays?"  The auxilliary "do" is introduced and "things" is changed to "what."
"I am doing something on Sunday." is changed into "What are you doing on Sunday?"  The be verb "am" is changed into "are" and "something" is changed to "what."
The first sentence / question ask about regular or habitual activities.  The second is asking for a future plan or activity.  The present continuous is often used to talk about the future, and often an adverbial is added for clarity: "I am flying to New York on Sunday." or "I am cleaning my home on New Year's day."
As a side note, the use of present progressive to talk about the future started being used around Shakespeare's time.

A: What do you is clearly referring a hypothetical or unspecific time while What are you is referring to a state of being. Since the former is in-finite (non-timed), you use the infinitive verb form (do). Since the latter is with respect to a process connected to now or another specific time, you use the progressive verb form (doing).


text:
Q: Seaking a review of circuits for an Arduino driven soil moisture sensing and analysis device. AKA using caps and current sensors I am building a soil moisture sensing and analysis device and I am also a complete novice. The following diagram describes the use of an Arduino Nano Every to monitor battery voltage and current.

Can you tell me how close I am to a sound design and schematic? What kind of standards or best practices should I be following?
The current sensing part of the diagram is where my main questions lay. The circuit fragment comes from the MLX91217 Data Sheet.

What are C1 and C2 used for? What is decoupling?
When I power the circuit I get output from the current sensor but I don't know how to interpret it. The main power line that is the current source for the sensor is not in place to be read by the sensor, yet I still get output. If I place main power line in proximity to the sensor, the output does not change.

Finally, here is the code:
const unsigned int VOLTAGE_RAW_INPUT_PIN = A0;
const unsigned int CURRENT_RAW_INPUT_PIN = A1;
unsigned int VOLTAGE_READING;
unsigned int CURRENT_READING;
float VOLTAGE;
float CURRENT;

void setup() {
  Serial.begin(9600);
  pinMode(VOLTAGE_RAW_INPUT_PIN, INPUT);
  pinMode(CURRENT_RAW_INPUT_PIN, INPUT);
}

void loop() {
  VOLTAGE_READING = analogRead(VOLTAGE_RAW_INPUT_PIN);
  VOLTAGE = (VOLTAGE_READING * 0.00488281) * 2;
  CURRENT_READING = analogRead(CURRENT_RAW_INPUT_PIN);
  CURRENT = CURRENT_READING * 0.00488281;
  Serial.print("voltage: ");
  Serial.print(VOLTAGE);
  Serial.print(" | current: ");
  Serial.println(CURRENT);
  delay(2000);
}

A:
What are C1 and C2 used for? What is decoupling?

Decoupling or bypass capacitors act as filters with the wires to help 'filter' the power voltage to keep it steady when the load changes (drawing more or less current).

When I power the circuit I get output from the current sensor but I
don't know how to interpret it. The main power line that is the
current source for the sensor is not in place to be read by the
sensor, yet I still get output. If I place main power line in
proximity to the sensor, the output does not change.

Put a known voltage on the voltage line (connect the other end to board ground) like a bench supply or 1.5V battery. You should see a change to the known voltage, if you don't you might be polling the wrong ADC in the code.

A: Decoupling capacitors are used to ensure the chip has a 'clean' power supply as it might be drawing high speed peaks of current. The capacitor acts as a local 'store'. Without tge capacitor, the inductance of this power wiring might cause problems. Short answer - do what the manufacturer says.
Your pull-down resistor of 100R is way too low. The manufacturer recommends 10k at a minimum. 100R is loading down the signal.
If you are measuring AC current, then your code needs to sample the input and rectify the ADC values and average them in order to get a useful reading. This is needed as with AC, the current is constantly changing. There are examples of how to do this on the 'web. Usually it is referred to as calculating RMS.


text:
Q: perl: concatenate lines into a single string I have a file that looks something like this:
hellothisisline1
andthisisline2hi
yepthisistheline

I want to concatenate the lines so that into a single string
hellothisisline1andthisisline2hiyepthisistheline
print "Input file name \n";
open (FILE, <>);
$string = "";
while($line = <FILE>) {
   $string = $string . "" . $line;
}
print "$string \n";

But that didn't seem to work and the output is the file in its original format.

A: If you are using Perl5, chomp is useful to remove the newline character at the end of string.
print "Input file name \n";
open (FILE, <>);
$string = "";
while($line = <FILE>) {
    chomp($line); # add this line
    $string = $string . "" . $line;
}
print "$string \n";

A: Using the chomp function to remove the newlines.
The map applies the chomp function to each line, and the join sticks all the lines together.
print "Input file name \n";
open (FILE, <>);
$string = join('', map { chomp; $_ } <FILE>);
print "$string \n";

Could also use "tr" to delete the newlines after slurping the file:
print "Input file name \n";
open (FILE, <>);
($string = join('', <FILE>)) =~ tr/\n//d;
print "$string \n";


text:
Q: How can we change language in JTextField? How can I change the language in a JTextField while running? For example I want to type Chinese so I must change keyboard (Shift+alt).

A: You can change the locale used in JTextField with InputContext.selectInputMethod:
JTextField txt = new JTextField();
txt.getInputContext().selectInputMethod(Locale.CHINESE);


text:
Q: XML Serialize List of generic objects derived from an interface,,, So I'm trying to XML serialize a List<IObject> derrived from an interface, but the IObjects are generic types... best resort to code:
public interface IOSCMethod
{
    string Name { get; }
    object Value { get; set; }
    Type Type { get; }
}

public class OSCMethod<T> : IOSCMethod
{
    public string Name { get; set; }
    public T Value { get; set; }
    public Type Type { get { return _type; } }

    protected string _name;
    protected Type _type;

    public OSCMethod() { }

    // Explicit implementation of IFormField.Value
    object IOSCMethod.Value
    {
        get { return this.Value; }
        set { this.Value = (T)value; }
    }
}

And I have a List of IOSCMethods:
List<IOSCMethod>

of which I add objects to in the following way:
        List<IOSCMethod> methodList = new List<IOSCMethod>();
        methodList.Add(new OSCMethod<float>() { Name = "/1/button1", Value = 0 });
        methodList.Add(new OSCMethod<float[]>() { Name = "/1/array1", Value = new float[10] });

And it's this methodList which is what I'm trying to serialize. But everytime I try, either I get a "Can't serialize an interface" but when I make it (either the IOSCMethod or the OSCMethod<T> class) implement IXmlSerializable I get the problem of "can't serialize an object with a parameterless constructor. but obviously I can't because it's an interface! lame pants.
Any thoughts?

A: Is this what you want:
[TestFixture]
public class SerializeOscTest
{
    [Test]
    public void SerializeEmpTest()
    {
        var oscMethods = new List<OscMethod>
                             {
                                  new OscMethod<float> {Value = 0f},
                                  new OscMethod<float[]> {Value = new float[] {10,0}}
                              };
        string xmlString = oscMethods.GetXmlString();
    }
}

public class OscMethod<T> : OscMethod
{
    public T Value { get; set; }
}

[XmlInclude(typeof(OscMethod<float>)),XmlInclude(typeof(OscMethod<float[]>))]
public abstract class OscMethod
{

}

public static class Extenstion
{
    public static string GetXmlString<T>(this T objectToSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
        StringBuilder stringBuilder = new StringBuilder();
        string xml;
        using (var xmlTextWriter = new XmlTextWriter(new StringWriter(stringBuilder)))
        {
            xmlSerializer.Serialize(xmlTextWriter, objectToSerialize);
            xml = stringBuilder.ToString();
        }
        return xml;
    }
}


text:
Q: node-postgres: function unnest(unknown) is not unique I'm trying to run an AWS Lambda which upserts data into a Postgres (RDS) table
Here's my table structure:

id(integer)
name(character varying)
marks(decimal)

1
derp
42

2
derpina
45.5

My upsert query which runs perfectly on my local pgAdmin console:
INSERT INTO mytable (
    id, name,
    marks)
    VALUES (
        unnest(ARRAY[1,4,3]::integer[]),
        unnest(ARRAY['derp','frog','doge']::string[]),
        unnest(ARRAY[100,50.0,122]::decimal[])
    ) ON CONFLICT
    ON CONSTRAINT pkey
    DO UPDATE
    SET
    marks=excluded.marks;

My code snippet:
const pg = require("pg");
const Pool = pg.Pool;
var query = "INSERT INTO mytable (id, name, marks) VALUES (unnest($1::integer[]),unnest($2::string[]), unnest($3::decimal[])) ON CONFLICT ON CONSTRAINT pkey DO UPDATE SET marks=excluded.marks;"
var row = [];
var ids = [1,4,3];
var names = ['derp','tom','jerry'];
var marks = [100,44.5,31];
row.push(ids);
row.push(names);
row.push(marks);
// more code on starting up pool connection, etc...
client.query(query, row, (err, res) => {
    if (err) {
        console.log("DB upsert error: ", err.stack);
    } else {
        console.log("upserted " + res.rowCount + " entries");
    }
});

My error:
function unnest(unknown) is not unique

I already tried the solution suggested in pq: function unnest(unknown) is not unique, unnest(unknown) is not unique and unnest(array) returns text instead of the actual type but nothing seems to suggest the solution.
Please help!


text:
Q: jQuery left and right assignment I am tring to decrease and after increase the value of a variable but I got an error.
.children('#collapse' + (--count++))

The error is:
Invalid left-hand side expression in prefix operation

The goal of my code should be to concatenate the decreased count variable and after increase is value

A: You have to use comma operator at this context,
.children('#collapse' + (--count, count++))

The syntax that you are using is invalid.

A: It sounds like what you really want is to just subtract 1 from the variable without changing the variable's value. If so, why not just do that?
.children('#collapse' + (count - 1))


text:
Q: Unless Vs. If - What's the difference here? Could anyone explain why one is correct and the other is not?

I'll lend you my umbrella if you don't have yours - Okay   I'll lend you my umbrella unless you have yours - Wrong

What's the difference in these sentences? What to use when?

A: Actually, your sentence is grammatically correct.
Y will happen unless X means that if X happens, Y will not happen.
So It makes perfect sense to form your sentence as you did grammatically:

I'll lend you my umbrella unless you have yours.

It means that I am going to lend you my umbrella if you have forgotten yours.
The problem with the sentence is that it is hard to imagine how I will force you to borrow my umbrella, so even if you forgot yours, it would still be up to you to borrow mine or not.
Take this example:

I will beat you unless you give me your lunch money.

Grammatically it is just like your sentence, but this time it makes more sense that I can keep my word.
I will do X, unless you Y only makes sense if X is something that I can actually execute by myself.
You could change your sentence a bit as well:

I will not lend you my umbrella, unless you forgot yours.

This means that X (I will not lend you my umbrella) will not happen if Y happens (you forgot your umbrella).
So now, if you do not have your umbrella, I will lend you mine.


text:
Q: Display the value of each bar when cursor hovered on that bar in matplotlib I have written a really simple code which basically number of pets against pets in a locality.
import matplotlib.pyplot as plt
y_axis = [1,2,3,4]
x_axis = ['Dogs','Cats','Otter','Chipmunk']
plt.barh(x_axis, y_axis)
plt.show()

Now I want a feature which basically shows the value associated with that bar in form of some tooltip or in front of that bar.
How to do this? Can we do this without the use of subplot?

A: You can use mplcursors.  The following code is an adaption of a tutorial example for vertical bars.  For some reason, that example uses sel.index instead of sel.target.index. Maybe something has changed in matplotlib?
import matplotlib.pyplot as plt
import mplcursors

y_axis = [1, 2, 3, 4]
x_axis = ['Dogs', 'Cats', 'Otter', 'Chipmunk']
plt.barh(x_axis, y_axis)

cursor = mplcursors.cursor(hover=True)
@cursor.connect("add")
def on_add(sel):
    x, y, width, height = sel.artist[sel.target.index].get_bbox().bounds
    sel.annotation.set(text=f"{x_axis[sel.target.index]}: {width:g}",
                       position=(10, 0), anncoords="offset points")
    sel.annotation.xy = (x + width / 2, y + height / 2)
    sel.annotation.get_bbox_patch().set(alpha=0.8)

plt.tight_layout()
plt.show()


text:
Q: NSMutableDictionary key values is it true that the key values for NSMutableDictionary can only be strings?
I was trying to use objects, but I am getting a warning.

A: From the docs:

In general, a key can be any object
  (provided that it conforms to the
  NSCopying protocol—see below), but
  note that when using key-value coding
  the key must be a string (see
  Key-Value Coding Fundamentals).

What warning are you getting?

A: You can use any object, but the object must implement -[NSObject hash], -[NSObject isEqual:], and the NSCopying protocol.

A: If you take a look at header file of NSMutableDictionary, the add function can take id as the key:
- (void)setObject:(id)anObject forKey:(id)aKey;
- (void)removeObjectForKey:(id)aKey;

So you can use virtually anything as the key and value.


text:
Q: Logistic regression with panel data I am looking for a package/library to run logistic regression on panel data. I already did some research and most of the sources suggest Stata, however, I would like to use R or Python, as I am using one of these for data preparation. I have found this, but this is not a well know package as far as I know. Any suggestions would be welcome.

A: You can model longitudinal data within a Generalized Linear Mixed Model (GLMM) framework, if you're looking to implement logistic regressions. One commonly used R package is lme4, you can use the glmer() function.


text:
Q: How to save the data in my ListView from the first Activity to the second Activity? I am writing an app for a restaurant and would like to be able to select a specific dish that you would like to order and that it has been added to OrderActivity where, in the form of ListView, you will be displaying individual dishes selected by the user.
I do not know how to do it in the best way, do you need to use the interface and maybe just get the intention of a specific dish?
And how do I save a specific request in OrderActivity so that when I return to an earlier Activity I do not lose the saved data in the ListView?
I managed to solve the problem of transmitting data from one Activity to the second Activity and showing it on the ListView, I do not know how to save that data, say on the example of SharedPreferences?
If I click the back button in my second Activity, my list becomes empty.
I understand that the fault is on onResume() because I am killing the second Activity, when I come back to the first, is that so?
How to solve the problem?
FirstActivity:
public class DinnerDetailActivity extends AppCompatActivity {

    public static final String EXTRA_DINNER = "dinner";

    private final int requestCode = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_obiady_domowe_detail);

        int dinner = (Integer) getIntent().getExtras().get(EXTRA_DINNER);

        String dinnerName = Dinner.dinn[dinner].getName();
        TextView textView = (TextView) findViewById(R.id.dinner_text);
        textView.setText(dinnerName);

        int dinnerImage = Dinner.dinn[dinner].getImageResourceId();
        ImageView imageView = (ImageView) findViewById(R.id.dinner_image);
        imageView.setImageDrawable(getResources().getDrawable(dinnerImage));
        imageView.setContentDescription(dinnerName);

        Toolbar myChildToolbar = (Toolbar)
        findViewById(R.id.my_child_toolbar_obiady_detail);
        setSupportActionBar(myChildToolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

   /* @Override
    protected void onResume() {

        SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("KEY", listItems.add();
        editor.apply();

        Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
        super.onResume();
    }
*/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_main, menu);

        TextView textView = (TextView) findViewById(R.id.dinner_text);
        CharSequence dinnerName = textView.getText();
        MenuItem menuItem = menu.findItem(R.id.action_share);
        ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, dinnerName);
        shareActionProvider.setShareIntent(intent);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_create_order:
                Intent intent = new Intent(this, TopFragment.class);
                startActivity(intent);
                return true;
            default:

        return super.onOptionsItemSelected(item);
     }
    }

//Click button, and add dinnerName to SecondActivity ListView
    public void addInOrder(View view) {

    int dinner = (Integer) getIntent().getExtras().get(EXTRA_DINNER);

    String dinnerName = Dinner.dinn[dinner].getName();

    Intent intent1 = new Intent(this, CreateYourOrderActivity.class);
    intent1.putExtra("OK", dinnerName);
    startActivityForResult(intent1, requestCode);

    }
}

Second Activity:
public class CreateYourOrderActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayAdapter<String> adapter;
    private ArrayList<String> listItems;

    private String dinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zloz_zamowienie);

        Toolbar myChildToolbar = (Toolbar)
            findViewById(R.id.my_child_toolbar);

        setSupportActionBar(myChildToolbar);

        ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);

        textView = (TextView) findViewById(R.id.text_view);

    }
/*
    @Override
    protected void onResume() {

        SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("KEY", obiad);
        editor.apply();

        listItems.add(obiad);
        adapter.notifyDataSetChanged();

        Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
        super.onResume();
    }
*/
    /* @Override
    public void onBackPressed() {
        SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("KEY", listItems.get(0).toString());
        editor.apply();

        Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
    }*/

    public void saveInfo(View view) {

    }

    public void openInfo(View view) {

        SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
        String obiadNames = sharedPref.getString("KEY", "");

        textView.setText(obiadNames);
        //listItems.add(obiadNames);
        //adapter.notifyDataSetChanged();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_create_order:
                Intent intent = new Intent(this, MainActivity.class);

                return true;
            default:

                return super.onOptionsItemSelected(item);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

       Intent intent = getIntent();

        if(resultCode == RESULT_OK) {
           if(requestCode == 1){

            dinner = data.getExtras().getString("OK");

            listView = (ListView) findViewById(R.id.listView);

            listItems.add(dinner);

            adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
            listView.setAdapter(adapter);

            //  adapter.add(dinner);
            adapter.notifyDataSetChanged();

            finish();
        }

       }
    }

So as you can see in the attached photos we have the first Activity, several dishes from which we go to the detailed Activity, where we have AddOrder Button.
I would like to click on this button to add the name of my specific dish in the 3 Activities that you see in the pictures.
This is to be added as a ListView.
Also, I would like to have the names of dishes not gone when I return to 1 Activity.

A: SharedPreferences are for simple values.
You'll need a proper database (Sqlite, Realm, or other) with which you can persistently store and query your data across the entire application without passing entire objects across Intent boundaries.
More specifically, you need to replace the Dinner.dinn array
To get specific items when you go to a detail view, you can pass the database ID of the object, then query it later.
When you add a new item and go back to the list, you will update the adapter with all the database entries


text:
Q: Submitting a form in a document retrieved using a DOMParser I'm writing automation software in JavaScript within TamperMonkey.
My script does few AJAX requests which return HTML that I parse using a DOMParser. I was wondering if it was possible to submit these forms without having to actually open the newly returned HTML in the main page.

A: Yes. You need to get your form from the document body, create a FormData object and set field values, and send a POST request.
For simplicity sake I used the Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API. I also assumed that the credentials also needed to be passed from the same origin.
fetch('<GET URL>', {method: "GET", credentials: 'same-origin'})
  .then((response) => (response.text()))
  .then((responseBody) => {
    var html = htmlBody(responseBody);
    var form = html.querySelector('#my-form'); // whatever your form is called
    var formData = new FormData();

    formData.append('someName', 'someValue'); // the field name will probably come from your form fields

    postForm(formData)
      .then((response) => (response.text()))
      .then((responseBody) => {
        // whatever with the form post response
    });
})

function htmlBody(string) {
  var document = new DOMParser;
  return document.parseFromString(string, 'text/html').body;
}

function postForm(formData) {
  return fetch('<POST URL>', {
    method: 'POST',
    body: formData,
    credentials: 'same-origin'
  })
}


text:
Q: How do I stop the second prompt from appearing until the first if/else condition is satisfied? (Start Page for a game) If the user name is not entered, the age prompt still comes up, I want the whole prompt to terminate if the user name is not entered, basically, when it says "You cannot proceed without the name" after that the prompt asking for the age still appears, I don't want that to happen.
Here is my code:
</style>

Welcome to

 Hangman

  <button onclick="myFunction()">Let's start</button>


text:
Q: Call a function that exist on other JS file In my app every view has its own JS,
the user can click on "upload" button and a file Upload modal is showing > then he choose an image from the list > then he hit "save" button:
fileUpload.js:
  viewModel.prototype.save = function () {
        cms.closeDialog(this, this.selectedObject());
    };

what i am trying to achieve > when the user hit the "save" button > a thumbnail of the image will be shown in the dedicated div in Products.html:

*

*now it's working but only after refreshing the page.

Products.js:
 fileUpload.prototype.fileUploaded = function (fileSize, fileName, extension) {
            this.resetThumbnail();
            this.value().fileName = fileName;
            this.updateFileSize(fileSize);
            if (this.uploadCallback) {
                this.uploadCallback.call(this.context || this, fileName, extension);
            }
        };

From the save event in fileUpload.js I am trying to call fileUploaded function that exists in Products.js.
How can i achieve that?

A: Your Product.js file probably has something like this:
var ProductModel = {
   //code on this model

   fileUpload.prototype.fileUploaded = function (fileSize, fileName, extension) {
        this.resetThumbnail();
        this.value().fileName = fileName;
        this.updateFileSize(fileSize);
        if (this.uploadCallback) {
            this.uploadCallback.call(this.context || this, fileName, extension);
        }
    };

    //code on this model
}

And because of that when you try to reach that function from the outside, it's not on the current scope.
You will probably have to use the variable you set the model on Products.js to call your function.


text:
Q: Python - "pyodbc" is not accessed Pylance Im new to using python, and having some trouble using pyodbc to connect to MS SQL.
I've reinstalled almost everything except windows so far.
reinstalled a few times, both with pip/pip3. Even tried older versions of pyodbc.
Only have one version of python installed.
Not running any VM.
using python 3.8-32, with pyodbc 4.0.32.
Error im getting is:
"pyodbc" is not accessed Pylance
Import "pyodbc" could not be resolved Pylance (reportMissingImports)
Just to mention it, have been searching for a fix for this for a few hours now, getting a bit weary. cant find a fix or even anything postet within 2 years that is relatable.
Anyone got any tips/suggestion would be much appreaciated by a PythonNewbie.

A: The error you show is one given by your editor, not by Python. Pylance is an extension for Visual Studio Code (VSCode) to help the editor understand Python code. It simply means that Pylance is not using the same Python binary as your project.
Open the command palette and type "Python: select interpreter", then find your Python interpreter that has pyodbc installed. See the documentation on using Python environments.
Note that even with as single Python installation, you can have multiple virtual environments. You may have installed PyODBC in a virtual environment, or in the system Python packages, but if Pylance is looking at the wrong environment it won't find PyODBC.


text:
Q: How to draw near front clipping plane? I am trying to draw object in OpenGL near front clipping plane. There is already defined path, and a camera is moving down the path. Now, I want to draw object that is moving with a camera, bot is not directly on front clipping plane.
I am using Tux Racer game port on Android and tried with small test function like this in hud.c:
void draw_triangle() {
    set_gl_options(FOG_PLANE);

    glPushMatrix();
    {
        glTranslatef(getparam_x_resolution() / 2.0, getparam_y_resolution() / 2.0, -5.0);
        glBegin(GL_TRIANGLES);          // Drawing Using Triangles
        glVertex3f(0.0f, 50.0f, 0.0f);      // Top
        glVertex3f(-50.0f, -50.0f, 0.0f);   // Bottom Left
        glVertex3f(50.0f, -50.0f, 0.0f);    // Bottom Right
        glEnd();                // Finished Drawing
    }
    glPopMatrix();
}

but it wouldn't draw. Where am I getting wrong? I'm not shute if -5.0 for z-axis is too far, or I should use some other option for set_gl_options(), that is, I'm not shure what should be enabled/disabled from this options to see 3D object:

*

*GL_TEXTURE_2D

*GL_DEPTH_TEST

*GL_CULL_FACE

*GL_LIGHTING

*GL_NORMALIZE

*GL_ALPHA_TEST

*GL_BLEND

*GL_STENCIL_TEST

*GL_TEXTURE_GEN_S

*GL_TEXTURE_GEN_T

*GL_COLOR_MATERIAL

Other Functions:

*

*glDepthMask

*glShadeModel

*glDepthFunc

Here is code for setting camera view:
void update_view(player_data_t *plyr, scalar_t dt) {
    point_t view_pt;
    vector_t view_dir, up_dir, vel_dir, view_vec;
    scalar_t ycoord;
    scalar_t course_angle;
    vector_t axis;
    matrixgl_t rot_mat;
    vector_t y_vec;
    vector_t mz_vec;
    vector_t vel_proj;
    quaternion_t rot_quat;
    scalar_t speed;
    vector_t vel_cpy;
    scalar_t time_constant_mult;

    vel_cpy = plyr->vel;
    speed = normalize_vector(&vel_cpy);

    time_constant_mult =
            1.0
                    / min( 1.0,
                            max( 0.0,
                                    ( speed - NO_INTERPOLATION_SPEED ) /
                                    ( BASELINE_INTERPOLATION_SPEED - NO_INTERPOLATION_SPEED )));

    up_dir = make_vector(0, 1, 0);

    vel_dir = plyr->vel;
    normalize_vector(&vel_dir);

    course_angle = get_course_angle();

    switch (plyr->view.mode) {
    case TUXEYE: {
        .
.
.
        break;
    }
    case BEHIND: {
        /* Camera-on-a-string mode */

        /* Construct vector from player to camera */
        view_vec = make_vector(0, sin(ANGLES_TO_RADIANS(
                course_angle -
                CAMERA_ANGLE_ABOVE_SLOPE +
                PLAYER_ANGLE_IN_CAMERA )), cos(ANGLES_TO_RADIANS(
                course_angle -
                CAMERA_ANGLE_ABOVE_SLOPE +
                PLAYER_ANGLE_IN_CAMERA )));

        view_vec = scale_vector(CAMERA_DISTANCE, view_vec);

        y_vec = make_vector(0.0, 1.0, 0.0);
        mz_vec = make_vector(0.0, 0.0, -1.0);
        vel_proj = project_into_plane(y_vec, vel_dir);

        normalize_vector(&vel_proj);

        /* Rotate view_vec so that it places the camera behind player */
        rot_quat = make_rotation_quaternion(mz_vec, vel_proj);

        view_vec = rotate_vector(rot_quat, view_vec);

        /* Construct view point */
        view_pt = move_point(plyr->pos, view_vec);

        /* Make sure view point is above terrain */
        ycoord = find_y_coord(view_pt.x, view_pt.z);

        if (view_pt.y < ycoord + MIN_CAMERA_HEIGHT) {
            view_pt.y = ycoord + MIN_CAMERA_HEIGHT;
        }

        /* Interpolate view point */
        if (plyr->view.initialized) {
            /* Interpolate twice to get a second-order filter */
            int i;
            for (i = 0; i < 2; i++) {
                view_pt = interpolate_view_pos(plyr->pos, plyr->pos,
                        MAX_CAMERA_PITCH, plyr->view.pos, view_pt,
                        CAMERA_DISTANCE, dt,
                        BEHIND_ORBIT_TIME_CONSTANT * time_constant_mult);
            }
        }

        /* Make sure interpolated view point is above terrain */
        ycoord = find_y_coord(view_pt.x, view_pt.z);

        if (view_pt.y < ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT) {
            view_pt.y = ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT;
        }

        /* Construct view direction */
        view_vec = subtract_points(view_pt, plyr->pos);

        axis = cross_product(y_vec, view_vec);
        normalize_vector(&axis);

        make_rotation_about_vector_matrix(rot_mat, axis,
                PLAYER_ANGLE_IN_CAMERA);
        view_dir = scale_vector(-1.0, transform_vector(rot_mat, view_vec));

        /* Interpolate orientation of camera */
        if (plyr->view.initialized) {
            /* Interpolate twice to get a second-order filter */
            int i;
            for (i = 0; i < 2; i++) {
                interpolate_view_frame(plyr->view.up, plyr->view.dir, &up_dir,
                        &view_dir, dt, BEHIND_ORIENT_TIME_CONSTANT);
                up_dir = make_vector(0.0, 1.0, 0.0);
            }
        }

        break;
    }

    case FOLLOW: {
        /* Camera follows player (above and behind) */

        up_dir = make_vector(0, 1, 0);

        /* Construct vector from player to camera */
        view_vec = make_vector(0, sin(ANGLES_TO_RADIANS(
                course_angle -
                CAMERA_ANGLE_ABOVE_SLOPE +
                PLAYER_ANGLE_IN_CAMERA )), cos(ANGLES_TO_RADIANS(
                course_angle -
                CAMERA_ANGLE_ABOVE_SLOPE +
                PLAYER_ANGLE_IN_CAMERA )));
        view_vec = scale_vector(CAMERA_DISTANCE, view_vec);

        y_vec = make_vector(0.0, 1.0, 0.0);
        mz_vec = make_vector(0.0, 0.0, -1.0);
        vel_proj = project_into_plane(y_vec, vel_dir);

        normalize_vector(&vel_proj);

        /* Rotate view_vec so that it places the camera behind player */
        rot_quat = make_rotation_quaternion(mz_vec, vel_proj);

        view_vec = rotate_vector(rot_quat, view_vec);

        /* Construct view point */
        view_pt = move_point(plyr->pos, view_vec);

        /* Make sure view point is above terrain */
        ycoord = find_y_coord(view_pt.x, view_pt.z);

        if (view_pt.y < ycoord + MIN_CAMERA_HEIGHT) {
            view_pt.y = ycoord + MIN_CAMERA_HEIGHT;
        }

        /* Interpolate view point */
        if (plyr->view.initialized) {
            /* Interpolate twice to get a second-order filter */
            int i;
            for (i = 0; i < 2; i++) {
                view_pt = interpolate_view_pos(plyr->view.plyr_pos, plyr->pos,
                        MAX_CAMERA_PITCH, plyr->view.pos, view_pt,
                        CAMERA_DISTANCE, dt,
                        FOLLOW_ORBIT_TIME_CONSTANT * time_constant_mult);
            }
        }

        /* Make sure interpolate view point is above terrain */
        ycoord = find_y_coord(view_pt.x, view_pt.z);

        if (view_pt.y < ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT) {
            view_pt.y = ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT;
        }

        /* Construct view direction */
        view_vec = subtract_points(view_pt, plyr->pos);

        axis = cross_product(y_vec, view_vec);
        normalize_vector(&axis);

        make_rotation_about_vector_matrix(rot_mat, axis,
                PLAYER_ANGLE_IN_CAMERA);
        view_dir = scale_vector(-1.0, transform_vector(rot_mat, view_vec));

        /* Interpolate orientation of camera */
        if (plyr->view.initialized) {
            /* Interpolate twice to get a second-order filter */
            int i;
            for (i = 0; i < 2; i++) {
                interpolate_view_frame(plyr->view.up, plyr->view.dir, &up_dir,
                        &view_dir, dt, FOLLOW_ORIENT_TIME_CONSTANT);
                up_dir = make_vector(0.0, 1.0, 0.0);
            }
        }

        break;
    }

    case ABOVE: {
        /* Camera always uphill of player */

        up_dir = make_vector(0, 1, 0);

        /* Construct vector from player to camera */
        view_vec = make_vector(0, sin(ANGLES_TO_RADIANS(
                course_angle -
                CAMERA_ANGLE_ABOVE_SLOPE+
                PLAYER_ANGLE_IN_CAMERA )), cos(ANGLES_TO_RADIANS(
                course_angle -
                CAMERA_ANGLE_ABOVE_SLOPE+
                PLAYER_ANGLE_IN_CAMERA )));
        view_vec = scale_vector(CAMERA_DISTANCE, view_vec);

        /* Construct view point */
        view_pt = move_point(plyr->pos, view_vec);

        /* Make sure view point is above terrain */
        ycoord = find_y_coord(view_pt.x, view_pt.z);

        if (view_pt.y < ycoord + MIN_CAMERA_HEIGHT) {
            view_pt.y = ycoord + MIN_CAMERA_HEIGHT;
        }

        /* Construct view direction */
        view_vec = subtract_points(view_pt, plyr->pos);

        make_rotation_matrix(rot_mat, PLAYER_ANGLE_IN_CAMERA, 'x');
        view_dir = scale_vector(-1.0, transform_vector(rot_mat, view_vec));

        break;
    }

    case BIRDEYE: {
        /* Camera always uphill of player */

        up_dir = make_vector(0, 1, 0);

        /* Construct vector from player to camera */
        /*sin(ANGLES_TO_RADIANS(
                                        course_angle -
                                        CAMERA_ANGLE_ABOVE_SLOPE+
                                        PLAYER_ANGLE_IN_CAMERA ))
                                        */
        /*cos(ANGLES_TO_RADIANS(
                                                course_angle -
                                                CAMERA_ANGLE_ABOVE_SLOPE+
                                                PLAYER_ANGLE_IN_CAMERA ))
                                                */
        view_vec = make_vector(0, 3, -0.5);
        view_vec = scale_vector(CAMERA_DISTANCE, view_vec);

        /* Construct view point */
        view_pt = move_point(plyr->pos, view_vec);

        /* Make sure view point is above terrain */
        ycoord = find_y_coord(view_pt.x, view_pt.z);

        if (view_pt.y < ycoord + MIN_CAMERA_HEIGHT) {
            view_pt.y = ycoord + MIN_CAMERA_HEIGHT;
        }

        /* Construct view direction */
        view_vec = subtract_points(view_pt, plyr->pos);

        make_rotation_matrix(rot_mat, PLAYER_ANGLE_IN_CAMERA, 'x');
        view_dir = scale_vector(-1.0, transform_vector(rot_mat, view_vec));

        break;
    }
    default:
        code_not_reached();
        break;
    }

    /* Create view matrix */
    plyr->view.pos = view_pt;
    plyr->view.dir = view_dir;
    plyr->view.up = up_dir;
    plyr->view.plyr_pos = plyr->pos;
    plyr->view.initialized = True;

    setup_view_matrix(plyr);
}

UPDATE
Solved!, The problem was in using OpenGL instead OpenGL ES.

A: Android uses OpenGL ES, which doesn't support glBegin() and glEnd(), so your code is not going to draw anything. You need to use Vertex Buffer Objects to draw objects.
A classic guide to VBOs is here: http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=45
but you may find that googling "Android OpenGL tutorial" will provide some simpler guides.

A: well, if you want to display something just in front of the camera, all the camera setup code is irrelevant; moreover, you need to make sure that it does not apply to your triangle, that is, you call to drawTriangle() from somewhere where the matrix stack is empty. where do you call it from now? I went to GitHub to look at TuxRider and got lost, sorry.
after that, if you render a triangle in screen coordinates, it might be worth taking into account that they range from -1 to +1 - your geometry of 50 by 50 at 5 away is too big and too far away.
Bests of luck


text:
Q: Access Nested List Item for Functions Applied to a Data Frame I'm trying to split a string in one column...
> df.arpt
          arpt
1    CMH 39402
2    IAH 97571
3    DAL 67191
4    HOU 07614
5    OKC 11127

...and break it out into two new columns with a result that looks like this...
> df.arpt
          arpt   arptCode    arptID
1    CMH 39402        CMH     39402
2    IAH 97571        IAH     97571
3    DAL 67191        DAL     67191
4    HOU 07614        HOU     07614
5    OKC 11127        OKC     11127

I really want something like this to be possible...
> df.arpt$arptCode <- strsplit(df.arpt$arpt, " ")[[...]][1]
> df.arpt$arptID   <- strsplit(df.arpt$arpt, " ")[[...]][2]

... where the ... in the code represents "for every record in the data frame".
Any suggestions on how to go about this? (I'd like to stick with base R / "out-of-the-box" R rather than higher-level packages.) Am I thinking about this the right way in R?

A: If the arptCode values are row names, you can convert them into a column.
library(tidyverse)
df.arpt %>%
  rownames_to_column(var = "arptCode")

If they are not row names then you can use separate.
library(tidyverse)
df.arpt %>%
  separate(arpt, into = c('arptCode', 'aprtID'))

A: How about this:
df<-data.frame(arpt =c("CMH 39402", "IAH 97571", "DAL 67191", "HOU 07614", "OKC 11127"))
tidyr::separate(df, arpt, into = c("artpCode", "arptID"))

A: Because the strings are all fixed length, I was able to apply the substr function instead in order to move past the problem. However, I still don't know what the solution would be if the result of the function was a list.


text:
Q: In theory (because light can still enter a black hole) if you are inside of the event horizon, could you see outside of it? To my limited knowledge, it should be possible for you to see from inside of a black hole. Is this true, or am I missing something?

A: Yes, you should be able to see out of a black hole, assuming you're still alive.


text:
Q: Can't run bbb from CL I'm trying to install bbb but am having problems in the CL. I have managed to download the packages using npm (although I had to use sudo - is that normal?) but when I try to use the bbb command I get a "command not found" error.
I've tried updating my $PATH with where I think the modules are, but that doesn't seem to help.
It looks as though bbb has been downloaded to /usr/local/lib/node_modules so that is what I've tried adding to my $PATH.
Any help would be gratefully received. Especially because I want to try Yeoman next and I'm afraid I might run into the same problems.
I'm running Mac OS X 10.8.4


text:
Q: Jquery: Convert any CSS color to rgb Is there a quick way I can covert any css color such as #ffe, whitesmoke, or hsl(20,50%,80%), to a rgb color like rgb(140,75,20)?
Can I use the .css() method on a variable to convert the color to rgb somehow?

A: This may answer your question -
RGB to Hex and Hex to RGB
function hexToRgb(hex) {
   var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
   return result ? {
       r: parseInt(result[1], 16),
       g: parseInt(result[2], 16),
       b: parseInt(result[3], 16)
   } : null;
}

alert( hexToRgb("#0033ff").g ); // "51";


text:
Q: Error Handling - protobuf message to DLT instead of Retry in case of connection exception I've implemented an KafkaListener using SpringBoot 2.7.6, Confluent platform and now I need to implement the Error Handler for it.
The listener manages to pick up a protobuf topic message and POST the payload to an HTTP endpoint properly. But in case of the java.net.ConnectException happens I need to send the same protobuf message to a DLT instead of Retry.
I implemented this using the following Listener:
@Component
class ConsumerListener(
    private val apiPathsConfig: ApiPathsConfig,
    private val myHttpClient: MyHttpClient,
    @Value("\${ingestion.config.httpClientTimeOutInSeconds}") private val httpRequestTimeout: Long
) {
    val log: Logger = LoggerFactory.getLogger(ConsumerListener::class.java)

    @RetryableTopic(
        attempts = "4",
        backoff = Backoff(delay = 5000, multiplier = 2.0),    //TODO: env var?
        autoCreateTopics = "false",
        topicSuffixingStrategy = TopicSuffixingStrategy.SUFFIX_WITH_INDEX_VALUE,
        timeout = "3000",    //TODO: env var?
        dltStrategy = DltStrategy.FAIL_ON_ERROR
    )
    @KafkaListener(
        id = "ingestionConsumerListener",
        topics = ["#{'\${ingestion.config.topic.name}'}"],
        groupId = "#{'\${ingestion.consumer.group.id}'}",
        concurrency = "#{'\${ingestion.config.consumer.concurrency}'}"
    )
    fun consume(ingestionHttpRequest: ConsumerRecord<String, HttpRequest.HttpRequest>) {

        ...
        try {
            val response: HttpResponse<Void> = myHttpClient.send(request, HttpResponse.BodyHandlers.discarding())
            if (response.statusCode() in 400..520) {
                val ingestionResponseError = "Ingestion response status code [${response.statusCode()}] - headers [${response.headers()}] - body [${response.body()}]"
                log.error(ingestionResponseError)
                throw RuntimeException(ingestionResponseError)
            }
        } catch (e: IOException) {
            log.error("IOException stackTrace : ${e.printStackTrace()}")
            throw RuntimeException(e.stackTrace.contentToString())
        } catch (e: InterruptedException) {
            log.error("InterruptedException stackTrace : ${e.printStackTrace()}")
            throw RuntimeException(e.stackTrace.contentToString())
        } catch (e: IllegalArgumentException) {
            log.error("IllegalArgumentException stackTrace : ${e.printStackTrace()}")
            throw RuntimeException(e.stackTrace.contentToString())
        }

    }
    ...
}

When the java.net.ConnectException happens the DeadLetterPublishingRecoverFactory show this:
15:19:44.546 [kafka-producer-network-thread | producer-1] INFO  org.apache.kafka.clients.producer.internals.TransactionManager - [Producer clientId=producer-1] ProducerId set to 3330155 with epoch 0
15:19:44.547 [ingestionConsumerListener-2-C-1] ERROR org.springframework.kafka.retrytopic.DeadLetterPublishingRecovererFactory$1 - Dead-letter publication to ingestion-topic-retry-0failed for: ingestion-topic-5@32
org.apache.kafka.common.errors.SerializationException: Can't convert value of class com.xxx.ingestion.IngestionHttpRequest$HttpRequest to class org.apache.kafka.common.serialization.StringSerializer specified in value.serializer

...
Caused by: java.lang.ClassCastException: class com.xxx.ingestion.IngestionHttpRequest$HttpRequest cannot be cast to class java.lang.String (com.xxx.ingestion.IngestionHttpRequest$HttpRequest is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')
    at org.apache.kafka.common.serialization.StringSerializer.serialize(StringSerializer.java:29)

Please, how to resend the protobuf message to a DLT instead of Retry in case of ConnectionException and how to keep the Retry in case of the the HTTP endpoint response 4xx or 5xx code?
Please user:2756547

A: You either need a protobuf serializer to re-serialize the data, or don't deserialize the prototbuf in a deserializer, use a ByteArrayDeserializer and convert it in your listener instead; then use a ByteArraySerializer.
You can also configure certain exception types to go straight to the DLT.
EDIT
See https://docs.spring.io/spring-kafka/docs/current/reference/html/#retry-topic-global-settings
@Configuration
public class MyRetryTopicConfiguration extends RetryTopicConfigurationSupport {

    @Override
    protected void manageNonBlockingFatalExceptions(List<Class<? extends Throwable>> nonBlockingFatalExceptions) {
        nonBlockingFatalExceptions.add(MyNonBlockingException.class);
    }

}

/**
 * Override this method to manage non-blocking retries fatal exceptions.
 * Records which processing throws an exception present in this list will be
 * forwarded directly to the DLT, if one is configured, or stop being processed
 * otherwise.
 * @param nonBlockingRetriesExceptions a {@link List} of fatal exceptions
 * containing the framework defaults.
 */
protected void manageNonBlockingFatalExceptions(List<Class<? extends Throwable>> nonBlockingRetriesExceptions) {
}


text:
Q: Theorem 7.17 in Baby Rudin: Differentiability of the limit function of a uniformly convergent sequence Here is a theorem which I came across in Principles of Mathematical analysis by Walter Rudin

Theorem 7.17$\space\space$ Suppose $\{f_n\}$ is a sequence of functions, differentiable on $[a,b]$ and such that $\{f_n(x_0)\}$ converges for some point $x_0$ on $[a,b].$ If $\{f_n'\}$ converges uniformly on $[a,b]$, then ${f_n}$ converges uniformly on $[a,b]$, to a function $f$, and $$f'(x)=\lim_{n\to\infty}f'_n(x)\quad\quad\quad\quad(a\le x\le b)$$

In the proof of this theorem he proves the uniform convergence of ${f_n}$ and defines the limit function as equal to $f$. Further he says that if we fix a point $x$ then we can define $$\phi_n(t)=\frac{f_n(t)-f_n(x)}{t-x},\quad\quad\quad \phi(t)=\frac{f(t)-f(x)}{t-x}$$ for $a\le t\le b,\space t\neq x$. It is then proven that $\phi_n(t)$ converges uniformly for $t\neq x$ using the Cauchy criterion of uniform convergence which means that the proof of $\phi_n(t)$ is uniformly convergent has been established but the limit function is yet unknown. He then writes that since $\{f_n\}$ converges to $f$ therefore we can conclude that $$\lim_{n\to \infty}\phi_n(t)=\phi(t)$$
It is this part of the proof which I don't understand. If we are claiming that $\phi_n(t)$ converges uniformly to $\phi(t)$ then it should be possible to show that for an $\varepsilon \gt 0$ there exists an $N$ such that $\quad sup|\phi_n(t)-\phi(t)|\lt\varepsilon\quad$ for all $n\ge N$ if $t\in[a,b],$ and $t\neq x$. The way I started to prove it is
$$|\phi_n(t)-\phi(t)|=\left|\frac{f_n(t)-f_n(x)}{t-x}-\frac{f(t)-f(x)}{t-x}\right|\le
\frac{1}{|t-x|} \Bigl[|f_n(t)-f(t)|+|f_n(x)-f(x)|\Bigr]$$
If I resolve the above I will be able to show the existence of an $N$ such that
$$|\phi_n(t)-\phi(t)| \lt \frac{\varepsilon}{|t-x|}$$
for all $n\ge N$. So, how do I get rid of $|t-x|$ in the above since I can't assume that $f$ is differentiable (that is what we have to prove in this theorem) so mean value theorem is out of question?
Another doubt in the same proof has already been asked here: Baby Rudin Theorem 7.17 where the whole proof has been quoted from the book. Since I don't have enough reputation yet so I couldn't ask for clarification of the proof in the same thread itself and hence have to post it as a separate question.

A: As I mentioned in my comment, one could avoid an explicit usage of the Cauchy criterion by intertwining it into a complicated estimate (i.e basically repeat proofs of theorems already proven). Just to be clear: I think Rudin's proof is going to be much simpler than what I present below, but in case you're a brave soul, here goes.
Let $\psi$ be the limit of $f_n'$. I'm going to assume we already know $f_n$ converges pointwise to some function $f$. Now, fix an $x\in [a,b]$. Now, for any $t\neq x$, and any $n,m\in\Bbb{N}$, we use a 3-fold triangle inequality to get
\begin{align}
\left|\frac{f(t)-f(x)}{t-x}-\psi(x)\right|&\leq
\left|\frac{f(t)-f(x)}{t-x}-\frac{f_n(t)-f_n(x)}{t-x}\right|\\
&+\left|\frac{(f_n-f_m)(t)-(f_n-f_m)(x)}{t-x}\right|\\
&+\left|\frac{f_m(t)-f_m(x)}{t-x}-\psi(x)\right|
\end{align}
Using the mean-value theorem for $f_n-f_m$, we can bound the second term by $\|f_n'-f_m'\|_{\infty}$ (i.e the supremum norm). Hence, we get
\begin{align}
\left|\frac{f(t)-f(x)}{t-x}-\psi(x)\right|&\leq
\left|\frac{f(t)-f(x)}{t-x}-\frac{f_n(t)-f_n(x)}{t-x}\right|\\
&+\|f_n'-f_m'\|_{\infty}\\
&+\left|\frac{f_m(t)-f_m(x)}{t-x}-\psi(x)\right|
\end{align}
Now, we take the limit as $n\to \infty$ on both sides. On the LHS, nothing happens, while on the RHS, the first term vanishes since $f_n\to f$ pointwise by definition. The second term becomes $\|\psi-f_m'\|_{\infty}$ (because norms are continuous so we can pull the limit inside. Note that we're using the fact $f_n'\to \psi$ uniformly here). Hence,
\begin{align}
\left|\frac{f(t)-f(x)}{t-x}-\psi(x)\right| & \leq 0 + \|\psi-f_m'\|_{\infty}+
\left|\frac{f_m(t)-f_m(x)}{t-x}-\psi(x)\right|
\end{align}
Now, we take $\limsup\limits_{t\to x}$ on both sides (we take $\limsup$ because the limit superior of any function always exists, while the limit a-priori need not exist. Also, recall that limit exists if and only if $\limsup$ and $\liminf$ are equal, in which case all three are equal). This gives us
\begin{align}
\limsup_{t\to x}\left|\frac{f(t)-f(x)}{t-x}-\psi(x)\right| & \leq \|\psi-f_m'\|_{\infty}+\limsup_{t\to x}\left|\frac{f_m(t)-f_m(x)}{t-x}-\psi(x)\right|\\
&=\|\psi-f_m'\|_{\infty}+|f_m'(x)-\psi(x)|\\
&\leq 2\|f_m'-\psi\|_{\infty}.
\end{align}
Finally, we can let $m\to \infty$, so that the RHS vanishes. Therefore, we have proven that
\begin{align}
\limsup_{t\to x}\left|\frac{f(t)-f(x)}{t-x}-\psi(x)\right|&\leq 0.
\end{align}
This means the $\limsup$ is actually equal to $0$, and thus the $\lim\limits_{t\to x}$ also exists and equals zero. This is exactly what it means to show $f$ is differentiable at $x$ with $f'(x)=\psi(x)=\lim\limits_{n\to \infty}f_n'(x)$.
The usefulness of $\limsup$ is that it saves us from bringing in $\epsilon$'s and $N$'s and $\delta$'s.


text:
Q: "The process cannot access the file because it is being used by another process." with SystemReader I have no coding experience but have been trying to fix a broken program many years ago. I've been fumbling through fixing things but have stumbled upon a piece that I can't fix. From what I've gathered you get Alexa to append a Dropbox file and the program reads that file looking for the change and, depending on what it is, executes a certain command based on a customizable list in an XML document.
I've gotten this to work about five times in the hundred of attempts I've done, every other time it will crash and Visual Studio gives me: "System.IO.IOException: 'The process cannot access the file 'C:\Users\\"User"\Dropbox\controlcomputer\controlfile.txt' because it is being used by another process.'"
This is the file that Dropbox appends and this only happens when I append the file, otherwise, the program works fine and I can navigate it.
I believe this is the code that handles this as this is the only mention of StreamReader in all of the code:
public static void launchTaskControlFile(string path)
    {
        int num = 0;
        StreamReader streamReader = new StreamReader(path);
        string str = "";
        while (true)
        {
            string str1 = streamReader.ReadLine();
            string str2 = str1;
            if (str1 == null)
            {
                break;
            }
            str = str2.TrimStart(new char[] { '#' });
            num++;
        }
        streamReader.Close();
        if (str.Contains("Google"))
        {
            MainWindow.googleSearch(str);
        }
        else if (str.Contains("LockDown") && Settings.Default.lockdownEnabled)
        {
            MainWindow.executeLock();
        }
        else if (str.Contains("Shutdown") && Settings.Default.shutdownEnabled)
        {
            MainWindow.executeShutdown();
        }
        else if (str.Contains("Restart") && Settings.Default.restartEnabled)
        {
            MainWindow.executeRestart();
        }
        else if (!str.Contains("Password"))
        {
            MainWindow.launchApplication(str);
        }
        else
        {
            SendKeys.SendWait(" ");
            Thread.Sleep(500);
            string str3 = "potato";
            for (int i = 0; i < str3.Length; i++)
            {
                SendKeys.SendWait(str3[i].ToString());
            }
        }
        Console.ReadLine();
    }

I've searched online but have no idea how I could apply anything I've found to this. Once again before working on this I have no coding experience so act like you're talking to a toddler.
Sorry if anything I added here is unnecessary I'm just trying to be thorough. Any help would be appreciated.

A: I set up a try delay pattern like Adriano Repetti said and it seems to be working, however doing that flat out would only cause it to not crash so I had to add a loop around it and set the loop to stop when a variable hit 1, which happened whenever any command types are triggered. This takes it out of the loop and sets the integer back to 0, triggering the loop again. That seems to be working now.


text:
Q: Trouble searching for specific values using XMLNAMESPACES I've taken a look and wasn't able to find an answer that would help me with my issue. (Most probably due to my poor skills)
However was hoping that someone would be able to point me in the right direction.
The issue:
I have an XML column in the table that I am querying and I need the query to return rows all rows with a specific value.
An example from the xml column
 <EventD xmlns="http://example1" xmlns:e3q1="http://example2" xmlns:xsi="http://example3" xsi:type="e3q1:Valuechange">
  <e3q1:NewValue>Running</e3q1:NewValue>
  <e3q1:OldValue>Stopped</e3q1:OldValue>
</EventD>

What I would need to do is to return all rows that have "NewValue" as "Running"
;WITH XMLNAMESPACES ('example2' as e3q1)
select top 100
Xml.value('(EventD/NewValue)[1]', 'varchar(100)'),

* from Table1
and Xml.value('(EventD/NewValue)[1]', 'varchar(100)') like 'Running'

Yet this does not seem to return any rows at all, would be really grateful if someone could point out what am i doing wrong here.
Thanks in advance,

A: Looks like  Jeroen Mostert already says all necessary
I can only add - name of namespace is not important, only uri
declare @xml xml='<EventD xmlns="http://example1" xmlns:e3q1="http://example2" xmlns:xsi="http://example3" xsi:type="e3q1:Valuechange">
  <e3q1:NewValue>Running</e3q1:NewValue>
  <e3q1:OldValue>Stopped</e3q1:OldValue>
  <xsi:test>test</xsi:test>
  <test1>test1</test1>
</EventD>'

;WITH XMLNAMESPACES ('http://example2' as test)
select
 @xml.query('(*/test:*)')

compare with result of
select
     @xml.query('(*/*)')

A: You do declare the namespace e3q1 (although it's missing the http:// and you don't use it later...), but you did not declare the default namespace
DECLARE @tbl TABLE([Xml] XML);
INSERT INTO @tbl VALUES
(
 N'<EventD xmlns="http://example1" xmlns:e3q1="http://example2" xmlns:xsi="http://example3" xsi:type="e3q1:Valuechange">
  <e3q1:NewValue>Running</e3q1:NewValue>
  <e3q1:OldValue>Stopped</e3q1:OldValue>
</EventD>'
);

;WITH XMLNAMESPACES (DEFAULT 'http://example1', 'http://example2' as e3q1)
SELECT [Xml].value('(EventD/e3q1:NewValue)[1]', 'varchar(100)')
from @tbl AS Table1
WHERE Xml.value('(EventD/e3q1:NewValue)[1]', 'varchar(100)') like 'Running';

But this approach is - at least I think so - not what you really want. I think you are looking for .nodes(). The next lines show as alternative an approach to replace namespaces with a wildcard. But I would recommend to be as specific as possible.
SELECT Only.Running.value('text()[1]', 'varchar(100)')
from @tbl AS Table1
CROSS APPLY Xml.nodes('*:EventD/*:NewValue[text()="Running"]') AS Only(Running)


text:
Q: GIS extension of Boost.Geometry I am using Boost 1.50.0 and I need to use the GIS extension of Boost.Geometry. Where can I find this extension for Boost 1.50.0 or lower? (I haven't upgraded my application to newer version of Boost due to some compatibility issues.)

A: The extensions are a part of the development version of a library, they're not released. So in order to use them you should probably checkout/clone (and use) the development version of Boost.Geometry. You could also try to mix the released version and the extensions from the development version but I'm guessing this way it'd be easier to make some mistake which would e.g. result in unwanted incompatibilities.
Anyway, the most simple way of doing it would be to see which commit was the most recent one in the Boost.Geometry released in Boost 1.50 (boost-1.50.0 tag in Boost.Geometry repository on GitHub):
https://github.com/boostorg/geometry/commits/boost-1.50.0
and then try to find a corresponding one in the develop branch:
https://github.com/boostorg/geometry/commits/develop
Note that you can find some commits in both branches that can't be found in the other. I don't know if that's because SVN was used back then or the reason is different. In your case I'd try with this commit from boost-1.50.0:
https://github.com/boostorg/geometry/commit/443b01bc07b0fb329aee803ea1bef6a8f14e449b
which seems to correspond to this commit in develop:
https://github.com/boostorg/geometry/commit/d35eb8f2dff20e61655fcef5ee4a23ca4d9d9847
so this is the develop tree:
https://github.com/boostorg/geometry/tree/d35eb8f2dff20e61655fcef5ee4a23ca4d9d9847
which you should be able to download by clicking the "Download ZIP" button on the right side of the page. Then you could use it instead of the released version or just extract the extensions from it, etc. Just have in mind it's not officially released version and that no guarantees can be made.
Here you can see the extensions in that tree:
https://github.com/boostorg/geometry/tree/d35eb8f2dff20e61655fcef5ee4a23ca4d9d9847/include/boost/geometry/extensions


text:
Q: Cyberoam authenticated network only allows browsers to connect to internet, not any other application I'm accessing my college network (which is protected via Cyberoam) via Wifi, and I need to authenticate to the network using my ID in the web browser. Once done, I can access internet with the browser (but, keeping the authentication tab opened).
But other web based apps in the computer can't access network (due to lack of authentication). For example, Windows Update is not working, chat clients can't connect (even on off days when social networking sites are allowed in the network).
Is there any way I can apply the authentication system-wide so that it works for every app installed? I'm looking for solution that works on both Windows and Ubuntu.

A: This could be due to application and website filtering rules configured by Firewall Admin on your college network. In many schools and colleges such restrictions are recommended by management.
You can check with your IT support or Firewall Admin about this and if he can help you resolve this issue.


text:
Q: CSS messes up when CACHE is cleared I have a wordpress site: www.gravitywild.com
The latests posts I've added don't show.
I talked to support and they told me to erase the site cache and so I did.
This is what the site looked like for me when I cleared the cache: www.gravitywild.com/home-nc.png
As you can see the site CSS is messed up. However they told me that this is how they were seeing the site:

I have cleared the browser cache and it still looks the same.
UPDATE 1: Bluehost support told me that it's a theme vendor bug.
Any ideas?

A: Caching is usually an issue with the visitor's browser. Sometimes they won't get a change that you have made to a page. So a Ctrl+F5 will force a reload of everything.
If you have enabled caching on the back-end (usually with a plugin), then you may need to rebuild the cache for that page. If you see the black admin bar at the top when you view the page, you might see a menu choice for "Cache" that will allow you to rebuild the site cache for that page.
If you have a 'cloud-based' site, then pages will be cached there, and a change that you make may not be visible until you clear the cache on your site.
If you are doing development work, then a theme code change, for example, may not show up, so you might have to force a full reload on your browser (Ctrl+F5), or perhaps rebuild that page's cache as described above.
Note that it always useful here to provide as much information about you problem as you can: the things you did, the way you did it, the outcome you expected, and the outcome you got (including any error messages). Adding this detailed information will ensure that you get a good answer.


text:
Q: If $|f(z)|=1$ , $f$ is holomorphic then $f$ is constant Let $G\subset \mathbb{C}$ be a region, $f$ a holomorphic function.
Then it does hold that:

*

*If $f(G) \subset \mathbb{R} \Rightarrow  f$ is constant

*If $|f(z)|=1$ for all $z \in G$, then $f$ is constant.
Proof of 1:
$f$ is holomorphic, so it holds that $$u_x=v_y; u_y=-v_x$$ where $f(z) = u(x,y)+iv(x,y)$, then $u_x=0$ and $u_y=0$ so $u,v$ both must be constant
Proof of 2:
$$|f(z)|= 1 \Rightarrow u^2+v^2=1 $$
taking the partial derivatives:
$$2uu_x+2vv_x=0 , 2uu_y+2vv_y= 0$$
putting inside the Cauchy-Riemann equations:
$$uu_x-vu_y=(u^2u_x^2-2uvu_xu_y+v^2u_y^2)=0; uu_y+vu_x=(u^2u_y^2+2uvu_xu_y+v^2v_y^2)=0$$
so either $u=v = 0$ or $u_x=u_y=0$
so $$\Leftrightarrow (u^2+v^2)(u_x^2+u_y^2)=0.$$
If everything was done correctly so far, wouldn't
switching $1$ with a constant $M$ give a proof for Liouville's theorem?

A: Both claims follow at once from the fact that a non-constant holomorphic function is an open map: Apparently, the image of $f$ is not open in $\mathbb C$.


text:
Q: What happened to mathmode documentation? There used to be a document distributed with TeXLive that contained a very nice description of the many different math modes, when they should be used, with examples of how to do it. I could easily open that document by issuing the command texdoc mathmode. Now that doesn't work.
I've searched online and can't find the document. Does it still exist, and if so, where can I find it?

A: The document still exists as mathmode on CTAN but it is considered obsolete with this "disclaimer":

The author considers this package now as being too old and afflicted with too many typographical bugs. That's why it has been classified as "obsolete", at least for the time being.

A: Because of the reasons Werner named, Herbert Voß, the author of mathmode wrote a replacement for the mathmode. He called it Typesetting mathematics with LaTeX (version 0.33, from 2017/8/9, checked on 2018/5/4).
Thank @gusbrs for the hints!


text:
Q: Lista con iconos no se colocan Tengo una lista que quiero que quede dividida en 2 columnas, para ello, usé este código:

.fila {
  display: flex;
}

.columna {
  display: flex;
  width: 33%;
  margin: 0px;
  align-items: center;
}

#contenido {
 background-color:none;
 float:left;
 width:100%;
 padding:15px;
 margin-top:7px;
 text-align:left;
}

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Ingredientes

            play_arrow
            2 huevos.

            play_arrow
            30 g de mantequilla pomada.

            play_arrow
            1 vaso de leche.

            play_arrow
             30 g de azúcar.

            play_arrow
             220 g de harina de trigo

            play_arrow
             1 trocito de mantequilla.

            play_arrow
             1/2 cucharadita de levadura química.

Pero en la web se ve así

A: Siguiendo el patrón de tu código solo deberias crear otro
 y agregar la tercera etiqueta
 que tienes en el primer div de la siguiente forma y cambiar el porcentaje de la clase columna por  width: 50%; para que abarque toda la página.

.fila {
  display: flex;
}

.columna {
  display: flex;
  width: 50%;
  margin: 0px;
  align-items: center;
}

#contenido {
 background-color:none;
 float:left;
 width:100%;
 padding:15px;
 margin-top:7px;
 text-align:left;
}

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Ingredientes

            play_arrow
            2 huevos.

            play_arrow
            30 g de mantequilla pomada.

            play_arrow
             30 g de azúcar.

            play_arrow
             220 g de harina de trigo

            play_arrow
             1 trocito de mantequilla.

            play_arrow
             1/2 cucharadita de levadura química.

            play_arrow
            1 vaso de leche.

A: En tu html en realidad tienes definidas 3 columnas, puedes usar el siguiente estilo:

Ejemplo:

.fila {
  display: flex;
}

.columna {
  flex: 50%;
}

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Ingredientes

            play_arrow
            2 huevos.

            play_arrow
            30 g de mantequilla pomada.

            play_arrow
            1 vaso de leche.

            play_arrow
             30 g de azúcar.

            play_arrow
             220 g de harina de trigo

            play_arrow
             1 trocito de mantequilla.

            play_arrow
             1/2 cucharadita de levadura química.


text:
Q: Porque recebo a mensagem de property is undefined mesmo com arrow function? Estou iniciando com react e não consigo entender porque do código abaixo não funcionar.
Recebo a seguinte mensagem:
"TypeError: can't access property "aoClicarNota", this is undefined"
Já estou utilizando o aoClicarNota como arrow function mas mesmo assim não funciona.
O que estou fazendo de errado?
import React from 'react';
import axios from 'axios';
import { Button, ButtonGroup, Container } from 'react-bootstrap';

class BlocoNotasPossiveis extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            notasPossiveis: [
                {
                    nota: '1',
                    descricaoCurta: 'Nota baixa',
                    descricaoLonga:
                        'Serviços sempre apresentam falhas, com grande impacto na produtividade, gerando retrabalho constantemente.'
                },
                {
                    nota: '2',
                    descricaoCurta: 'Nota ruim',
                    descricaoLonga:
                        'Serviços sempre apresentam falhas, com grande impacto na produtividade, gerando retrabalho constantemente.'
                }
            ]
        };
    }

    render() {
        return (

                <ButtonGroup aria-label="First group">
                    {this.state.notasPossiveis.map(this.renderizarBotao)}
                </ButtonGroup>

        );
    }

    aoClicarNota = () => {
        console.log("valor.nota")
    }

    renderizarBotao(valor) {
        return (
            <Button variant="primary" size="lg" onClick={this.aoClicarNota}>
                {valor.nota}
                {valor.descricaoCurta}
            </Button>
        );
    }
}

export default BlocoNotasPossiveis;

A: O problema está na sua função renderizarBotao. Dentro dela, você tenta acessar this.aoClicarNota, mas não há um this definido no contexto da função renderizarBotao.
Precisamos definir um this para a sua função renderizarBotao e podemos fazer isso de duas formas:

*

*Fazer o bind manualmente a partir de:
this.renderizarBotao = this.renderizarBotao.bind(this); no construtor da classe;

*Usar a sintaxe de arrow function para esta função também renderizarBotao = (valor) => {
Aqui um exemplo implementando arrow function:
https://codesandbox.io/s/react-playground-gp6io


text:
Q: html() does not retrieve the whole content I am getting the following response

        1

        2

Now I am trying to attach the rows like the following:
 function _ajax(postData)
    {
        loadUrl         = "getweblogs.asp";
        $.ajax( {
            url : loadUrl, // your ajax file
            type : 'post',
            data : postData,
            success : function( resp ) {
                alert($("#weblogs" , resp).html());
                $('#weblogs > tbody:last').append($("#weblogs" , resp).html());

            }
        });
        return false;
    }

The replace is working fine. My problem is, that the htmls elements from the response are removed. I'm getting only 1 and 2. instead of

        1

        2

I don't know what am I doing wrong. Could someone give me any clue?
Thank you!
Greetings
Magda

A: What you're trying to do is not so clear. Is there already an element with id="weblogs" in the page? If so, why does your response have an element with the same id (not a good idea), and if not, why are you trying to append an element's contents to itself like that (also, not a good idea)?
Why not just change the server-side to send the html required, without a wrapping div tag (which makes it invalid html anyway, another bad idea), and then use it as-is?
Another problem is that you're trying to select .html() of something that will always be an empty jquery object: $(selector, string) will never match anything. You'll need to make the string a jquery object if you want to search its substructure: string = $(string).
And I think you're misunderstanding the use of $(selector, $obj). The selector must be in the $obj's sub-structure:
$('#foo', $('

')); // returns empty jquery object
So looking for #weblogs in the substructure of an element with id weblogs will also never find anything.

A: Your question isn't entirely clear, but I'll try and answer: are you working with Internet Explorer? If so, consider this paragraph from the docs:

For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

API docs: html()


text:
Q: Error exporting the site field named "HashTags_0"." I am trying to save a site as template in SharePoint Server 2013 on premises but I keep getting this error:

Error exporting the site field named "HashTags_0"." ...

I don't see a field named 'HashTags_0' in site columns.Does anyone know how to resolve this?

A: I realized what the problem was. Even though I don't know what the cause is. When I view the site elements in SharePoint Manager 2013, the HashTag_0 field is there twice with the same GUID.
So I guess that when the export process cant overwrite the field a second time with the same GUID so it chokes.
My solution is to use powershell to delete duplicate fields as follows:
$web = Get-SPWeb http://somesite/someweb

$HashFields =  $web.Fields | Where {$_.Title -like 'HashTags_0'}

  foreach($F in $HashFields)

  {

    $F.Title

    if(!$F.Sealed){$F.delete()}

  }

$web.Update()

$web.Dispose()

After this I was able to Save site as template.
I hope this helps


text:
Q: What are cheaper alternatives to Adobe Illustrator on Windows, Mac, Linux? Background: I'm mostly a Mac user and have tried out Inkscape and even created SVGs with it, but it is highly user-unfriendly, it uses CTRL as the modifier key. I found VectorDesigner which seems promising so far. I also use Windows and Linux (Xubuntu and Ubuntu for desktop applications) so either of those would be great too.
So, finally: What are cheaper alternatives to Adobe Illustrator on Windows, Mac, Linux?
Thanks!

A: i'm using Xara Extreme (and Xara 3D); user-friendly, fast and reasonably priced.

for Windows $89, for Linux (Xara LX) $0

A: You could try Xara Xtreme. It's free to use and works on Linux only
By the way: What's wrong with Inkscape using CTRL as Control-Key?

A: On a Mac, check out Lineform ($80 USD):


text:
Q: BigQueryIO returns TypedRead instead of PCollection. How to get the real data? I have a problem with retrieving a data from bigquery table inside DoFn. I can't find example to extract values from TypedRead.
This is a simplified pipeline. I would like to check does record with target SSN exists or not in bigquery table. The target SSN will be received via pubsub in real pipeline, I have replaced it with array of strings.
final BigQueryIoTestOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(BigQueryIoTestOptions.class);

final List<String> SSNs = Arrays.asList("775-89-3939");

Pipeline p = Pipeline.create(options);

PCollection<String> ssnCollection = p.apply("GetSSNParams", Create.of(SSNs)).setCoder(StringUtf8Coder.of());

ssnCollection.apply("SelectFromBQ", ParDo.of(new DoFn<String, TypedRead<TableRow>>() {
  @ProcessElement
  public void processElement(ProcessContext c) throws Exception {
    TypedRead<TableRow> tr =
    BigQueryIO.readTableRows()
    .fromQuery("SELECT pid19PatientSSN FROM dataset.table where pid19PatientSSN = '" + c.element() + "' LIMIT 1");

    c.output(tr);
  }
  }))
.apply("ParseResponseFromBigQuery", ParDo.of(new DoFn<TypedRead<TableRow>, Void>() {
  @ProcessElement
  public void processElement(ProcessContext c) throws Exception {
    System.out.println(c.element().toString());
  }
}));

p.run();

A: Big query returns PCollection only, we can get the result as entry set like the below example or we can serialize to objects as well like mentioned here
If you want to query from BigQuery middle of your pipeline use BigQuery instead of BigQueryIO like mentioned here
BigQueryIO Example:
PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create();
Pipeline pipeline = Pipeline.create(options);
PCollection<TableRow> result = pipeline.apply(BigQueryIO.readTableRows()
                .fromQuery("SELECT id, name FROM [project-test:test_data.test] LIMIT 1"));
result.apply(MapElements.via(new SimpleFunction<TableRow, Void>() {
            @Override
            public Void apply(TableRow obj) {
                System.out.println("***" + obj);
                obj.entrySet().forEach(
                        (k)-> {
                            System.out.println(k.getKey() + " :" + k.getValue());
                        }
                );
                return null;
            }
        }));
        pipeline.run().waitUntilFinish();

BigQuery Example:
// [START bigquery_simple_app_client]
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
// [END bigquery_simple_app_client]
// [START bigquery_simple_app_query]
QueryJobConfiguration queryConfig =
    QueryJobConfiguration.newBuilder(
      "SELECT "
          + "CONCAT('https://stackoverflow.com/questions/', CAST(id as STRING)) as url, "
          + "view_count "
          + "FROM `bigquery-public-data.stackoverflow.posts_questions` "
          + "WHERE tags like '%google-bigquery%' "
          + "ORDER BY favorite_count DESC LIMIT 10")
        // Use standard SQL syntax for queries.
        // See: https://cloud.google.com/bigquery/sql-reference/
        .setUseLegacySql(false)
        .build();

// Create a job ID so that we can safely retry.
JobId jobId = JobId.of(UUID.randomUUID().toString());
Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

// Wait for the query to complete.
queryJob = queryJob.waitFor();

// Check for errors
if (queryJob == null) {
  throw new RuntimeException("Job no longer exists");
} else if (queryJob.getStatus().getError() != null) {
  // You can also look at queryJob.getStatus().getExecutionErrors() for all
  // errors, not just the latest one.
  throw new RuntimeException(queryJob.getStatus().getError().toString());
}
// [END bigquery_simple_app_query]

// [START bigquery_simple_app_print]
// Get the results.
QueryResponse response = bigquery.getQueryResults(jobId);

TableResult result = queryJob.getQueryResults();

// Print all pages of the results.
for (FieldValueList row : result.iterateAll()) {
  String url = row.get("url").getStringValue();
  long viewCount = row.get("view_count").getLongValue();
  System.out.printf("url: %s views: %d%n", url, viewCount);
}
// [END bigquery_simple_app_print]


text:
Q: setDT() has unexpected side effect This question is not a duplicate of Error in setDT from data.table package.
library(data.table)
dt <- iris
str(iris) # a data.frame solely
setDT(dt)
str(iris) # data.frame and data.table

Why should setDT() act on an object that is not its argument?
Thank you all for pointing out why iris is changed in parallel with dt. Unless one knew the answer already, there would be no way to know that the question was a duplicate.

A: Your objects iris and dt have the same address in memory. You can make a real copy by dt <- data.table::copy(iris).
Consider this:
dt <- iris
> tracemem(iris) == tracemem(dt)
[1] TRUE

but
dt <- data.table::copy(iris)
> tracemem(iris) == tracemem(dt)
[1] FALSE

Reason
?data.table::setDT says:

When working on large lists or data.frames, it might be both time and memory consuming to convert them to a data.table using as.data.table(.), as this will make a complete copy of the input object before to convert it to a data.table. The setDT function takes care of this issue by allowing to convert lists - both named and unnamed lists and data.frames by reference instead. That is, the input object is modified in place, no copy is being made.


text:
Q: BWA can't find the local index file I'm currently trying to import a .fasta file into bwa to use a reference genome to map my reads to. However, i currently am getting this error:
[E::bwa_idx_load_from_disk] fail to locate the index files

Any help? Here is my code:
#!/bin/bash

source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load fastqc/0.10.1
module load fastx/0.0.13
source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load pear/0.9.10
source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load fastqc/0.10.1
module load fastx/0.0.13
module load bwa/0.7.12
module load samtools/1.2
source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load trimmomatic/0.35

r=20
####mapping
#Indexing reference library for BWA mapping:
bwa index -a is ~/gz_files/sample_things/fungiref.fa fungiref

bwa mem fungiref sample${r}_clipped_paired.assembled.fastq > sample${r}.sam

#sort and convert to bam
samtools view -bS sample${r}.sam | samtools sort - sample{r}_sorted

#counts and stats
samtools index sample${r}_sorted.bam
samtools idxstats sample${r}_sorted.bam > ${r}_counts.txt

A: The usage for bwa index is
bwa index [-p prefix] [-a algoType] <in.db.fasta>

Your usage doesn't match this; it's a shame that bwa silently accepts this instead of immediately throwing an error. Annoyingly, there is also simply no way to specify a path prefix for the index. You're stuck with the location of your reference.
At any rate, the index filename is derived from the FASTA reference file. As a consequence you need to adjust your index filename in the subsequent command:
bwa mem ~/gz_files/sample_things/fungiref.fa sample${r}_clipped_paired.assembled.fastq > sample${r}.sam


text:
Q: sunburst.R total frequency count is incorrect I am plotting a sunburst donut and I cannot figure out why the total is incorrect.
library(sunburstR)
reports <- data.frame(
    sequence = c("SVP-VP-Dir-end","SVP-VP-Dir-end","SVP-VP-Dir-end","SVP-VP-Dir-end","SVP-No VP-Dir-end","SVP-No VP-Dir-end","SVP-No VP-Dir-end"),
    freq = as.numeric(c("167","60","51","32","5","1","1")))

sunburst(reports, count = TRUE)

It is supposed to be 100% 317 of 317 . Anyone know how to fix this? There is not much documentation on this great package.
Also, I would like it to have a default value in the center of donut.

If there is another way to create an interactive donut using R, please let me know.
Thanks you in advance.

A: It looks like the default function generating the message in the center of the donut rounds the total value to the nearest ten.
But you can customize this function using the explanation argument of sunburst. Oddly, the customized function (in javascript) must be provided as a string.
Try the following function:
custom.message = "function (d) {
  root = d;
  while (root.parent) {
    root = root.parent
  }
  p = (100*d.value/root.value).toPrecision(3);
  msg = p+' %
'+d.value+' of '+root.value;
  return msg;
}"

Now:
sunburst(reports, explanation = custom.message )

will generate the donut displaying exact total values. The count argument is no longer needed, as it is used by the default explanation function.
The value returned by custom.message is html code. As you can see, I've just inserted a line break (
). You can modify the msg return value to further customize the look and feel.


text:
Q: How do I mock the http requests in my case I am having a weird issue regarding my unit test.
In controller I have something like
testFactory.testFunction($scope.id)
       .then(function(returnData) {
           // do something with the return
       })

Factory file
test.testFunction = function(id) {
        return $http.get('/api/v.10/book/' + id + '/books');
};

unit test
var books = {data: {id: 333, name: 'my book'}};

beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, _testFactory_) {
        scope        = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;
        testFactory = _testFactory_;

        testCtrl = _$controller_('testCtrl', {
            $scope: scope
        });

        $httpBackend.whenGET('/api/v.10/book/333/books').respond(books);
    }));

 it('should check if test runs', function() {
         testFactory.testFunction(333).then(function(returnData){
                console.log(returnData)
         })
         $httpBackend.flush();
  })

For some reason, the console.log for the 'returnData' add the 'books' variable to an objects and add headers, status…etc to the response.
For example:
Object{data: Object{data: Object{id: ..., name: ...}},
             status: 200, headers: function (name) { ... },
             transformResponse: [...],
             url: '/api/v.10/book/333/books', statusText: ''}

I am only expecting
{data: {id: 333, name: 'my book''}} as my response.
Can someone help me about the issue?
Thanks a lot!

A: When using respond with a single parameter, it should be the data object you want returned to your web service, as shown under when in the docs. So you need to change your books variable to just {id: 333, name: 'my book'}.


text:
Q: Android legacy launcher icon dimensions and padding I am looking for the Android specification for legacy launcher icons.
I found the specification for Android adaptive icons, which is 108x108, with content inside a 72x72 for mdpi: https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive
I also found the specification for Android Play Store icon, which is 512x512, with content inside 384x384 (75%). https://developer.android.com/google-play/resources/icon-design-specifications
However, I cannot seem to find the specification for legacy launcher icons. i.e. The main thing I'm looking for is:

*

*Size of the padding

*Radius size

*Shadow properties

According to this:
https://iconhandbook.co.uk/reference/chart/android/
the mdpi size is 48x48, but no mention of padding, corner radius, shadow etc.

A: If you're in Android Studio, and you do "Image Asset" in the Resource Manager's add (+) menu, you can take the 512x512 icon and it will generate the others for you, including a legacy version - there are a few options like Round, Square, and some weird long ones.
Just eyeballing it, they look identical to the standard Round Icon and Square Icon previews for the adaptive icons that get generated, I think they're just literally taking either of those and making a "legacy" copy.
Sorry that's not very concrete - if it helps the generated icon is 48px by 48px for mdpi! And there's more info about the actual design specs here:
https://material.io/design/iconography/product-icons.html#grid-and-keyline-shapes
I know, this info is all over the place and it's really hard to find everything you need. But personally, designing for those adaptive specs and just letting the Resource Manager handle generating the icon worked well for me, I'd use that if you can


text:
Q: PROJ.4 cs2cs is too slow. Alternative? I use PROJ.4 cs2cs to convert data from a Lambert Conformal Conic to a geodetic coordinate (NAD83) or vice versa. In my application, sometimes I need to convert a lot of data. Because I call cs2cs with subprocess.Popen() and parse result in python, input/output overhead becomes too big for a large data set.
Is there an faster alternative to cs2cs or a way to make calling cs2cs in python faster?

A: The answer is Pyproj. Transforms lists of coordinates in a single call, and since it's a C extension module that uses PROJ.4, the same results as cs2cs but at C speed.