text:
Q: Getting just the latest value on a joined table with Eloquent I have two tables like this:
products:
+----+-----------+
| id |   name    |
+----+-----------+
|  1 | Product 1 |
|  2 | Product 2 |
|  3 | Product 3 |
|  4 | Product 4 |
+----+-----------+

prices:
+----+-------+------------+---------------------+
| id | price | product_id |     created_at      |
+----+-------+------------+---------------------+
|  1 |    20 |          1 | 2014-06-21 16:00:00 |
|  2 |    10 |          1 | 2014-06-21 17:00:00 |
|  3 |    50 |          2 | 2014-06-21 18:00:00 |
|  4 |    40 |          2 | 2014-06-21 19:00:00 |
+----+-------+------------+---------------------+

I have this relationship on Product:
public function prices()
{
    return $this->hasMany('Price');
}

I can easily run Product::with('prices')->get(); to get each product with each of the prices it's had.
How can I use Eloquent to only get the most recent price? (Also, what if I wanted the cheapest/most expensive price instead?)

A: When Laravel eager loads a relationship, it will perform two queries similar to this:
SELECT * FROM products WHERE 1;
SELECT * FROM prices WHERE product_id = 1;

What you want to do is to add a condition to the second query to get the row with most recent price. So you would want something like this:
SELECT * FROM products WHERE 1;
SELECT * FROM prices WHERE product_id = 1 ORDER BY price;

Luckily in Laravel's Eager Load Constraints you can, instead of passing a string into with(), you can pass an array with the relationship name as key and a subquery closure as its value. Like this:
$products = Product::with(array('prices' => function($query)
{
    $query->orderBy('created_at', 'desc');
}))->get();

Then in your code you can do:
$product->prices->first();

to get the most recent price of each product.
Note: You may notice that Laravel will still load all the prices for each product. I don't think there's a way around it while still using purely Eloquent because the way eager loading work is fetching all the relationship records in one single query, so there isn't an easy way to say get only the most recent price for each product.

Another solution:
However, if you are strictly needing to know just a value from another table, you could do a sub-select instead:
$products = Product::select('*')
    ->addSelect(DB::raw('(SELECT price FROM prices WHERE products.id = prices.product_id ORDER BY created_at DESC LIMIT 1) price'))
    ->get();

A: You can tweak your relations to get what you want. Accepted answer of course works, however it might be memory overkill with lots of data.
Find out more here and there.
Here's how to use Eloquent for this:
// Product model
public function latestPrice()
{
   return $this->hasOne('Price')->latest();
}

// now we're fetching only single row, thus create single object, per product:
$products = Product::with('latestPrice')->get();
$products->first()->latestPrice; // Price model

That's nice, but there's more. Imagine you'd like to load highest price (just a value) for all the products:
public function highestPrice()
{
   return $this->hasOne('Price')
      ->selectRaw('product_id, max(price) as aggregate')
      ->groupBy('product_id');
}

Not very convenient yet:
$products = Product::with('highestPrice')->get();
$products->first()->highestPrice; // Price model, but only with 2 properties
$products->first()->highestPrice->aggregate; // highest price we need

So add this accessor to make the life easier:
public function getHighestPriceAttribute()
{
    if ( ! array_key_exists('highestPrice', $this->relations)) $this->load('highestPrice');

    $related = $this->getRelation('highestPrice');

    return ($related) ? $related->aggregate : null;
}

// now it's getting pretty simple
$products->first()->highestPrice; // highest price value we need


text:
Q: opencv didn't output images correctly I have debugging my code and here is what I found:
img = cv2.resize(img, (224, 224))

cv2.imshow("img",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

img = (img / 127.5) - 1

cv2.imshow("img",(127.5*(img+1)).astype(int))
cv2.waitKey(0)
cv2.destroyAllWindows()

these operations don't output the same picture even tough they are same, does somebody konow why?

A: Try checking the dtype each time you display:
print(img.dtype)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selecting optimal PayPal API I've been given a task to integrate PayPal API to an already existing website, where buyer details should be taken out from the existing user database and all front-end design should be custom - created as part of whole system design.
I basically need to select PayPal API that will allow me to simply authorize and invoke credit card charge for selected amount of cache based on user details and credit card information.
Which of the PayPal API's is designed for this?

A: You would want to use Payments Pro for that.


text:
Q: solr displayed some results first when they are part of the results I consider this solr psedo-doc
<doc>
<field name="title"/>
<field name="name"/>
<field name="keywords"/>
</doc>

Some doc's will have the keyword "up" which means that they should appear first (despite of their initial order position) when and only when they are part of the search results.
So lets say I have:
doc1('title1','Bob, Alice','people, up, couple')
doc2('title2','Smart Phone, Laptop, Bob','devices, electronics')

if I query with "title:title2 name:Bob" then I should get doc1 first (it has the 'up' keyword).
if I query with "name:Bob" I still get doc1 first for the same reason.
if I query with "name:Laptop" then I should only get doc2 in my results. doc1 should not be included since it doesnt match my search query.
Any suggestion to do this?

A: This can be solved with Solr's query time boosting. So following the guidance from the Solr Relevancy FAQ - you could add an additional boosted search term to all queries, e.g. title:title2 name:Bob keywords:up^2
You could also at index time for each document, determine if the up keyword is present then store that in an additional field (boolean for example) in your schema and boost the query results based on that boolean field.

A: You have several options to do something like that:

*

*function query / boost query (in dismax handler)

*during index time (boost documents)

*extract 'up' keyword to additional field and sort by this field, than score

For example (with dismax handler):
 /select?defType=dismax&q=...&bq=keywords:"up"^1000


text:
Q: How to calculate marginal effects of logit model with fixed effects by using a sample of more than 50 million observations I have a sample of more than 50 million observations. I estimate the following model in R:
model1 <- feglm(rejection~  variable1+ variable1^2 +  variable2+ variable3+ variable4 | city_fixed_effects + year_fixed_effects, family=binomial(link="logit"),  data=database)

Based on the estimates from model1, I calculate the marginal effects:
mfx2 <- marginaleffects(model1)
summary(mfx2)

This line of code also calculates the marginal effects of each fixed effects which slows down R. I only need to calculate the average marginal effects of variables 1, 2, and 3. If I separately, calculate the marginal effects by using mfx2 <- marginaleffects(model1, variables = "variable1") then it does not show the standard error and the p-value of the average marginal effects.
Any solution for this issue?

A: Both the fixest and the marginaleffects packages have made recent
changes to improve interoperability. The next official CRAN releases
will be able to do this, but as of 2021-12-08 you can use the
development versions. Install:
library(remotes)
install_github("lrberge/fixest")
install_github("vincentarelbundock/marginaleffects")

I recommend converting your fixed effects variables to factors before
fitting your models:
library(fixest)
library(marginaleffects)

dat <- mtcars
dat$gear <- as.factor(dat$gear)

mod <- feglm(am ~ mpg + mpg^2 + hp + hp^3| gear,
             family = binomial(link = "logit"),
             data = dat)

Then, you can use marginaleffects and summary to compute average
marginal effects:
mfx <- marginaleffects(mod, variables = "mpg")
summary(mfx)

## Average marginal effects
##       type Term Effect Std. Error  z value Pr(>|z|)  2.5 % 97.5 %
## 1 response  mpg 0.3352         40 0.008381  0.99331 -78.06  78.73
##
## Model type:  fixest
## Prediction type:  response

Note that computing average marginal effects requires calculating a
distinct marginal effect for every single row of your dataset. This can
be computationally expensive when your data includes millions of
observations.
Instead, you can compute marginal effects for specific values of the
regressors using the newdata argument and the typical function.
Please refer to the marginaleffects documentation for details on
those:
marginaleffects(mod,
                variables = "mpg",
                newdata = typical(mpg = 22, gear = 4))

##   rowid     type term     dydx std.error       hp mpg gear predicted
## 1     1 response  mpg 1.068844   50.7849 146.6875  22    4 0.4167502


text:
Q: ruby search for name and value in nokogiri object The code below will get me all nodes with name=visible, like this node:
<property name="visible" value="false"/>

  vis = @noko_obj.search("property[name=visible]")

...regardless of what value is.  However, what if I want the nodes whose name="visible" AND whose value="true"?
thanks

A: Just add another attribute selector:
vis_true = @noko_obj.search('property[name=visible][value=true]')

The order of the attribute selectors doesn't matter so you could also do this:
vis_true = @noko_obj.search('property[value=true][name=visible]')


text:
Q: How to use regex in xsl I have this request coming in xml. Its a CDATA
<cmd>
     <![CDATA[HG<><><36.75><0420>< ><HS6011201700446279><><>< >< ><  ><><><  ><><  ><  ><><  ><><  ><>]]>
</cmd>

I need to extract HS6011201700446279 from the cdata path.
Following is the regex they gave. How to use this in xsl
HG<\\s*><\\s*><.*><.*><.*><[A-Z]{2}(\\d{10,}).*

A: There is no regex support in XSLT 1.0. Assuming that the sub-string you want is within the 6th "tag" of the given string, you could extract it by calling a recursive named template:
<xsl:template match="cmd">
    <result>
        <xsl:call-template name="get-Nth-value">
            <xsl:with-param name="list" select="."/>
            <xsl:with-param name="N" select="6"/>
        </xsl:call-template>
    </result>
</xsl:template>

<xsl:template name="get-Nth-value">
    <xsl:param name="list"/>
    <xsl:param name="N"/>
    <xsl:param name="delimiter" select="'><'"/>
    <xsl:choose>
        <xsl:when test="$N = 1">
            <xsl:value-of select="substring-before(concat($list, $delimiter), $delimiter)"/>
        </xsl:when>
        <xsl:when test="contains($list, $delimiter) and $N > 1">
            <!-- recursive call -->
            <xsl:call-template name="get-Nth-value">
                <xsl:with-param name="list" select="substring-after($list, $delimiter)"/>
                <xsl:with-param name="N" select="$N - 1"/>
                <xsl:with-param name="delimiter" select="$delimiter"/>
            </xsl:call-template>
        </xsl:when>
    </xsl:choose>
</xsl:template>


text:
Q: How to connect to Informix DB on host machine from a container through jdbc? Informix db 12.10 is installed and works fine to connect via a java application using informix jdbc, both are on host machine. When I use a docker container to run my java application and connect to Informix on host machine, it does not connect.
The docker0 on host machine shows 172.17.0.1 and ip of container is 172.17.0.2.
ping works between two IPs
is there any setting required to bind informix to 0.0.0.0 or to pass --host variable to container while starting it?

A: Informix needs to listen on the IP through which you'd like to connect. In case Informix is listening only on 127.0.0.1, you cannot connect through 172.17.0.1.
One way to fix this is to configure Informix to listen on 0.0.0.0. This way if you try to connect through docker0's 172.17.0.1, it should work.


text:
Q: Как отобразить спецсимволы в android? Мне нужно подписать единицы измерения на шкале прибора: кгс/см квадратный. Разработка в Android Studio. Подскажите, как можно отобразить сам символ квадрата. Как отобразить спецсимволы в интернете я нашла. Но там нет квадрата.

A: <string name"kgs_sm_2">кгс/см2</string>

XML поддерживает простейшие HTML теги

A: <string name="kgs_sm_2">кгс/см²</string>

Я использую десятичный код, Ваш пример будет выглядить так.

A: HTML теги в данном случае не нужны. Символы ² и ³ можно использовать без каких-либо ограничений. Их начертание есть во всех шрифтах на android и проблем не возникнет.
Например, в XML:
<string name="unit_kgf_cm2">кгс/см²</string>

или в коде:
textView.setText("кгс/см²");

Вместо символа можно использовать его код U+00B2 (178).
В XML:
<string name="unit_kgf_cm2">кгс/см²</string>

В коде:
textView.setText("кгс/см\u00B2");

Но по мне так такой вариант только ухудшает читаемость.
В данных случаях это обычные строки и работают все соответствующие операции. Например, не возникает проблем при такой конкатенации:
String value = "0.5 " + getString(R.string.unit_kgf_cm2);
textView.setText(value);

Конечно, можно использовать и HTML теги:
<string name"kgs_sm_2">кгс/см2</string>

Но в этом случае это уже будут не обычные строки, а текст с форматированием и это нужно будет везде учитывать. Предыдущий пример уже будет выглядеть примерно так:
CharSequence value = TextUtils.concat("0.5 ", getText(R.string.unit_kgf_cm2));
textView.setText(value);


text:
Q: How to check if the current presented view controller is MPMoviePlayerController? I tried this to get the current view controller and check if its a kind of class of MPMoviePlayerController or not but it always returns the last view controller before the MPMoviePlayerController.
[self.window.rootViewController.presentedViewController.childViewControllers firstObject]

so how to check if the presented controller is a MPMoviePlayerController?

A: Firstly I think it should be MPMoviePlayerViewController and not MPMoviePlayerController when it is the view controller that you are trying to check here.
If that is correct then once you present the MPMoviePlayerViewController via
[self presentMoviePlayerViewControllerAnimated:movieplayer]; // movieplayer being your MPMoviePlayerViewController's instance

then you should be able to verify the present viewcontroller via
[[self presentedViewController] isKindOfClass:[MPMoviePlayerViewController class]]; // will return true


text:
Q: Show/Hide inside of Cloned div via dropdown selection I've modified Josiah's answer from clone form element with increment
which is working well for me however now I need to extend it a little further with the abiltiy to show and hide additional fields from inside a cloned div
JS Fiddle
I need to show div.hidden if #delivery_mode selection value is 1 or 2 and make sure it works for each cloned div.
Javascript
$(document).ready(function(){
var template = $('#products .product:first').clone();
var productsCount = 1;
window.addProduct = function(){
    productsCount++;
    var product = template.clone().find(':input, div').each(function(){
        var newId = this.id.substring(0, this.id.length-1) + productsCount;

        $(this).next().attr('for', newId); // update label for
        this.id = newId; // update id and name (assume the same)
        }).end()
        .attr('id', 'product' + productsCount)
        .appendTo('#products');
        }
$('.add').click(addProduct);

$("a#rp").click(function () {
if ($(".product").length != 1) {
    $(".product:last").remove();
    }
        event.preventDefault();
    });
 });

Array for days:
$days = array("0" => "Monday", "1" => "Tuesday", "2" => "Wednesday",
 "3" => "Thursday", "4" => "Friday", "5" => "Saturday", "6" => "Sunday"); ?>

HTML

                        Delivery Mode

                                    <select name="delivery_mode[]" class="delivery_mode">
                                        <option value="0">Online</option>
                                        <option value="1">FT</option>
                                        <option value="2">PT</option>
                                    </select>

                        @foreach($days as $day)
                            <input name="<?php echo $day; ?>[]" id="<?php echo $day; ?>_1" value="1" type="checkbox" class="is-checkradio is-white f_input" />
                            <label for="<?php echo $day; ?>_1"><?php echo $day; ?>
                        @endforeach

Remove
Product

Add
Product


text:
Q: Alamofire dealing with special character parameters the ServiceKey I got for the api is mixed with complex characters, like D%2FFgugDIl1le9xiY7be1ge%2B0Q%3D%3D
and when I put the key in the params of alamofire and use the .get keyword, my key transforms and when the url is actually created, it becomes a totally different key.
is there any way to solve this problem?
This is the code I am using
Alamofire.request(BusURL, method: .get, parameters: ["cityCode": 25, "routeId":"DJB30300052ND", "ServiceKey": key])
        .responseString { response in
            print(" - API url: \(String(describing: response.request!))")   // original url request
            var statusCode = response.response?.statusCode

            switch response.result {
            case .success:
                print("status code is: \(String(describing: statusCode))")
                if let string = response.result.value {
                    print("XML: \(string)")
                }
            case .failure(let error):
                statusCode = error._code // statusCode private
                print("status code is: \(String(describing: statusCode))")
                print(error)
            }
    }

A: Try below:
let params = ["cityCode": "25", "routeId":"DJB30300052ND"]
        var urlParams = params.flatMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }).joined(separator: "&")

        let key = "&ServiceKey=D%2FFgugDIl1le9xiY7be1ge%2B0Q%3D%3D"
        urlParams.append(key)

        let url = "https://google.com?\(urlParams)"
        print("url\(url)")
        Alamofire.request(url, method: .get).validate().responseString(completionHandler: {response in
            switch response.result{
            case .success:
                let s = response.result.value ?? "Empty Result"
                print("response \(s)")
            case .failure:
                print("Call Failed")
                debugPrint(response)
            }
        })

output: https://google.com?cityCode=25&routeId=DJB30300052ND&ServiceKey=D%2FFgugDIl1le9xiY7be1ge%2B0Q%3D%3D


text:
Q: Synchronize local SQLite database with central database We are developing an Android App based on a product that already has a website. As a result, when launching the Android app it may happen that a lot of things differ between the local SQLite database and our central database.
What is the fastest way to synchronize the Android App?

*

*Compare the data in our central database with the SQLite database and update/insert/delete accordingly (for each table)?

*Or just drop the concerning tables and create them again - and execute a transaction with compiled statements?

Sounds like the first option may be very slow.
Any help would be appreciated!

A: In your case needs value the situation!! When I have this problems the first questions are...

*

*The tables that I want to do 'drop table' have few data? If it's yes the best way is the 'drop table' command. If it's no then you need to use the 'insert' and 'update' commands. I need to remark that it's possible that the SQLite database grows with time, then the good programmer would second way because it's more secure and you think with future possibilities.

*My app syncs any time or syncs a few times a day? If the answer is in any time then you need use the 'insert' and 'update' commands. Because you can't delete database tables every minutes or seconds.
Tell me if I helped you and good programming!


text:
Q: How to dissipate a lot of current Lets say I want to test out a sine wave 120V 15Amp inverter by drawing 15 amps of resistive load. How can I draw this without generating very much heat, and optimized for as small as possible.

A: You are converting energy from one form to another.  So since you state that converting electrical energy into heat is not acceptable I suggest another form, say, potential energy?  drive a motor to get you to the top of a hill, a rail gun to shoot down an airplane ?  Or store it in chemical energy, and run an electrolysis bath, say, water to get you Hydrogen and Oxygen?

A: You will generate a lot of heat. 1800W actually. You can use an usual home fan heater for this task - it has similar characteristics and is suitable to work on high temperatures.
Other household heating devices - electrical stoves, water heaters may do the job as well.

A: The power has to go somewhere.  Usually it is heat, and commonly such things are designed around power resistors, though in some shops I've been in they actually switched in typical electrical heaters one might use in a house, due to their cheap availability.
The only other options without generating heat are to try to push that power back into another sink - for instance convert that energy into 48V, then use an inverter to push it back onto the power line, similar to the way solar panel systems push energy onto the grid.  This produces less heat, but is far from compact and inexpensive. However it's becoming more common in equipment testing to save energy, which is only going up in cost.
Another option that is smaller and much less expensive is to convert that energy to light.  It won't be particularly small, and it will still generate a good bit of heat, but if you need more lighting in your workarea (and I've rarely seen an engineer claim there's too much light for their workarea) then this might be a good solution.
Mechanical energy might be useful - run some fans off it, or spin up a flywheel. Pump water from a storage tank to another storage tank and reverse the pump when one gets too full. Charge some batteries, or electric vehicles. An air conditioner, heat pump, or refrigerator could eat a lot of power,  though you might consider pumping heat from one place to another generating heat, but again you need to pick your poison.  If you don't want heat, then do you want light?  Electricity? Electromagnetic waves?

A: Your inverter is putting out 15 A at 120 V into a resistive load.  That means (15 A)(120 V) = 1.8 kW is being moved from your inverter to somewhere.  That's basic physics you can't change.  Your only choice is what to do with the 1.8 kW.
Others have already given you plenty of ideas for how to dissipate it.  I usually use LEBs (light emitting bulbs) for this.  They are designed to dissipate significant power, are cheap, and inherently indicate when dumping power.
One issue is that they are non-linear, but this can actually be a advantage.  They look resistive (current will be proportional to voltage) in the short term of a power cycle or a few.  In the long term, this resistance varies with voltage such that lower voltages cause lower resistance.  This makes the power they dissipate less sensitive to the voltage than a resistor.  That can be useful as the inverter will still be putting out closer to the desired power than when driving a resistor when the voltage changes a bit.
However, the real point of this answer is to mention something called a electronic load.  This is a device specifically designed to do what you want.  It's like a power supply in reverse.  You can adjust it to draw some set voltage, power, or current, cause load step changes, and the like.  These things are intended for testing power supplies.
High power electronic loads usually absorb the power from the power supply under test and dump it back onto the AC line.  Instead of heating the room with 1.8 kW, only a few 100 W might be released as heat, with the rest going back to the AC line.
These things are expensive and not that easy to find, so I don't recommend going out and buying one.  Now that you know what to look for, maybe you can find someone that happens to have one, or get permission to use one after hours somewhere.  Chances are a local university has one.  If you know someone that is a student or a faculty member there, maybe you can get access when nobody else is trying to use it.

A: Consider purchasing a 1200 and a 600 watt space heater. You could get either the resistive wire/ribbon type or get a quartz rod type heater. These would make a good load for your inverter.
You have to face it that there is no such thing as trying to dissapate about 1800 watts of power without generating a lot of heat. And doing that is a very small size would be a serious challenge.
I like using resistive space heaters for loads becasue they are fully designed to throw off all the heat. They also come equipped with a very handy power cord that makes connecting the load very easy.

A: Check the specs of a lady's hair dryer.  Some are 1800 watts @ 120v AC.  Connect it up/plug it in and set it on highest heat and test away.
Best after a shower :D
Failing that, try an electric frying pan.  Bacon makes a great test addition.
 :)

A: 15 amps of resistive load quite literally means the power dissipated is \$15^2\times R\$ and at 120V RMS this is going to be 1.8kW.
If, on the other hand you want to test the system with 15 amps of reactive load you'll need an impedance that is \$\dfrac{120}{15}\$ = 8 ohms and this has to be a reactive impedance such as from an inductor or capacitor.
At 60Hz, the inductor's reactance is 8 ohms therefore it's inductance is \$\dfrac{8}{2\pi F}\$ = 21.2mH.
To avoid saturation of the core (because you'll need a core) it'll be a 5" to 10" cube off the top of my head.

A: The smallest way to dissipate that amount of power via heat is fans and load resistors attached to heatsinks. It's noisy and warms the workshop up nicely.
The other way is to water cool the loads. For less than 30V loads you can always submerge it in a bath of water and have the inflow and drain taps  cracked open. Requires metal resistors and is not a permanent solution. (I got nervous just watching it being set up, it wasn't my idea, but it got the job done)
For higher voltage you need cooling loops through heatsinks and plumbing.
Water and high voltage (over 30V) is serious stuff so not my option of choice.

A:
simulate this circuit – Schematic created using CircuitLab


text:
Q: split one column from import into 2 column in database i have a file i need to import that has a column with the settings A, S and B in them,
i would like to split this column and and all the A's go into a column but be reset to a 1 and the rest to go into another column and changed to a 1.
is this possible in derived columns?

A: I'm not 100% sure what you're asking for but how about something like this:
SELECT
  CASE ImportColumn WHEN 'A' THEN 1 ELSE NULL END AS [A Column]
, CASE ImportColumn WHEN 'A' THEN NULL ELSE 1 END AS [Other Column]
FROM
  Import

When the value is 'A' then a row will be added with the first col 1 and 2nd col null.
When the value is not 'A' then a row will be added with null in first col and 1 in the second.  Is that what you meant?

A: The answer is to create two derived columns using an If statement
([Product Type Code] == "A" ? "1" : "0")
and invert the outcome for the other derived column.


text:
Q: SPFieldLookupValue and unboxing I have a general question around unboxing vs parsing of the identity property on an SPFieldLookupValue.
Let's say, we have a call to a list and we get a reference to the a lookup field:
// call to site / web, get instance of class and iterate through records
// find column [lookup field]
SPFieldLookupValue fieldName = item["ALookupField"] as SPFieldLookupValue;

In the example above, I have a reference to the lookup value, whereby I can pull the Id and the Value separately instead of working with a string (ie. id#value).
Now, the LookupId property is of type object, but I know that this value will in almost all cases be an integer, so my assumption here is that I can do:
int id = (int)fieldName.LookupId;

But, obviously I need to ensure that I am working with an integer, so I should, in theory, try and parse this to the type I need:
bool isInt = int.TryParse(fieldName, out intField);

I know that this is probably more accurate, but my question is why can I not explicitly unbox the object, to it's int equivalent, when I know that it will most likely always be an int?

A: LookupId is of type int. See here


text:
Q: reply-with history Xpages how? I would create a simple Reply-With-history function that from an XPages with RichText Control (that use CkEDITOR) open another XPages with the history of previous PAGE
(richtext + attachments + images etc...)
I think that is possible..but I don't know the correct way for this.
Anyone have any suggestion?
Tnx to all
P.S. Think that you have a inbound email document and you create the button reply-with-history-and-attachments...the Inotes open a new WebPage with CkEditor that into the body there are the inbound mail...and into the attachment utility ( I think DownloadControl) there are the attachments of Inboud document

A: Something like this would add a parent documents subject to the current one
var content = <richTextControl>.getValue();
if(dominoDoc.isResponse())
{
    var doc = database.getDocumentByUNID(dominoDoc.getParentId());
    content += "\n\n";
    content += "=================== Previous: ==================";
    content += doc.getItemValueString("content");
}

so this would get the current content, add 2 lines space, add a line to show the end and then its parents content. Depending on your use case maybe put this in a scoped variable and on the click of a button add it to the current document.
EDIT:
If you want to deal with attachments to a field you can use code like the below I used in a repeat to iterate through a list of attachments and return links. for your use you may need to change this to use a for loop
var al:java.util.list = dominoDoc.getAttachment("Body");
var eo:NotesEmbeddedObject = "";
if(!al.isEmpty())
{
   eo = al.get(index);
   return eo.getHref();
}
else
{
   return "";
}

A: You get the content of the document as MIME (In case you have forgotten, speak after me: There is no RichText in the Internet, it is a ghost of Christmas past. There's only MIME) using the Mime methods of the Notes document. Then you check what you have: HTML or plain text. If it is plain text, then you just do a String concatenation similar to above but with the MIMEPart instead of the itemValueString.
When it is HTML (as your question suggests) read it with a parser (e.g. HTMLCleaner can read HTML nicely) and then insert your new stuff after you encountered the body tag. Then read the rest and write the MIME back. Would make a nice bean.


text:
Q: How to check whether array includes certain value google Apps Script I'm using range.getValues() to load an array in Google Apps Script.
I want to loop through the array and do something if the array includes the value I'm looking for.
if (array.include("abc")){*doSomething*}

The problem is when I use this method, the array contain another arrays, so array.include() doesn't work.
I can use a workaround like this:
for (var i = 0; i<=array.length; i++){
  if (array[i] == "abc"){*doSomething*}

I wonder are there a better way to do it?
I tried to use array.indexOf() but it returns -1 for 0th value, which is weird

A: function find() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  const haystack=sh.getDataRange().getValues();
  const needle="44";
  let found = false;
  haystack.forEach(r=>{
    r.forEach(c=>{
      if(c==needle) {
        found=true;
      }
    })
  });
  if(found) {
    SpreadsheetApp.getUi().alert('Needle was found in haystack');
  }
}

or
function find() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  const haystack=sh.getDataRange().getValues();
  const needle="44";
  let found = false;
  haystack.forEach(r=>{
    if(~r.indexOf(needle)) {
      found=true;
    }
  });
  if(found) {
    SpreadsheetApp.getUi().alert('Needle was found in haystack');
  }
}

A: Recommendation:
Alternatively, you can also try this way:
function arrayCheck(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var arr = ss.getDataRange().getValues(); //Get all values from sheet
  Logger.log(arr);
  arr.forEach(function(res) {
    if(res == 'abc'){
      Logger.log("Found a match");
      //do something
    }else{
      Logger.log(res+" does not match abc");
    }
  });
}

Here's a sample sheet where I've got all the array values from:

Here's the result:


text:
Q: How to solve : "Unsupported class version number[52.0] maximum 51.0, Java1.7"? Can't read

[C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework\MonoAndroid\v7.0\mono.android.jar]
  (Can't process class [android/app/ActivityTracker.class] (Unsupported
  class version number [52.0] (maximum 51.0, Java 1.7)))

how to solve this issue..??

A: Had this error too. Which JDK Version do you have installed? I had no problems after upgrading it to version 1.8
Alright, if somebody else is reading this with the same problem, upgrading ProGuard seems to fix this problem too. Just try that! :)


text:
Q: Selecting specific object with Json.NET (SelectToken) I'm new to Json.NET and try out using the SelectToken function.
My test JSON:
{
  "Root": {
    "aNode": {
      "bNode": {
        "cNode": {
          "id": "myID1"
        }
      },
      "cNode": {
        "id": "myID2"
      },
      "dNode": {
        "cNode": [
          {
            "id": "myID3"
          },
          {
            "id": "myID4"
          }
        ]
      }
    },
    "cNode": {
      "id": "myID5"
    }
  }
}

Now, I'm trying to use the following code for getting specific objects:
JObject obj = JsonConvert.DeserializeObject<JObject>(jsonTxt);

//Not found
var myID1 = obj.SelectToken("..cNode[?(@.id=='myID1')]");

//Not found
var myID2 = obj.SelectToken("..cNode[?(@.id=='myID2')]");

//Found
var myID3 = obj.SelectToken("..cNode[?(@.id=='myID3')]");

//Found
var myID4 = obj.SelectToken("..cNode[?(@.id=='myID4')]");

//Not found
var myID5 = obj.SelectToken("..cNode[?(@.id=='myID5')]");

Why do I get these (for me) strange results?
I think I should get in every case the cNode object with the specific ID, and not only myID3 and myID4. What's wrong here?

A: I am not sure what you really want to achieve but you can use Linq to get cNodes
var nodes = obj.Descendants()
                .OfType<JProperty>()
                .Where(p => p.Name == "id")
                .Select(p=>p.Parent)
                .ToList();


text:
Q: replace an invalid URI in the .xml file how can i replace an invalid URI in xml file, i cannot parse the xml file because it gives an invalid URI error while trying to parse the file. How can i read the contents of the .xml file into a string so that the invalid URI can be replaced.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Submit xmlns="http://localhost/....">
    <Order>
    <Components>
        <Component>
            <ocode> ABC</ocode>
        </Component>
    </Components>
</Order>
</Submit>
</soap:Body>
</soap:Envelope>

A: If you just want the content, use SimpleXML and XPath to fetch the body contents...
$xml=simplexml_load_file("NewFile.xml");
$content = $xml->xpath("//soap:Body/*");
echo $content[0]->Order->asXML();

will give...
<Order>
    <Components>
        <Component>
            <ocode> ABC</ocode>
        </Component>
    </Components>
</Order>

Not sure what the namespace http://localhost/.... is supposed to be, but it should be a valid URI - even if it is http://localhost.
Edit:
To try and fix the URI, you can read the file to a string first and then replace the invalid string with a valid one...
$data = file_get_contents("NewFile.xml");
$data = str_replace("http://localhost/....", "http://localhost", $data);
$xml=simplexml_load_string($data);

Or you could also try removing all of the attributes...
$data = preg_replace("/<Submit.*?>/", "<Submit>", $data);


text:
Q: Transform vertical table to horizontal with MySQL I have a TableA with information, like so:
TIME           DATA    VALUE
-------------  ------  ------
120520142546    Title   Mr
120520142546    Name    Smith
120520142546    Smoke   Yes
180303140429    Title   Ms
180303140429    Name    Lea
180303140429    Smoke   No

I'm trying to get a TableB (which is already created, just want to insert the value) where data with the same time value are displayed in the same row, like so (and also tranform the 'Yes' by 1 and 'No' by 0) :
ID      Title  Name    Smoke
---     -----  -----   -----
1       Mr     Smith    1
2       Ms     Lea      0

I kind of understand that it can be do with the PIVOT thing but i couldn't find an easy tutorial that I would understand.

A: Try this:
CREATE TABLE TableB (
    Id int NOT NULL AUTO_INCREMENT,
    Title varchar(255) NOT NULL,
    Name varchar(255) NOT NULL,
    Smoke tinyint(255) NOT NULL,
    PRIMARY KEY (Id)
);

INSERT INTO TableB (Title, Name, Smoke)
SELECT t1.value AS title, t2.value AS name, (t3.value = 'Yes') AS smoke
FROM TableA t1
JOIN TableA t2 ON t1.time = t2.time
JOIN TableA t3 ON t1.time = t3.time
WHERE t1.data = 'Title' AND t2.data = 'Name' AND t3.data = 'Smoke';

This assumes all three attributes will always be available for each timestamp, and no duplicate entries exist for any timestamp.


text:
Q: How to add Jquery code snippet in the HTML editor for footer_cms_content When I place this code :-
$(".social-icons").after('');
$.getScript("https://seal.godaddy.com/getSeal?sealID=beP8DWYRCbG8YIK0Chdr8BKQQsmmOG3jEF1rddbw106hSZicW0fWglZgVTRQ",function(){"";
});

at the end of the HTML for footer_cms_content, it just displays the the code itself instead of the Godaddy Trust Seal. Is it possible to place it in this cms block for footer?
Thanks.

A: I am only for you suggest. may be help you
Magento 2 jquery or javascript not add in cms block SO you create the simple the .phtml file and call the your footer cms block like :-
{{block class="Magento\Framework\View\Element\Template" template="Vendor_Module::myfiles/myfile.phtml"}}

A: I would create a static block with your code and then call the static block via /app/design/frontend/Vendor/theme/Magento_Theme/layout/default.xml
<block class="Magento\Cms\Block\Block" name="godaddy.seal" before="-">
    <arguments>
        <argument name="block_id" xsi:type="string">block_code_name</argument>
    </arguments>
</block>

<move element="godaddy.seal" destination="footer_cms_content" before="-"/>


text:
Q: Error inflating class com.google.android.material.tabs.TabLayout in espresso test I have a fragment with which has a TabLayout:
<com.google.android.material.tabs.TabLayout
    android:id="@+id/playerSectionsTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    app:tabIndicatorHeight="0dp"
    app:tabMode="scrollable"
    app:tabRippleColor="@null"
    app:tabTextAppearance="@style/TabLayoutTextAppearance" />

and I'm using:
implementation 'com.google.android.material:material:1.0.0'

and it works fine. But it doesn't work in espresso tests and I get this:
android.view.InflateException: Binary XML file line #15: Error inflating class com.google.android.material.tabs.TabLayout
...
Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).

BTW I use fragment-testing package to test my fragments.


text:
Q: Sort a specific XML File with XSLT by multiple attributes Here is the XML structure. I have to sort/order by category name first, then by preference name and then sort the value list itself. I am new to xslt. How to achieve multiple ordering?
<?xml version="1.0" encoding="ISO-8859-1"?>
<preferences version="10.0">
  <category name="Administration.Access Manager">
   <category_description></category_description>
    <preference name="ADA_admin_notifier_list" type="String" array="true" disabled="false" protectionScope="Site" envEnabled="false">
     <preference_description>Text</preference_description>
    </preference>
    <preference name="ADA_allow_gov_classification_propagation" type="Logical" array="false" disabled="false" protectionScope="Site" envEnabled="false">
     <preference_description>Text</preference_description>
     <context name="Teamcenter">
      <value>b</value>
      <value>c</value>
      <value>a</value>
     </context>
   </preference>
   <preference name="ADA_saveas_propagated_license_types" type="String" array="true" disabled="false" protectionScope="Site" envEnabled="false">
    <preference_description>TEXT</preference_description>
     <context name="Teamcenter">
      <value>IP_License</value>
      <value>ITAR_License</value>
      <value>Exclude_License</value>
    </context>
  </preference>
 </category>
</preferences>

How can I apply a xslt via Browser. How to reference the xslt in the XML?
Edit:
I now tried something like the following. First Problem there are missing some attributes in the Output like the descriptions. I think I don't understand the apply-template right.
Second Problem is that the values are not sorted. The category name and the Preference name is sorted
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:strip-space elements="*"/>

<xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

    <xsl:template match="preferences">
     <xsl:copy>
     <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="category">
            <xsl:sort select="@name"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

   <xsl:template match="category">
     <xsl:copy>
    <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="preference">
            <xsl:sort select="@name"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

 <xsl:template match="preference">
     <xsl:copy>
     <xsl:apply-templates select="@*"/>
     <xsl:apply-templates select="preference_desciption"/>
        <xsl:apply-templates select="context">
            <xsl:sort select="value" data-type="text"/>
        </xsl:apply-templates>
   </xsl:copy>
</xsl:template>

</xsl:stylesheet>

A: You haven't explained your requirements very clearly: for example there's no hint what output you want to produce (is it HTML?). If you want to sort the preferences within a category, you can do
<xsl:template match="category">
  <xsl:apply-templates select="preference">
    <xsl:sort select="@name"/>
  </xsl:apply-templates>
</xsl:template>

and similarly for the other things you want to sort.

A: Try it this way:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="/preferences">
     <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:apply-templates select="category">
            <xsl:sort select="@name"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

<xsl:template match="category">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:apply-templates select="preference">
            <xsl:sort select="@name"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

<xsl:template match="context">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:apply-templates select="value">
            <xsl:sort select="."/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


text:
Q: How to Bind datasource from a static method? ASP.net I want to bind a dataSource from a static method. but i cant see my repeater on my static method.
[WebMethod]
public static int setPages(string num)
{
   int result = MarketplaceDataBridge.SetPageNumber(num);
   repeater1.datasource(result);
   repeater1.databind();
   return result;
}

is it possible to do this?, or what are the ways that i could do to achieve this thanks.
-ive been searching this whole time from calling static to nonstatic and passing ajax values to wherever up to creating webservices haha- sorry for being such a newb-
--Update ive been able to call it this way
public partial class _Default : System.Web.UI.Page
{
    [WebMethod]
    public static int setPages(string num)
    {
       _Default page = new _Default();
       int result = MarketplaceDataBridge.SetPageNumber(num);
       page.binder(result);
       return result;
    }

private void binder(List<MobileApplication> map)
        {
            List<MobileApplication> maps = new List<MobileApplication>();

            maps = map;
            if (maps != null)
            {
                Apps.DataSource = maps;
                Apps.DataBind();
            }

        }
}

but im getting errors unhandledNullException but whenever i pass maps it has values in it

A: Try to make your binder method static also


text:
Q: (ES v7.5.1) Speed up snapshot restore from GCS Snapshot Repository We are trying to speed up our snapshot restoration speed in our ES cluster hosted on GCP Compute instances.
TL;DR:

*

*Current Performance: 56 MBps per data node

*Infra Capable of 500 MBps

*We want to improve our restore speed up to the maximum disk throughput (no throttling from infrastructure).

Infra Details:

*

*3 Master | 10 Data Nodes

*Each node has 8core/16gb config (heap size: 8gb)

*Each Data instance supports max 15k disk IOPS (500 MBps Throughput)

Current Restore Performance: 4.5 Gbps on the whole cluster (56 MBps per node).
We are currently getting 10% of the total disk write throughput. We are looking for options to improve it.
Note: Have already tested any infra-related throttling. Using gsutil -m, we saw the download speed reach to 450 MBps on one of the data nodes.
What we have already tried:

*

*Setting max_restore_bytes_per_sec to 0 in our gcs snapshot repository.

*Setting indices.recovery.max_bytes_per_sec to 0.

We are unable to figure out the config that is throttling the network performance.

Update:
We tried to increase the number of data nodes, to check if the throttling is on some data nodes:
Changed Data nodes count from 10 to 20.
Result: Speed still throttled at 4.5 Gbps (speed on individual data nodes decreased to half).

A: After trying multiple options, we weren't able to find the root cause of this.
We decided to use an updated version of ES (version: 7.10.2).
We are now able to reach 33gbps speed with the updated cluster.
Interestingly, we are using similar configs (similar ansible playbooks) for both the version, but with version 7.10.2, we were able to reach the target speed.


text:
Q: Disable MFMT in lftp How to disable MFMT in lftp?
I use lftp mirror command to sync my files with the remote server.
Looks like lftp send MFMT command after uploading file.
This is undesirable in my case and I would like to turn it off.

A: Try this:
set ftp:use-feat off

Lftp won't use FEAT to find out existing server features and thus won't use the MFMT command.


text:
Q: Eclipse Plugin Development install dependencies if not installed yet Hey guys,
I'm developing a plugin for eclipse and I need some dependencies, e.g. org.eclipse.graphiti.
When I export my plugin and when I build my update site, everthing works fine, until i try to install my plugin, because then the install wizard says I don't have graphiti installed. How can I tell my wizard to ask if you want to install the needed plugin automatically?
Thanks for any help and ideas.

A: During install select the 'Contact all available update sites' checkbox in the lower part of the feature selection dialog. This allows searching all existing update sites. This might help, or if not, then add the Graphiti update site your feature.xml.


text:
Q: Vimeo API request with AngularJs "401 Authorization required" I've been trying to call an external API (Vimeo) from my AngularJS code, using $http.jsonp. But all i get is a 401 Authorization required even though i added my authorization Key to the header.  had a similar problem doing the same thing with jQuery.ajax(). But with jQuery i solved the problem by setting the beforeSend function to set my authorization key on the request Header using the xhr object.
My code:

function(){
  var config = {
              headers: {Authorization: "bearer 34210aeac4e02a251b8821a53620e93c"},
              params : {
                  callback: 'JSON_CALLBACK'
                  }
              };
  var url = "https://api.vimeo.com/tags/fun/videos?per_page=5";
  $http.jsonp(url, config).success(function(response){
      console.log(response);
  });
};

How do i get this to work. Is the some kind of config.beforeSend that i can use to set the header just like jQuery

A: In angular you could use http interceptor

*

*Define your http interceptor: this one will add a token on every http request
ng.module('interceptors')
 .factory('authorizationInterceptor', function () {
    return {
        request: function (config) {
           config.headers = config.headers || {};
           config.headers.Authorization = 'Bearer ' +  '34210aeac4e02a251b8821a53620e93c';
           return config;
       }
};});

*register your interceptor
angular.module('myApp',[]).config(['$httpProvider',function ($httpProvider) {
    $httpProvider.interceptors.push('authorizationInterceptor');
    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);

Note, I think the first letter of bearer must be capital letter in you header

A: I don't know Angular too well, but I think the issue is that you're using JSONP.  Since that uses the browser's script tag to get around CORS restrictions, it does not allow for verbs other than GET nor setting headers.
The Vimeo API supports CORS headers, so you actually want to make a regular GET request using the browser's AJAX functionality.  I believe that AngularJS provides for this with the $http.get function to do what you're currently doing (docs).
I would try out:
function(){
    var config = {
        headers: {Authorization: "Bearer 34210aeac4e02a251b8821a53620e93c"}
    };
    var url = "https://api.vimeo.com/tags/fun/videos?per_page=5";
    $http.get(url, config).success(function(response){
        console.log(response);
    });
};


text:
Q: INSERT NULL Values not working instead i get 0.000 I'm trying to input a form into a database that uses numerical values (mainly decimals)
This form updates and inserts fine, but i want NULL fields to insert NULL into the database.
If I leave a field blank it still puts 0.000 into the database. I have the database set to NULL = YES
Is there a short piece of code i can use to do this for all 14 text boxes?
This is my code:
<?php
if (isset($_POST['submit'])) {

$date2 = date("y-m-d"); // DATE OF TANK ADDITION
$time2 = date("H:i:s", time() - 3600);   // TIME OF TANK ADDITION

$test1 = $_POST['test1'];
$test2 = $_POST['test2'];
$test3 = $_POST['test3'];
$test4 = $_POST['test4'];
$test5 = $_POST['test5'];
$test6 = $_POST['test6'];
$test7 = $_POST['test7'];
$test8 = $_POST['test8'];
$test9 = $_POST['test9'];
$test10 = $_POST['test10'];
$test11 = $_POST['test11'];
$test12 = $_POST['test12'];
$test13 = $_POST['test13'];
$test14 = $_POST['test14'];
$time = $_POST['time'];
$date = $_POST['date'];
$month = $_POST['month'];
$day = $_POST['day'];
$active1 = $_POST['active1'];
$active2 = $_POST['active2'];
$active3 = $_POST['active3'];
$active4 = $_POST['active4'];
$active5 = $_POST['active5'];
$active6 = $_POST['active6'];
$active7 = $_POST['active7'];
$active8 = $_POST['active8'];
$active9 = $_POST['active9'];
$active10 = $_POST['active10'];
$active11 = $_POST['active11'];
$active12 = $_POST['active12'];
$active13 = $_POST['active13'];
$active14 = $_POST['active14'];
$tank = $_POST['tank'];

$insert = "INSERT INTO tests SET
member_id='$_SESSION[SESS_MEMBER_ID]',
test1='$test1',
test2='$test2',
test3='$test3',
test4='$test4',
test5='$test5',
test6='$test6',
test7='$test7',
test8='$test8',
test9='$test9',
test10='$test10',
test11='$test11',
test12='$test12',
test13='$test13',
test14='$test14',
date='$date',
month='$month',
day='$day',
time='$time',
active1='$active1',
active2='$active2',
active3='$active3',
active4='$active4',
active5='$active5',
active6='$active6',
active7='$active7',
active8='$active8',
active9='$active9',
active10='$active10',
active11='$active11',
active12='$active12',
active13='$active13',
active14='$active14',
tank_id='$tank'";

A: When a field is empty or someone clears it on edit (I assume that is possible too), the value is an empty string.
So to make sure you insert NULL where there are empty strings, you can do (for all variables that can be NULL):
$test1 = ($_POST['test1'] === '') ? NULL : $_POST['test1'];

That will really set the value to NULL instead of an empty string that will be cast to 0 when you insert it.
And you should use prepared statements for your sql inserts.
Edit: Also note that when you try to insert your NULL value, you should be inserting just NULL and not 'NULL'. That problem would also be solved by switching to a prepared statement with bound variables.
Edit 2: A temporary solution that would work here, is to remove the quotes from the sql statement and add them in the assignment:
$test1 = ($_POST['test1'] === '') ? NULL : ("'" . (float) $_POST['test1'] . "'");
...

and:
$insert = "INSERT INTO tests SET
member_id='$_SESSION[SESS_MEMBER_ID]',
test1=$test,
test2=$test2,
test3=$test3,
...

I have used (float) to at least get rid of the sql injection problem here (mysql_real_escape_string() might be better, don't know, don't use that any more...), but this is more of a hack than a real solution. Please switch to prepared statements with bound variables.

A: You have to leave the items you want NULL out of the query entirely.
Try something like:
foreach ($_POST as $k => $v)
{
    $query .= "{$k}='{$v}',";
}

You will have to make your commas work, etc.
WARNING:
Don't use this code in production, please. You should always sanitize user inputs, use parameterized SQL, and don't accept POST keys you are not expecting.

A: Do you have a DEFAULT NULL in your table's structure for the specific field?
The table needs to know what to do with default values
CREATE TABLE IF NOT EXISTS MyTable (
  MyField datatype DEFAULT NULL,
);

If you want to update a table rather that re-create it, do this:
ALTER TABLE MyTable
ALTER COLUMN MyField datatype DEFAULT NULL


text:
Q: Always get response 404 I have handled the process to get a valid access token;
nevertheless, now I am stuck to get data from the server;
I have checked the forum and other web pages, but I could not figure out what I am doing wrong;
I am running the following Google Application Script:
var jawbone_access_token = "my private access token - long string";
var options = {
                 'Accept'        : 'application/json',
                 'Authorization' : 'Bearer ' + jawbone_access_token
                }

var jawbone_request = "https://jawbone.com/nudge/api/v.1.1/users/@me";
response = UrlFetchApp.fetch(jawbone_request, options).getContentText();
writeLog(response);

nevertheless, I always get the following response:

ERROR - Stau:Exception: Fehler bei der Anfrage für
  https://jawbone.com/nudge/api/v.1.1/users/@me. Folgender Code wurde
  zurückgegeben: 404. Gekürzte Serverantwort: {"meta": {"error_detail":
  "Unsupported API version 1.1, unless called with an OAuth header",
  "code": 404, "error_type": "endpoint_error", "time": 1.... Verwenden
  Sie "muteHttpExceptions", um die vollständige Antwort zu lesen.

can you please help me to figure out what I am doing wrong;
Thank you very much in adavance for your help;
Best Regards
Rudolf

A: That is the response you get when you haven't provided the Access Token in the header.
I took a quick look at the UrlFetchApp documentation, and you need to put your headers in a headers object:
var options = {
    'headers': {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + jawbone_access_token
    }
}


text:
Q: executing commands in containers from within a container using docker-compose up vs docker-compose run I'll try to explain this as simply as possible.
I have a dockerised python app. Within this python app at some point I try to run a docker command in another (libreoffice) container as such:
import subprocess
file_path = 'path_to_file'
args = ['docker', 'run', '-it', '-v', '/tmp:/tmp',
'lcrea/libreoffice-headless', '--headless', '--convert-to', 'pdf', file_path,
'--outdir', '/tmp']

process = subprocess.run(args,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        timeout=timeout)

I end my python app's Dockerfile with a command which starts the server:
CMD python3 -m app.run_app
What is interesting is when I start the python app like this it works fine:
docker-compose run -p 9090:9090 backend /bin/bash
root@74430c3f1f0c:/src python3 -m app.run_app

But when I start it just using docker-compose up, the libreoffice container is never called. I am sure of it because when I do docker ps -a in the first instance a libreoffice container has been created while in the second there is none.
What is going on here?

A: I found the error. I was passing in the -it option which was failing the process because of the input device is not a TTY. All I had to do was take it out...


text:
Q: Notice:Undefined index error I'm getting this error:
Notice: Undefined index: prospectname in C:\wamp\www\var\SAS\insert.php on line 12

Here is the code
<form action="#" method="POST" class='form-horizontal form-bordered'>

        Prospect Name

            <input type="text" name="prospectname" id="prospectname" placeholder="prospectname" class="input-xlarge">

        Status

</form>

sas.js
$(".registeradd").click(function () {

    var prospectname = $("#prospectname").val();
    var status = $("#status").val();
    var dataString = 'prospectname =' + prospectname + '&status=' + status;

    if (prospectname == '') {
        alert("Please Enter Some Text");
    } else {
        $("#flash").show();
        $("#flash").fadeIn(400).html;

        $.ajax({
            type: "POST",
            url: "insert.php",
            data: dataString,
            cache: false,
            success: function (html) {
                $("#display").after(html);
                $("#flash").hide();
            }
        });
    }
    return false;
});

Insert.php
<?php

$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'test';

$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");

mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");

$prospectname =$_POST['prospectname'];
$status=$_POST['status'];

$sql_insert="insert into salesactivity(prospectname,status) values '$prospectname','$status')";

print $sql_insert;
mysql_query($sql_insert);

?>

A: Change your datastring
var dataString = 'prospectname ='+ prospectname +'&status='+status;

to a json object
var dataString = { 'prospectname': prospectname, 'status': status};

A: i think you forget status text field in your form  add it on html form
replace your form with this

  <form action="#" method="POST" class='form-horizontal form-bordered'>

                Prospect Name

                    <input type="text" name="prospectname" id="prospectname" placeholder="prospectname" class="input-xlarge">

                Status

                    <input type="text" name="status" id="status" placeholder="status" class="input-xlarge">

        </form>


text:
Q: GraphQL Schema Delegation through Declarative Programming I was looking at the documentation of graphql-tools, and wanted to know if we can use declarative programming model to delegate queries or mutations to sub-schemas?
https://www.graphql-tools.com/docs/schema-delegation
Specially the delegateToSchema type of call, can this done through SDL using directives?

A: Yes, it's possible. You can use the @delegate directive to delegate your query to the appropriate schema.
The sample below assumes you are querying for a customer. In your SDL, you might add:
type CustomerQuery
{
    customer(customerId: ID!) : Customer @delegate(schema: "CustomerServiceSchema": path: "customer(customerId: $arguments:customerId)")
}


text:
Q: Testing for Collinearity in a Dataset with Categorical and Continuous Variables I have a dataset that has 17 variables. 9 categorical and 8 continuous. Some have more than 2 levels. I've reduced the dimensionality significantly. I am looking for strategies to test for colinearity within the dataset before I construct the logistic model and test for collinearity there.
I can just split the model into subsets of the categorical and continuous data then test fo collinearity there. Then do so again for the logistic model with an Anova test. But I am not sure what the best options might be.


text:
Q: Do windows console color values have official names (constants) associated with them? Normally colors are called through their hexadecimal associations, but in the code is it possible to call these colors trough some constants build in windows console API ?
Here are colors names I found while searching SO: https://stackoverflow.com/a/7138277/393087
colors codes:
7 => default
0 => black
1 => blue
2 => green
3 => aqua
4 => red
5 => purple
6 => yellow
7 => light gray
8 => gray
9 => light blue
A => light green
B => light aqua
C => light red
D => light purple
E => light yellow
F => white

Are these names official ? So for example I could do:
SetConsoleTextAttribute(hConsole,LIGHT_BLUE * 16 + LIGHT_AQUA);

A: Console Screen Buffers - Character Attributes
FOREGROUND_BLUE         Text color contains blue.
FOREGROUND_GREEN        Text color contains green.
FOREGROUND_RED          Text color contains red.
FOREGROUND_INTENSITY    Text color is intensified.
BACKGROUND_BLUE         Background color contains blue.
BACKGROUND_GREEN        Background color contains green.
BACKGROUND_RED          Background color contains red.
BACKGROUND_INTENSITY    Background color is intensified.

A: Here is complete list of Background and Foreground colors in WinAPI.
/*Enum to store Foreground colors*/
    typedef enum FG_COLORS
    {
        FG_BLACK = 0,
        FG_BLUE = 1,
        FG_GREEN = 2,
        FG_CYAN = 3,
        FG_RED = 4,
        FG_MAGENTA = 5,
        FG_BROWN = 6,
        FG_LIGHTGRAY = 7,
        FG_GRAY = 8,
        FG_LIGHTBLUE = 9,
        FG_LIGHTGREEN = 10,
        FG_LIGHTCYAN = 11,
        FG_LIGHTRED = 12,
        FG_LIGHTMAGENTA = 13,
        FG_YELLOW = 14,
        FG_WHITE = 15
    }FG_COLORS;

    /*Enum to store Background colors*/
    typedef enum BG_COLORS
    {
        BG_NAVYBLUE = 16,
        BG_GREEN = 32,
        BG_TEAL = 48,
        BG_MAROON = 64,
        BG_PURPLE = 80,
        BG_OLIVE = 96,
        BG_SILVER = 112,
        BG_GRAY = 128,
        BG_BLUE = 144,
        BG_LIME = 160,
        BG_CYAN = 176,
        BG_RED = 192,
        BG_MAGENTA = 208,
        BG_YELLOW = 224,
        BG_WHITE = 240
    }BG_COLORS;


text:
Q: Pig Latin: using field in one table as position value to access data in another table Let's say we have two tables. The first table has following description:
animal_count: {zoo_name:chararray, counts:()}
The meaning of "zoo_name" fields is obvious. "counts" fields contains counts of each specific animal species. In order to know what exact species a given field in "counts" tuple represents, we use another table:
species_position : {species:chararray, position:int}
Let assume we have following data in "species_position" table:
"tiger", 0
"elephant", 1
"lion", 2
This data means the first field in animal_count.counts is the number of tigers in a given zoo. The second field in that tuple is the number of elephants, and so on. So, if we want to represent that fact that "san diego zoo" has 2 tigers, 4 elephants and no lion, we will have following data in "animal_count" table:
"san diego zoo", (2, 4, 0)
Given this setup, how can I write a query to extract the number of a given species in all zoos? I was hoping for something like:
FOREACH species_position GENERATE species, animal_count.counts.$position;
Of course, the "animal_count.counts.$position" won't work.
Is this possible without resorting to UDF?


text:
Q: dijit issue: none of the components getting rendered I am using SPring JS 2.3.0.RELEASE (which uses dojo 1.6): I tried adding widgets to my page but it never renders
I am using pages through tiles so here's the layout template shopper.jspx

<jsp:output doctype-root-element="HTML" doctype-system="about:legacy-compat" />
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:directive.page pageEncoding="UTF-8" />
<jsp:output omit-xml-declaration="true" />

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<link rel="stylesheet" type="text/css" href="/resources/dojo/resources/dojo.css"/>
<link rel="stylesheet" type="text/css" href="/resources/dijit/themes/nihilo/nihilo.css" />
<link rel="stylesheet" type="text/css" href="/resources/css/screen.css" />
<c:url var="rootUrl" value="/resources/"/>

<title>My Shopping</title>

  <tiles:insertAttribute name="header" />
  <tiles:insertAttribute name="submenu" />
  <tiles:insertAttribute name="body" />
  <tiles:insertAttribute name="footer" ignore="true" />

and here's the home.jspx template which overrides body attribute
<?xml version="1.0" encoding="UTF-8" ?>

  <jsp:directive.page contentType="text/html;charset=UTF-8" />
  <jsp:output omit-xml-declaration="yes" />
  <c:url var="rootUrl" value="/resources/"/>

I do not see any of these widgets getting rendered when I load the page. Also the browser console shows the error:
dojo.byId("inbox").addChild is not a function
[Break On This Error]

dojo.byId("inbox").addChild(bc.domNode);

despite having the  djconfig="parseOnLoad: true" configuration in place.
Update: hereś the initial declarative syntax I tried but could not get it to work.
shopper.jspx:

<jsp:output doctype-root-element="HTML"
    doctype-system="about:legacy-compat" />
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:directive.page pageEncoding="UTF-8" />
<jsp:output omit-xml-declaration="true" />

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<link rel="stylesheet"
    href="http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dijit/themes/nihilo/nihilo.css"
    media="screen"/>
<link rel="stylesheet" type="text/css" href="/resources/css/screen.css" />

<title>My Shopping</title>

    <tiles:insertAttribute name="header" />
    <tiles:insertAttribute name="submenu" />
    <tiles:insertAttribute name="body" />
    <tiles:insertAttribute name="footer" ignore="true" />

the declarative home.jspx I copied from dojo tutorial:
<?xml version="1.0" encoding="UTF-8" ?>

  <jsp:directive.page contentType="text/html;charset=UTF-8" />
  <jsp:output omit-xml-declaration="yes" />

Top pane

accordion pane #1

accordion pane #2

accordion pane #3

tab pane #1

tab pane #2

tab pane #3

Trailing pane

Bottom pane

in screen.css I have defined the following:
body {
  margin: 0;
  padding: 0;
  background-color: #EAECEE;
  font-family: Verdana, sans-serif;
  font-size: 12px;
}

#page {
  background: #ffffff;
  margin-left: auto;
  margin-right: auto;
  -moz-box-shadow: 0 0 5px 3px #999;
  -webkit-box-shadow: 0 0 5px 3px #999;
}

And I get no widgets rendered in when I access the page.
Fixed: Was ignoring the fact about how dijit places divs, I removed the styles applyed through "page" div id and fixed the height and width as follows:

  <jsp:directive.page contentType="text/html;charset=UTF-8" />
  <jsp:output omit-xml-declaration="yes" />

A: You are declaring a border container in markup and also trying to create one programmatically.
Try this:
Change

to

create the border container
var bc = new dijit.layout.BorderContainer({}, dojo.byId("inboxContainer"));
...
// dojo.byId("inbox").addChild(bc.domNode); // remove this

This line of code fails because dojo.byId returns a domNode and a domNode does not have an addChild method.
I also changed the width and height.  Using height: 100% requires all the dom nodes above it in the hierarchy (html, body, roundedCorners, inbox) to also have height: 100% and I couldn't verify in the code posted that this was the case, so eliminate this potential problem for now by specifying a direct height. Once, its working, you can change it back.


text:
Q: Is there a "Switch User" functionality in Windows that doesn't require switching users? For Example:
I'm working on 2 massive projects on a PC with limited screen real-estate and resources and would like to easily be able to switch between the 2 projects, without having to close and re-open programs and hide show certain windows (as needed to free resources or show proper open programs).
Explaining Further:
Does Windows have anything like the "Switch User" (Windows -> Shutdown -> Switch User) option, but without requiring a secondary account or sign in.
We'd keep the functionality of hiding, closing and opening windows and resources based on user signed in?

A: Based on your operating system, Desktops by Microsoft may well prove useful.  This tool can be downloaded from:
https://docs.microsoft.com/sysinternals/downloads/desktops
On Windows 10, see: https://support.microsoft.com/help/4028538/windows-10-multiple-desktops for similar functionality.


text:
Q: Matching a row across two columns in R I am trying to figure out how to add a new column that tells me whether or not 2 columns are matched. Dummy data set below:
col_A  col_B
food   food
drink  food
food   drink
drink  drink

What I want is something like this:
col_A  col_B  match_col
food   food   match
drink  food   no match
food   drink  no match
drink  drink  match

I am not sure if I need to a join or ifelse or combination of the two?

A: You can use ==.
For two columns:
df |>
  transform(match_col = ifelse(col_A == col_B, "match", "no match"))

For multiple columns:
library(dplyr)
df %>%
  mutate(match_col = if_all(col_B:col_D, `==`, col_A))

A: Try to run this and see how it works. Not the most sophisticated code, but it is simple to understand.
col_A<-c("food","drink")
col_B<-c("food","food")
df<-data.frame(col_A,col_B)
res<-match(df$col_A,df$col_B)
res<-gsub(1,"match",res)
res[is.na(res)]<-"no match"
res
df<-data.frame(df,res)
df

A: If your data frame is called mydf and you could live with TRUE and FALSE instead of "match" and "no match" there is this function called == as in
mydf$col_A == mydf$col_B

or
mydf$match_col <- mydf$col_A == mydf$col_B


text:
Q: ModeMongoose's Async/Await with Mongoose Deep Populate Chain I'm having a lot of trouble getting the chained mongoose commands run in sequential order when using async/await. A simple await Model.find({}) command works as one might expect in an asynchronous function, but when I chain find commands with lean, populate, and exec for the purposes of deep population (http://mongoosejs.com/docs/populate.html#deep-populate) I am not able to run them in order as I'd like.
const messageSchema = new Schema({
  ...
})
const Message = mongoose.model("message", messageSchema)

const chatSchema = new Schema({
  conversations: [{
      messages: [{ type: Schema.Types.ObjectId, ref: "message" }]
  }]
})
const Chat = mongoose.model("chat", phoneSchema)

console.log("11111111111")

const chat = await Chat.findOne({ ... })
  .lean()
  .populate({ path: "conversations" })
  .exec(async (err, docs) => {
    const options = {
      path: "conversations.messages",
      model: "message",
    }

    const result = await Chat.populate(docs, options,
      (e, foundChat) => foundChat)

    console.log("22222222222")

    return result
  })

console.log("333333333333")

Result:
11111111
33333333
22222222

Desired Result:
111111111
222222222
333333333

A: Not sure why, tried a lot of different things, but this works.
const chat = await Chat.findOne({ ... })
  .populate({
    path: "conversations.messages",
    model: "message",
  })
  .exec((error, foundChat) => foundChat)

A: I feel like your code has 2 issues:

*

*You cannot call populate() after you used the lean() option. Lean() turns the returned objects into regular javascript objects and not mongoose documents. Populate is a built-in method in mongoose, so you can only use it in mongoose documents. This has nothing to do with your question but it's important to know.

*When you call exec() on a query and pass a callback as parameter, it does not return a promise and therefore the 'await' clause has no effect over it. That's why your function is not waiting for Chat.findOne() to resolve and goes straight to the last console.log. The following would probably work:
const chat = await Chat.findOne({ ... })
 .populate({ path: "conversations" })
 .exec().then(async (docs) => {
   const options = {
     path: "conversations.messages",
     model: "message",
   }

   const result = await Chat.populate(docs, options)

   console.log("22222222222")

   return result
})


text:
Q: How do I kill a certain mob outside of a radius I have been working on this project and I need to kill an entity that has left a radius. I used this command but it didn't work.
/kill @e[type=ArmorStand,!r=100]

What do I do?

A: The target selector for targets outside a certain radius is rm=<range>.  The m, like other selector arguments, stands for minimum.
Thus, your command would be /kill @e[type=ArmorStand,rm=100].


text:
Q: Working Principle of Chimneys: Thermodynamics Why should a chimney be freestanding – that is, not part of the structural support of the house?
I suppose it has something to do with thermal equilibrium, and the fact that two bodies in thermal contact attain the same. I'm not sure how that can make the chimney 'non functional'
Could someone please explain?
Edit:
Source of the fact that chimneys are freestanding and not part of structural support of the house

A: This might not be the reason; but one immediately comes to mind.
Thermal expansion could be a huge issue if the chimney was structurally part of the house.  As the chimney heats up, it would cause local expansion far greater than expansion outside of the chimney.  If the chimney were firmly fastened to the house, on a cold day, the expansion may be enough to break the structural connection between the house and chimney.
To account for the expansion, and still have the chimney act as a structural member, is probably far more expensive than just designing the joint between the building and chimney to account for expansion. This way they don't have to maintain structural integrity between the two.


text:
Q: Wrong array needle used I will try to describe my very strange problem with an multidimensional array.
This is my form (part of it)
<?php
    echo'

                    <select class="form-control no-border input-sm" id="calc_norm_id['.$y.'][]" name="calc_norm_id['.$y.'][]" multiple="multiple" size="12" style="overflow-y: auto;">';

                        $norm_id_arr = explode(',', $row_table_2['norm_id']);

                        foreach ($rows_nrm as $row_nrm)
                        {
                            echo '<option ';if(in_array($row_nrm['id'], $norm_id_arr)) { echo 'selected="selected"';} echo 'value="'.$row_nrm['id'].'">'.$row_nrm['norm'].' '.$row_nrm['omschrijving'].'</option>';
                        }
                        echo '
                    </select>

                <input type="number" step="0.01" class="form-control no-border input-sm" id="calc_prijs['.$y.'][]" name="calc_prijs[]" value="'.$row_table_2['prijs'].'" style="text-align: right" onkeyup="validate(this, '.$y.')">

';
?>

The form is send without any issues and print_r($_POST) gives as expected:
$_POST Array ( [calc_norm_id] => Array ( [1] => Array ( [0] => 8 [1] => 3 [2] => 2 ) [2] => Array ( [0] => 1 [1] => 4 [2] => 5 ) ) [calc_prijs] => Array ( [0] => 454.00 [1] => 740.00 [2] => [3] => [4] => [5] => [6] => ) )

Other checks are print_r($_POST['calc_norm_id'] and print_r($_POST['calc_prijs']:
$_POST[calc_norm_id] Array ( [1] => Array ( [0] => 8 [1] => 3 [2] => 2 ) [2] => Array ( [0] => 1 [1] => 4 [2] => 5 ) )
$_POST[calc_prijs] Array ( [0] => 454.00 [1] => 740.00 [2] => [3] => [4] => [5] => [6] => )

Still going as expected.
Next step is looping through the Array to send to the database:
foreach($_POST['calc_prijs'] as $key=>$value)
{
$calc_prijs = trim(mysqli_real_escape_string($mysqli, $_POST['calc_prijs'][$key]));
if(is_array($_POST['calc_norm_id'][$key])) { $calc_norm_id = trim(mysqli_real_escape_string($mysqli, implode(',', $_POST['calc_norm_id'][$key]))); }
}

But when I check $calc_norm_id & $calc_prijs now I see that the content is not matching.
I am expecting:
$calc_norm_id = 8,3,2
$calc_prijs = 454.00

$calc_norm_id = 1,4,5
$calc_prijs = 740.00

But I am getting:
$calc_norm_id =
$calc_prijs = 454.00

$calc_norm_id = 8,3,2
$calc_prijs = 740.00

Any ideas of what happend here and how to solve this?

A: You need to align the subscripts in the array
$_POST[calc_norm_id] Array ( **[1]** => Array

TO
$_POST[calc_norm_id] Array ( **[0]** => Array

TO
$_POST[calc_norm_id] Array ( [0] => Array ( [0] => 8 [1] => 3 [2] => 2 ) [1] => Array ( [0] => 1 [1] => 4 [2] => 5 ) )
$_POST[calc_prijs] Array ( [0] => 454.00 [1] => 740.00 [2] => [3] => [4] => [5] => [6] => )


text:
Q: Can't access javascript object members while using mongoose I'm using mongoose library to retrieve data from MongoDB database and I'm having an unusual problem. I am working with these schemas:
var imgSchema = new mongoose.Schema({
  data: Buffer,
  contentType: String
});

var carsSchema = new mongoose.Schema({
  _owner : { type: mongoose.Schema.ObjectId, ref: 'User' },
  year: Number,
  brand: String,
  model: String,
  name: String,
  carImage: [imgSchema],
  kmTraveled: Number,
  fillups: [fillupsSchema],
  reminders: [remindersSchema]
})

And this is the code where the problem occurs:
app.get('/api/cars/:carId/image', function(req, res) {
console.log('Returning image...');
Car.findById(req.params.carId)
    .populate('carImage')
    .exec(function(err,car) {
      if(!err) {
        console.log('carImage: ' + car.carImage);
          console.log('contentType: ' + car.carImage.contentType);
          console.log('Data: ' + car.carImage.data);
       }
...

The output is the following:
carImage: { _id: 555a1ae275c52a072dffaa1a,
data:
{ _bsontype: 'Binary',
 sub_type: 0,
 position: 69702,
 buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 02 00 00 01 00 01 00 00 ff ed 00 9c 50 68 6f 74 6f 73 68 6f 70 20 33 2e 30 00 38 42 49 4d 04 04 00 00 00 00 00 80 1c ...> },
contentType: 'image/jpg' }
contentType: undefined
Data: undefined

As you can see, contentType and data members are there inside the object, but when I try to access them it's like they are not there. What could be the problem here?
I should maybe add that images are actually stored in a separate collection, just like users, but I didn't include the ref in the cars schema. Could this be the issue here?
Edit: yes, this was the issue, it works now. Question dismissed.


text:
Q: Tkinter Text and Itemconfigure Memory Leak Background:
A few months ago, I posted here asking about a memory leak occurring in my Tkinter canvas class. The primary cause of this was an accidental loop over several key bindings, and the removal of these bindings largely alleviated my problem. However, there remained a small memory leak, but I disregarded it as negligible enough to ignore. At this point (after a couple more months of work), the previously small leak has grown to be potentially damaging -- after an hour of continuous use my program can now fill 800mb+ of system memory, which is a serious concern as without the leak, the program should only require ~60mb.
The Issue:
After some testing, I have narrowed the origin down to two causes:
1. Tkinter itemconfigure function
2. Tkinter text objects
The code snippet below recreates the issue on my machine.
from Tkinter import *

stop=0

class Interface:
    def Initialise(self,master):
        global x
        self.master=master
        x=50
        width,height=master.winfo_screenwidth(),master.winfo_screenheight()
        self.c=Canvas(self.master, width=width, height=height, bg='white',scrollregion=(-1500,-1500,10000,10000))
        self.c.pack(side=LEFT,expand=True,fill=BOTH)
        self.Regenerate()
        self.master.bind("<a>", self.auto)

    def Regenerate(self):
        self.G=UI_Canvas()
        self.G.Visualise(self.c,x)

    def auto(self, event):
        global stop
        stop+=1
        self.master.after(5, self.auto_rotate)

    def auto_rotate(self):
        global x
        if stop % 2 == 1:
            x+=0.1
            self.Regenerate()
            self.c.after(5, self.auto_rotate)

class UI_Canvas:
    def Visualise(self, canvas,x):

        self.canvas=canvas
        self.canvas.delete('Network')

        data=[((x,400,0),1),((x,450,0),2),((x+50,450,0),3),((x+50,400,0),4)]
        for (x,y,z), j in data:
            self.canvas.create_oval(x-5, y-5, x+5, y+5, fill='gray15', tags=(j,("Node %.5s" % j),'Network'))
            #self.canvas.create_text(x-10,y, text=(j), fill='black', font=('Helvetica',12), tags=(j, ("Node %.5s" % j), 'Network'))

root=Tk()
UI=Interface()
UI.Initialise(root)
root.mainloop()

By commenting out all text and itemconfigure objects, the leak disappears and the program runs at a constant memory usage (as required). Specifically, commenting out all text objects (leaving no objects to be configured), removes the leak, and it therefore seems to me that the repeated refresh of text on-screen is causing the leak. Other canvas objects (lines, ovals and polygons) that I use do not cause this issue.
Attempted Solutions
Other memory leak problems posted here seem to revolve around having updates within loops, but I have not relied on this method, and instead delete then re-create objects inside a loop. As previously mentioned, this method works fine with shapes, but apparently not with text. I have moved the text object code into my 'master' canvas class (thereby no longer being directly in a refresh loop), and instead attempted to configure it from the loop, but the issue persists.
Question
The information contained in these text objects is very important to easily using my program, and resolving this issue is essential. My questions are: what is causing this issue? And are there any possible solutions?
Thank you in advance for any assistance!


text:
Q: Read all files in a directory and compare the result with a datagrid i need to read a list of files in a given directory (c:/file/test).
I only need to read the second line (always this line).
The file is a .NT940 so i need to open it in notepad (or something else).
I need to open every file in the directory, read the second line and stor it in a list.
 public List<FileInfo> Getextraitfile(string fileName)
        {
            List<FileInfo> listData = new List<FileInfo>();
            try
            {
                using (var reader = new StreamReader(fileName))
                {
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();

                        FileInfo fileInfo = new FileInfo();
                        fileInfo.DataLine = line;

                        listData.Add(fileInfo);
                    }
                }

                return listData;
            }
            catch (Exception ex)
            {
                Logger.logErreur("GetCsvFile : " + ex.Message + ex.StackTrace);
                return new List<FileInfo>();
            }
        }

I have this to get the nt90 file but i'm totaly lost, can you please help me ?

A: Welcome to SO. In future questions try to specify a little better what you need including examples and more details. I think that something like this will help you:
    public List<string> GetLinesOfFile(string folderName)
    {
        FileInfo[] files = new DirectoryInfo(folderName).GetFiles("*.nt940");

        List<string> listYouNeed = new List<string>();

        foreach (FileInfo f in files)
        {
            string[] allLines = File.ReadAllLines(f.FullName);

            listYouNeed.Add(allLines[1]); //HERE YOU READ THE SECOND LINE OF THE FILE
        }

        return listYouNeed;
    }


text:
Q: Powershell 2: Easy way to direct every bit of output to a file? I have a script that generates output of various forms - mostly standard output and error channels.
I have tried things like:
script.ps1 > $somefile 2>&1
script.ps1 | tee-object <args>
script.ps1 | out-file <args>

I've also tried start-transcript / stop-transcript. All of these methodologies have their drawbacks, or just don't plain seem to work.
What is the closest powershell equivalent of the UNIX-style invocation:
myScript.ps1 > $somefile 2>&1

When I try the above command in powershell, I see all output on console, and a 0-length file called 'output' is left behind. What gives?
EDIT: Okay, I believe most of my problem lies in the fact I'm using Write-Host, which I think bypasses the standard output stream. However, I am very worried that if I switch my Write-Host statements to Write-Output, then I'll end up corrupting the return values of all of my functions, or seriously screwing my script up some other way.
What is my most prudent option of dealing with the Write-Host entries so that I can reliably capture all output and errors to the same file? Also, I'm using colorization capabilities from Write-Host... I'm guessing I'll have to give that up if I'm looking to dump to log files.
Or even better, is it possible to set up a command-line argument, say, '-console' that controls whether Write-Host or something else is used? My script is initially being run dozens of times a day manually and interactively. It will then run once an hour every day for years to come, where logs of all output/errors will be desired.

A: Instead of doing
myScript.ps1 > $somefile

You can do
powershell myScript.ps1 > $somefile

A: I'd focus my efforts on start and stop transcript. I use it in a 3-tier system involving a client calling a script on a server that proxies a call to another server via PSRemote, and it does a splendid job for me. The output is clean and easily parsed.
It fails with native commands, unless you pipe its output to Out-Default. And you can't get to fancy with it. One transcript is all you get at a time, but one's enough.


text:
Q: Split cart in magento according to item I wish to wish split my cart according to the item. At a time I want to checkout with one product.For multiple products, cart will split into multiple carts and user at a time can checkout with one product.

Thanks in advance :)

A: You can achieve this by following the below steps.
Step-1: When user click in any product checkout button that time you need to save rest product in session and remove from cart. In checkout page, it will charge only single product which the user chooses for checkout.
Step-2: After checkout and before the success page load you need to add session product again in the cart.(use observer for this)
Step-3: After added product in the cart then you need to clear the session again.
For example, if a user come back from the checkout page to cart page without placing an order in this case you need to add session products back to the cart and clear session.


text:
Q: Using "where" clauses to produce optional types in Swift arithmetic I would like to trigger conditional logic based around certain UI relationships during user interaction (in this case, I want to call a method when a user scrolls to a certain point in a UIScrollView). I would expect the following line of code to do this legally, since it is quite expressive:
func scrollViewDidScroll(scrollView: UIScrollView) {
    guard let overlap = scrollView.contentOffset.y - 220 where overlap > 0 else {
        return
    }

    reactToScrollOverlap(of: overlap)
}

However, I get the error that the guard let requires an optional type. That's reasonable, but I expected in this case that the where clause would naturally introduce an optional, since if the arithmetic works out wrong then there is no matching value of overlap.
Is there a way to use guard let (or, alternatively, if let) such that included where clauses stipulate conditions on the outcomes of arithmetic between Int, CGFloat, or other primitive/primitive-like types?

A: guard and if let statements are normally only used to unwrap optionals.  I'm not really thrilled with this solution, but you could cast scrollView.contentOffset.y as an Optional<CGFloat> to get the behavior you want:
guard let overlap = scrollView.contentOffset.y - 220 as CGFloat? where overlap > 0 else {
    return
}

A: guard let value = someOptionalValue {
}

if let value = someOptionalValue {
}

These are the way how you bind an optionals to a variable. If you are using guard let or if let you are using to get a value from optional types only.
and where clause will be triggered only when all the optionals have a value that precedes the where clause.
I think what you want to do is something like this:
let delta = scrollView.contentOffset.y - 220

if delta > 0 {

} else {

}

I would prefer clarity over brevity.
Edit:
Here is a better way to do it I think:
let yOffset        = scrollView.contentOffset.y
let newOffset:Int? = yOffset > 220 ? yOffset : nil

A: You are doing 3 things in one expression - declaring a variable (constant), assigning it and checking its value.
Declaring a variable in expressions is usually frowned upon, Swift does not really enable it. With one exception - unwrapping of optionals. You are not unwrapping an optional so just split the expression correctly into a declaration and a comparison:
let overlap = contentOffset.y - 220

guard overlap > 0 else {
    return
}

Another option is to use the case let pattern. I am not a big fan of it but it's probably what you want:
guard case let overlap = contentOffset.y - 220 where overlap > 0 else {
    return
}

print("overlap:", overlap)


text:
Q: What happens when in offline sorting the dataset size exceeds RAM size? What happens when in offline sorting the dataset size exceeds RAM size?
I have to sort a large text file and want to know what happens if the size of my text file file exceeds the RAM size.

A: Offline sorting is precisely designed to work in the case where you can't fit your data set into RAM. The general idea is to split the data set apart into smaller pieces, each of which can fit into memory, and to sort each piece independently of the others. Afterwards, you can combine them all together.
The most common external sorting algorithm is an external mergesort. You begin by splitting your input apart into blocks of some fixed size - usually, as much as you can fit into RAM at one time - then sort those blocks independently and write the sorted versions back to disk. You then do a k-way merge operation to combine all of the sorted sequences back together; the specific algorithm used is usually a generalization of the normal 2-way merge algorithm combined with some buffering to minimize disk reads.
A less common approach is to use quicksort and a double-ended priority queue. You can read more about this here.


text:
Q: Cannot read property 'length' of undefined (Angular 6) I am trying to display MySQL tables in my project which is now fetching the tables from local json file.

public getProperties(): Observable<Property[]>{
    return this.http.get<Property[]>(this.url + 'properties.json');

  }

When replacing the url with the one with which i'm fetching the mysql table object using NodeJs and express, I get the given error in console. This is how I went:
public getProperties(): Observable<Property[]>{
    return this.http.get<Property[]>('http://localhost:3000/');

  }

Is there a way I can successfully pass the url to access MySQL tables?
Here is my NodeJS code:
router.get('/', function(req, res, next) {
  res.setHeader("Content-Type", "text/html");

  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  console.log("Function called")
  con.query('SELECT * FROM authors', (err,rows) => {
    if(err) throw err;

    console.log('Data received from Db:');
    console.log(rows);
    DBRows = rows;

    console.log("Data sent")
    res.send(JSON.stringify(DBRows));
  });
});

  con.query('SELECT * FROM authors', (err,rows) => {
    if(err) throw err;

    console.log('Data received from Db:');
    console.log(rows);
    DBRows = rows;

    console.log("Data sent")
    JSON.stringify(DBRows);
    res.send(JSON.stringify(DBRows));

  });

});

A: What is the result of "JSON.stringify(DBRows)" ?
You are expecting an array of Property in the result (Property[]) but you return a stringified DBRows which is probably an object
You need to modify your code so the result match what you expect.
If the result of "JSON.stringify(DBRows)" is
{
   values: [ {/* DbRow */}, {/* DbRow */}, ... ]
}

Then in your service you need to expect a similar object, example :
export class Response {
   values: Property[];
}
...
return this.http.get<Response>('http://localhost:3000/');


text:
Q: Node setInterval to modify global variable and access it from other module I need to check every 4 seconds if an ip is alive.
I'm using a global variable global.baseip (I know it's bad practice, I am only trying it out with setInterval)
global.baseip = "http://10.***.**.**:8048/TESTDEV02/ODataV4/Company('****')";

setInterval(function(){
  getip();
  console(baseip); //this gives the correct value
}, 4000);

 var getip = function() {
  var hosts = [["10.***.**.**", 8048]];
  hosts.forEach(function (item) {
    var sock = new net.Socket();
    sock.setTimeout(2500);
    sock
      .on("connect", function () {
        baseip =
          "http://'10.***.**.**':8048/TESTDEV02/ODataV4/Company('****')";
        sock.destroy();
      })
      .on("error", function (e) {
        baseip =
          "http://'10.***.**.**':8048/TESTDEV02/ODataV4/Company('****')";
      })
      .connect(item[1], item[0]);
  })
}

Then, I use baseip in other modules/files but it's always undefined.
Any help would be appreciated

A: Don't use a global. Though you may get it to work as you have discovered it is not easy to get it to work and is easy to forget something that causes your code to not work. It is also messing with node's internals and is deliberately working against the way node.js was designed. Node.js was explicitly designed to prevent people from using global variables. Therefore if you want to use global variables you need to somehow work around those protections.
Instead a simpler and more stable way to do this is to use a module.
One thing people don't realise about Commonjs modules is that they are singletons. This is a consequence of the module caching behavior. What this means is that if you import a module into 10 different files then you are not creating ten different objects that represent your module but all 10 files share a single object (the definition of the Singleton design pattern). Note that this works not only in node.js but also other Commonjs based systems like Webpack, React.js (jsx) and Typescript.
The code is really simple. So simple in fact that it makes no sense not to use this method because trying to circumvent the module system is far more complicated:
// shared.js

let shard_object = {
    baseip: "http://10.***.**.**:8048/TESTDEV02/ODataV4/Company('****')"
}

module.exports = shared_object;

Note: You can of course write the above much simpler or much more complicated. I wrote it the way I did for clarity

Then you can share the module above with your other modules:
// getip.js

const shared = require('./shared');

var getip = function() {
  var hosts = [["10.***.**.**", 8048]];
  hosts.forEach(function (item) {
    var sock = new net.Socket();
    sock.setTimeout(2500);
    sock
      .on("connect", function () {
        shared.baseip =
          "http://'10.***.**.**':8048/TESTDEV02/ODataV4/Company('****')";
        sock.destroy();
      })
      .on("error", function (e) {
        shared.baseip =
          "http://'10.***.**.**':8048/TESTDEV02/ODataV4/Company('****')";
      })
      .connect(item[1], item[0]);
  })
}

module.exports = getip;

and it works as expected:
// main.js

const getip = require('./getip');
const shared = require('./shared');

setInterval(function(){
  getip();
  console(shared.baseip); // this gives the correct value
}, 4000);

A: Because you define another variable with the same name inside the scope, you are in reality making changes to that variable.
Just get rid of it, so you can work with the real baseip.
 var getip = function() {
  //var baseip; //This variable is overshadowing your global variable
  var hosts = [["10.***.**.**", 8048]];
  hosts.forEach(function (item) {
    var sock = new net.Socket();
    sock.setTimeout(2500);
    sock
      .on("connect", function () {
        baseip =
          "http://'10.***.**.**':8048/TESTDEV02/ODataV4/Company('****')";
        sock.destroy();
      })
      .on("error", function (e) {
        baseip =
          "http://'10.***.**.**':8048/TESTDEV02/ODataV4/Company('****')";
      })
      .connect(item[1], item[0]);
  })
}