text:
Q: Rails 4: button_to not submitting params I am trying to get the following to work -
  Basically, the button submits to the searches_controller index action and SHOULD pass the params[:search_task] to it. But for some reason its not working.

            <button class = "btn btn-success InterestStatButton"><%= User.tagged_with(interest, :on => :tags, :any => true).count %></button>
            <%= button_to interest, searches_path, :method => :get,  :class => "btn btn-default InterestLabelButton"  %>
            <%= hidden_field_tag :search_task, interest, :id => "search", :class => "form-control" %>

On the very same page in the header I have this in the header which is an input field doing the same thing, and works fine. What I don't get it if you look at what each is producing in the HTML the hidden field in the first block of code is the same as the input in the form_tag in the second block of code.
          <%= form_tag searches_path, html: {class: "navbar-form navbar-left"}, :method => :get do %>

                    <%= text_field_tag :search_task, nil, class: "form-control", id: "search", placeholder: "Search for members or content", label: false %>

            <% end %>

A: The problem is that button_to is a self-contained method (IE you cannot pass a block etc):

Generates a form containing a single button that submits to the URL
  created by the set of options.

When you use:
<%= button_to interest, searches_path, :method => :get,  :class => "btn btn-default InterestLabelButton"  %>
<%= hidden_field_tag :search_task, interest, :id => "search", :class => "form-control" %>

... it simply won't be added to the form, hence will not be passed.

How to add additional params to a button_to form?
What you'll need is to add the search_task param to your button_to helper:
<%= button_to interest, searches_path, method: :get, class: "btn btn-default InterestLabelButton", params: { search_task: interest }  %>

The button_to form sends a POST request by default. This will mask the passed params; if you want to use GET, you've done the right thing and declared it. An important note is that the GET request appends params to the request URL.
You can read more about it here: http://www.w3schools.com/tags/ref_httpmethods.asp


text:
Q: Referrer-Policy with PHP and htaccess is there any way to overwrite the header referrer policy using htaccess or PHP?
HTML Code :
<meta name="referrer" content="origin">

Is any way to do same with htaccess or PHP? i tried these code from How to set Firefox referrer to "no-referrer" using PHP Referrer-Policy?
I tried (PHP) :
header("Referrer-Policy: origin");

With Htaccess :
<IfModule mod_headers.c>
    Header set Referrer-Policy "origin"
</IfModule>

Still it not overriding strict-origin-when-cross-origin.
Firefox info : https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy

A: I tried in private browser and it worked !!
<IfModule mod_headers.c>
    Header set Referrer-Policy "origin"
</IfModule>

redpajama_set_name: RedPajamaStackExchange


text:
Q: как сделать чтобы поток с++11 не висел? здравствуйте, есть абстрактная задача: создаются три асинхронных нити, первая - управляющая - ждет 3 секунды, затем с помощью condition variable запускает вывод у двух ожидающих сигнала нитей:
namespace mutexes {
std::mutex m;
std::condition_variable cond;
std::atomic<bool> at = ATOMIC_VAR_INIT(0);

void thread_1() {
    while(true) {
        static int i = 0;
        std::cout<<"thread 1\n";
        std::this_thread::sleep_for (std::chrono::seconds(1));
        if(i==5)
            break;
        if(i++==2) {
            at = 1;
            cond.notify_all();
        }
    }
    at = 0;
}
void thread_2() {
    while(true) {
        std::unique_lock<std::mutex> lk(m);
        cond.wait(lk,[]{ return at == 1;});
        std::cout<<"thread 2\n";
        std::this_thread::sleep_for (std::chrono::milliseconds(500));
    }
}
void thread_3() {
    while(true) {
        std::unique_lock<std::mutex> lk(m);
        cond.wait(lk,[]{ return at == 1;});
        std::cout<<"thread 3\n";
        std::this_thread::sleep_for (std::chrono::milliseconds(500));
    }
}
}    //namespace mutexes

int main() {
//запускаем все три потока асинхронно
std::thread([]{
            std::thread thrd1(&mutexes::thread_1);
            std::thread thrd2(&mutexes::thread_2);
            std::thread thrd3(&mutexes::thread_3);
            thrd1.detach();
            thrd2.detach();
            thrd3.detach();
            std::this_thread::sleep_for (std::chrono::seconds(6));
        }).join();
}

в итоге вывод идет только со второго(thread_2)... я не могу понять почему, видимо dead lock мьютекса... помогите сделать так, чтобы вывод в консоль шел с обоих потоков

A: В вашем исходном коде проблема в том, что оба потока требуют блокировку на одном и том же мьютексе для работы - поэтому в каждый момент времени может работать только один. Почему бы "этому одному" не быть каждый раз потоком номер 2? Совершенно корректное поведение.
Вам, наверное, следовало бы после получения задания освободить блокировку, чтобы потоки смогли работать одновременно:
void thread_2() {
    while(true) {
        {
            std::unique_lock<std::mutex> lk(m);
            cond.wait(lk,[]{ return at == 1;});
        }
        std::cout<<"thread 2\n";
        std::this_thread::sleep_for (std::chrono::milliseconds(500));
    }
}

PS Почему потоки 2 и 3 не могут быть запущены не сразу, а потоком 1 после истечения времени ожидания? Это бы все упростило.

A: сам отвечаю на свой вопрос... получился вывод с двух потоков только так:
namespace mutexes {
std::mutex m1;
std::mutex m2;
std::condition_variable_any cond;
std::atomic<bool> at = ATOMIC_VAR_INIT(0);

void thread_1() {
while(true) {
    static int i = 0;
    std::cout<<"thread 1\n";
    std::this_thread::sleep_for (std::chrono::seconds(1));
    if(i==5)
        break;
    if(i++==2) {
        at = 1;
        cond.notify_all();
    }
}
at = 0;
}

void thread_2() {
std::unique_lock<std::mutex> lk(m1);
while(true) {
    cond.wait(lk,[]{ return at == 1;});
    std::cout<<"thread 2\n";
    std::this_thread::sleep_for (std::chrono::milliseconds(500));
}
}

void thread_3() {
std::unique_lock<std::mutex> lk(m2);
while(true) {
    cond.wait(lk,[]{ return at == 1;});
    std::cout<<"thread 3\n";
    std::this_thread::sleep_for (std::chrono::milliseconds(500));
}
}
}    //namespace mutexes

int main() {
//запускаем все три потока асинхронно
std::thread([]{
        std::thread thrd1(&mutexes::thread_1);
        std::thread thrd2(&mutexes::thread_2);
        std::thread thrd3(&mutexes::thread_3);
        thrd1.detach();
        thrd2.detach();
        thrd3.detach();
        std::this_thread::sleep_for (std::chrono::seconds(6));
    }).join();
}

платформа linux_x86_64... был бы рад если б кто-нибудь объяснил бы почему работает только с std::condition_variable_any а не с std::condition_variable


text:
Q: How can I see what gems are currently in the ruby environment? My goal is, after running a script that may have some requires in it (or before), to see all of the gems that are loaded into my current environment.
Thank you!

A: Gem.loaded_specs.keys

(found here)


text:
Q: Scala - Spark In Dataframe retrieve, for row, column name with have max value I have a DataFrame:
name     column1  column2  column3  column4
first    2        1        2.1      5.4
test     1.5      0.5      0.9      3.7
choose   7        2.9      9.1      2.5

I want a new dataframe with a column with contain, the column name with have max value for row :
| name   | max_column |
|--------|------------|
| first  | column4    |
| test   | column4    |
| choose | column3    |

Thank you very much for support.

A: There might some better way of writing UDF. But this could be the working solution
val spark: SparkSession = SparkSession.builder.master("local").getOrCreate

//implicits for magic functions like .toDf
import spark.implicits._

import org.apache.spark.sql.functions.udf

//We have hard code number of params as UDF don't support variable number of args
val maxval = udf((c1: Double, c2: Double, c3: Double, c4: Double) =>
  if(c1 >= c2 && c1 >= c3 && c1 >= c4)
    "column1"
  else if(c2 >= c1 && c2 >= c3 && c2 >= c4)
    "column2"
  else if(c3 >= c1 && c3 >= c2 && c3 >= c4)
    "column3"
  else
    "column4"
)

//create schema class
case class Record(name: String,
                    column1: Double,
                    column2: Double,
                    column3: Double,
                    column4: Double)

val df = Seq(
  Record("first", 2.0, 1, 2.1, 5.4),
  Record("test", 1.5, 0.5, 0.9, 3.7),
  Record("choose", 7, 2.9, 9.1, 2.5)
).toDF();

df.withColumn("max_column", maxval($"column1", $"column2", $"column3", $"column4"))
  .select("name", "max_column").show

Output
+------+----------+
|  name|max_column|
+------+----------+
| first|   column4|
|  test|   column4|
|choose|   column3|
+------+----------+

A: You get the job done making a detour to an RDD and using 'getValuesMap'.
val dfIn = Seq(
  ("first", 2.0, 1., 2.1, 5.4),
  ("test", 1.5, 0.5, 0.9, 3.7),
  ("choose", 7., 2.9, 9.1, 2.5)
).toDF("name","column1","column2","column3","column4")

The simple solution is
val dfOut = dfIn.rdd
  .map(r => (
       r.getString(0),
       r.getValuesMap[Double](r.schema.fieldNames.filter(_!="name"))
     ))
  .map{case (n,m) => (n,m.maxBy(_._2)._1)}
  .toDF("name","max_column")

But if you want to take back all columns from the original dataframe (like in Scala/Spark dataframes: find the column name corresponding to the max), you have to play a bit with merging rows and extending the schema
import org.apache.spark.sql.types.{StructType,StructField,StringType}
import org.apache.spark.sql.Row
val dfOut = sqlContext.createDataFrame(
  dfIn.rdd
    .map(r => (r, r.getValuesMap[Double](r.schema.fieldNames.drop(1))))
    .map{case (r,m) => Row.merge(r,(Row(m.maxBy(_._2)._1)))},
  dfIn.schema.add(StructField("max_column",StringType))
)

A: I want post my final solution:
val finalDf = originalDf.withColumn("name", maxValAsMap(keys, values)).select("cookie_id", "max_column")

val maxValAsMap = udf((keys: Seq[String], values: Seq[Any]) => {

    val valueMap:Map[String,Double] = (keys zip values).filter( _._2.isInstanceOf[Double] ).map{
      case (x,y) => (x, y.asInstanceOf[Double])
    }.toMap

    if (valueMap.isEmpty) "not computed" else valueMap.maxBy(_._2)._1
  })

It's work very fast.


text:
Q: Downloading heavy images(>2GB) from server using NodeJS I am using the AngularJS and NodeJS for my project. I am storing my images to the AWS-EFS storage which is attached with an AWS-EC2 instance. Everything is working fine till I was downloading small images(less than 1 GB). When I tried to download big images(greater than 1 GB) it is throwing error.
Here is my Back-end code,
getTiff: function(req, res)
   {
       res.set('Content-Type', 'application/octet-stream')
       var name = req.param('filename').split('.')[0]
       var id = req.param('id')
       var filePath = '/mys3storage/' + id + '/' + name +
       '/3_dsm_ortho/2_mosaic/' + name + '_transparent_mosaic_group1.tiff'
       files = fs.readFileSync(filePath)
       res.send(files)
},

error: Sending 500 ("Server Error") response:
RangeError: Invalid typed array length
    at new Uint8Array (native)
    at createBuffer (buffer.js:23:15)
    at allocate (buffer.js:98:12)
    at new Buffer (buffer.js:53:12)
    at Object.fs.readFileSync (fs.js:419:16)
    at Object.module.exports.getAutocad.res.getContourLines.res.getContourPdf.res.getOrthoM (G:\desktop\unifliBackend\api\controllers\WebController.js:153:20)
    at wrapper (G:\desktop\unifliBackend\node_modules\@sailshq\lodash\lib\index.js:3250:19)
    at routeTargetFnWrapper (G:\desktop\unifliBackend\node_modules\sails\lib\router\bind.js:181:5)
    at callbacks (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:164:37)
    at param (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:138:11)
    at param (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:135:11)
    at param (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:135:11)
    at pass (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:145:5)
    at nextRoute (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:100:7)
    at callbacks (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:167:11)
    at alwaysAllow (G:\desktop\unifliBackend\node_modules\sails\lib\hooks\policies\index.js:224:11)
    at routeTargetFnWrapper (G:\desktop\unifliBackend\node_modules\sails\lib\router\bind.js:181:5)
    at callbacks (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:164:37)
    at param (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:138:11)
    at param (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:135:11)
    at param (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:135:11)
    at pass (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:145:5)
    at nextRoute (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:100:7)
    at callbacks (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:167:11)
    at G:\desktop\unifliBackend\node_modules\sails\lib\router\bind.js:232:18
    at callbacks (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:164:37)
    at param (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:138:11)
    at pass (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:145:5)
    at nextRoute (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:100:7)
    at callbacks (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:167:11)
    at G:\desktop\unifliBackend\node_modules\sails\lib\router\bind.js:232:18
    at callbacks (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:164:37)
    at param (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:138:11)
    at pass (G:\desktop\unifliBackend\node_modules\@sailshq\express\lib\router\index.js:145:5)

I'have also tried with createReadStream() but I can download one file at a time, on second file it would give me network failed error on browser. Please help!

getTiff: function(req, res) {
    res.set('Content-Type', 'application/octet-stream')
    var name = req.param('filename').split('.')[0]
    var filePath = req.param('id') var filePath = '/mys3storage/' + id + '/' + name + '/3_dsm_ortho/2_mosaic/' + name + '_transparent_mosaic_group1.tiff'
    fs.createReadStream(filePath).pipe(res)
}

This is the stream code I have used. It is working fine when I download one file at a time. if try to download to two files at a time it will stop the second file and shows "network failed" from browser
Here is my browser side code:
$scope.downloadOrthoMission = function(idForDownload, missionIdForDownload) {
    window.open(adminurl + 'getTiff/' + idForDownload + '/' + missionIdForDownload + '.tif', '_self')
}

A: Just referred this answer,
Nginx node.js express download big files stop at 1.08GB
It is working absolutely fine for me.


text:
Q: Check if a Firestore query (whereField isEqualTo) did find no documents I want to check if my Firestore query did find any documents with the specific fields I want or not. If not I would like to proceed to some other code.
Unfortunately I haven't found a solution myself to this problem. Can you help?
Code:
Firestore.firestore().collection("conversations").whereField("mainUserID", isEqualTo: MainUID)
.whereField("otherUserID", isEqualTo: otherUserId).getDocuments { (snapshot, err) in

if snapshot.exists == true {                // Value of type 'QuerySnapshot?' has no member 'exists'

} else {

       }
}

A: From the docs

A FIRQueryDocumentSnapshot contains data read from a document in your
Firestore database as part of a query. The document is guaranteed to
exist and its data can be extracted with the data property or by using
subscript syntax to access a specific field.
A FIRQueryDocumentSnapshot offers the same API surface as a
FIRDocumentSnapshot. As deleted documents are not returned from
queries, its exists property will always be true and data: will never
return nil.

with the important bit being this

The document is guaranteed to exist

so therefore a .exists option would not make sense due to the guaranteed existence of the snapshot.
One approach is to check how many documents are in the snapshot
if docs.count > 0 {
   //there are docs
} else {
   //there are no docs
}


text:
Q: Using "string_view" to represent the "string" key When I use map<string, string> kv; in protobuf 3.8.0, the next code works:
std::string_view key("key");
kv[key] = "value";

While in protobuf 3.19.4, the above code doesn't work.
The error msg is:

error: no match for 'operator[]' (operand types are 'google::protobuf::Map<std::__cxx11::basic_string
, std::__cxx11::basic_string>' and 'std::string_view' {aka 'std::basic_string_view'})

A: In 3.8.0, Map::operator[] is declared as:
Value& operator[](const Key& k)

Where, in your case, Key is std::string. std::string_view is convertible to std::string, which is why the code works in 3.8.0.
In 3.19.4, Map::operator[] is declared as:
template <typename K = key_type>
T& operator[](const key_arg<K>& key)

template <
    typename K = key_type,
    // Disable for integral types to reduce code bloat.
    typename = typename std::enable_if<!std::is_integral<K>::value>::type>
T& operator[](key_arg<K>&& key)

Where key_arg is declared as:
template <typename LookupKey>
using key_arg = typename internal::TransparentSupport<key_type>::template key_arg<LookupKey>;

And, in your case, key_type is std::string. std::string_view is not convertible to TransparentSupport::key_arg, which is why the code doesn't work in 3.19.4.


text:
Q: How to change the bootstrap's well color? I just started learning php and I dont know how to change the color of well.
Doing research I found this
.well.homefull{

background: rgba(0, 0, 0, 0.4);

}

But I dont know where to put it and how to use it with

if I simply put it before div class=well it doesnt work

A: You'll need to override the css rules of the boostrap well class.
To do this, you'll need to create a custom css file and call this external style sheet from the html page.
For example :

.well {
    background-color: rgba(0,0,0,0.4) !important;
}

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

    Some content

Hope it helps.
EDIT :
Or in one page, you could put the style rules between  tag (take care to put the overriding style rules after the call of bootstrap sources) :
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Developping JazZ Sheet</title>

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

        some content


text:
Q: Speed up scrolling in winforms treeView I need to speed up vertical scrolling while draging item in treeView in winforms project. I am not very familiar with winforms. Is this possible with treeView? Any solutions?

A: You should be able to use a combination of the TreeView's ItemDrag event and this answer, Maintain scroll position of treeview, to do what you are attempting to do.


text:
Q: How can I tell Asset Catalog (.xcassets) to use the Same Image for Multiple Image Wells? We have several Xcode app projects, and we're upgrading all of them to use the latest Xcode 5 features, including Asset Catalogs (.xcassets).
All of our default (launch) images already include spacing for the status bar, and we want to use these images for both the iOS 5,6 and iOS 7 launch images. Further, we don't want to include multiple copies of the same image in the project.
One of our projects is correctly set to use the same images for both of these image well sets. However, this was setup more so by accident.
Besides editing the Contents.json file directly (which is a last-resort workaround if need be), how can we do this using the Xcode GUI editor for Asset Catalog?
What we've already tried
1) Dragging and dropping the image to a different position... just moves the image to the other set
2) Dragging and dropping the same file from Finder to the Asset Catalog... creates a new copy of the image
3) Dragging and dropping the image with option (alt) pressed... creates a new copy of the image

A: You can right click on the .xcassets file and choose 'Show in Finder'. Go to the 'Image.launchimage' folder and open the Contents.json file in a text editor. Here you can see that unassigned slots don't contain an "filename". You can add this manually. For example change the following:
{
    "orientation" : "landscape",
    "idiom" : "ipad",
    "extent" : "full-screen",
    "minimum-system-version" : "7.0",
    "scale" : "2x"
}

Into:
{
    "orientation" : "landscape",
    "idiom" : "ipad",
    "extent" : "full-screen",
    "minimum-system-version" : "7.0",
    "filename" : "Default-Landscape@2x~ipad.png",
    "scale" : "2x"
}

Now safe the file, and voila!

A: I solved this by using build scripts to copy the right xcassets file in for each target. Details here

A: I think I've found the solution:  Simply drag the default images that you want to be used for iOS 6 and 7 into the iOS 6 bucket.  You get a warning about not having an iOS7-only image but the build works in the iOS7 simulato, an iOS7 iPhone and an iOS7 iPad.

A: I solved this by removing old xcassets and added new xcassets by using Don't use app catalogs

A: In my case I am using cocoa pods. The cocoa pods script Pods-resources.sh somehow caused the problem. Removing the asset parts from the script solved the problem.
Make sure to clean your project and delete derived data folder.
Parts to be deleted can be found here:
https://stackoverflow.com/a/21309102/832111

A: I upgraded to cocopods 0.37 and the problem was solved. If you used cocopods then it was probably its fault.


text:
Q: Export a Uint8 array as an image using Images in Julia I recently asked how to convert Float32 or Uint8 arrays into images in the Images package. I got an answer for the Float32 case, but am still having trouble figuring out how to save a Uint8 array.
As an example, let's create a random Uint8 array using the traditional Matlab scheme where the dimensions are (m,n,3):
array = rand(Uint8, 50, 50, 3);
img = convert(Image, array);

Using the same approach as works for the Float32 case,
imwrite(img, "out.png")

fails with message

ERROR: method 'mapinfo' has no method matching mapinfo(::Type{ImageMagick}, ::Image{Uint8, 3, Image{Uint8, 3, Array{Uint8, 3}}}).

I checked the documentation, and it says

If data encodes color information along one of the dimensions of the array (as opposed to using a ColorValue array, from the Color.jl package), be sure to specify the "colordim" and "colorspace" in properties.

However, inspecting the img object previously created shows that it has colordim = 3 and colorspace = RGB already set up, so this can't be the problem.
I then searched the documentation for all instances of MapInfo. In core.md there is one occurrence:

scalei: a property that controls default contrast scaling upon display. This should be a MapInfo value, to be used for setting the contrast upon display. In the absence of this property, the range 0 to 1 will be used.

But there was no information on what exactly a MapInfo object is, so I looked further, and in function_reference.md it says:

Here is how to directly construct the major concrete MapInfo types:
MapNone(T), indicating that the only form of scaling is conversion to type T. This is not very safe, as values "wrap around": for example, converting 258 to a Uint8 results in 0x02, which would look dimmer than 255 = 0xff.
...

and some other examples. So I tried to specify scalei = MapNone(Uint8) as follows:
img2 = Image(img, colordim = 3, colorspace = "RGB", scalei = MapNone(Uint8));
imwrite(img, "out.png")

but got the same error again.
How do you encode Uint8 image data using Images in Julia?

A: You can convert back and forth between arrays of primitive types such as UInt8 and arrays of color types. These conversions are achieved in a unified way via two functions: colorview and channelview.
Example
Convert array of UInt8 to array of RGB:
arr = rand(UInt8, 3, 50, 50)
img = colorview(RGB, arr / 255)

Convert back to channel view:
channelview(img)

Notes

*

*In this example the RGB color type requires that the entries of the array live in [0,1] as floating point. I manually converted UInt8 to Float64 using an explicit division by 255. There is probably a more generic way of achieving this result with reinterpret or some other function in Images.jl

*The colorview and channelview functions assume that the channel dimension is the first dimension of the array. You can use permutedims in case your channels live in a different dimension, or use some function in Images.jl (maybe reinterpretc?) to do it efficiently without memory copies.


text:
Q: how to send data in ping program I wanted to send data to the loop-back IP address 127.0.0.1 using the ping program.
$ping 127.0.0.1 "my data" and wanted to see it in the kernel space.
if anyone has some idea please respond to me

A: Use ping's -p option:

-p pattern
              You may specify up to 16 ``pad'' bytes to fill out the packet you send.
     This is useful for  diagnosing data-dependent  problems in a network.
     For example, -p ff will cause the sent packet to be filled with all ones.


text:
Q: Vuex - Load data from API on first getter call and then load from state I have a Vuex instance which loads data from API. The first time I access the store it should load the data from API, and when I access it again it should return the loaded data from the store.empresas. This is how my Vuex module looks like:
import Empresas from '@/api/empresas'
import moment from 'moment'

export default {
  state: {
    loaded: false,
    lastLoadedDate: null,
    empresas: []
  },

  getters: {
    empresas: state => {
      if (!state.loaded || moment().diff(state.lastLoadedDate, 'minutes') > 30) {
        //Was not loaded yet or was loaded more than 30 minutes ago,
        //Sould load from api -> actions.carregarEmpresas()
        //Don't know how to proceed here
      } else {
        //Already loaded
        return state.empresas
      }
    }
  },

  mutations: {
    setEmpresas (state, payload) {
      state.loaded = true
      state.lastLoadedDate = moment()
      state.empresas = payload
    }
  },

  actions: {
    carregarEmpresas ({ commit }) {
      Empresas.listar()
        .then(({ data }) => {
          commit('setEmpresas', data.empresas)
        })
    }
  }
}

The reason I need this is that I will need to access empresas in multiple files in my application, and I don't want to make an API call every time.
However, I don't know how to implement it inside the getter. Is it possible to do it?

A: This might be a duplicate of this post: Can I do dispatch from getters in Vuex. Check if the second answer helps you.
Basically, you shouldn't call actions from you getters. I would recommend you call the action at the initial load of the app. Then you will just use the getter without the conditional.


text:
Q: C++ dictionary trie implementation I am getting a segfault in my insert function on the line:
current->isWord = true;

Everything compiles fine with no warnings or errors (g++ -Wall -Wextra).  My main function just calls the insert function once and it won't work.  Here is my code; it is a hybrid between my .h and .cpp file:
const int alphabetSize = 26;

struct Node
{
    bool isWord;
    Node* child[alphabetSize];
};

Dictionary::Dictionary()
{
    initNode(head); //Node* head; is defined in my .h file under private:
}

bool Dictionary::isPrefix(string s)
{
    Node* current = endOfString(s, false);
    if (current == NULL)
    {
        return false;
    }
    else
    {
        return true;
    }
}

bool Dictionary::isWord(string s)
{
    Node* current = endOfString(s, false);
    if (current == NULL)
    {
        return false;
    }
    else
    {
        return current->isWord;
    }
}

void Dictionary::insert(string s)
{
    Node* current = endOfString(s, true);
    current->isWord = true; //segfault here
}

//initializes a new Node
void Dictionary::initNode(Node* current)
{
    current = new Node;
    current->isWord = false;
    for (int i = 0; i < alphabetSize; i++)
    {
       current->child[i] = NULL;
    }
}

//returns a pointer to the Node of the last character in the string
//isInsert tells it whether it needs to initialize new Nodes
Node* Dictionary::endOfString(string s, bool isInsert)
{
    Node* current = head;
    Node* next = head;
    for (unsigned int i = 0; i < s.length(); i++)
    {
        if (isalpha(s[i]) == true)
        {
            int letter = (tolower(s[i]) - 'a');
            next = current->child[letter];
            if (next == NULL)
            {
                if (isInsert == false)
                {
                    return NULL;
                }

                initNode(next);
                current->child[letter] = next;
            }
            current = current->child[letter];
        }
    }

    return current;
}

A: initNode creates a new Node and initializes it, but it is then discarded. Because current is passed by value, when it is modified inside of the function, the changes do not propagate outside of initNode. The straightforward fix is to make it pass by reference:
void Dictionary::initNode(Node*& current)

A: The problem is here:
//initializes a new Node
void Dictionary::initNode(Node* current)
{
    current = new Node;
    current->isWord = false;
    for (int i = 0; i < alphabetSize; i++)
    {
       current->child[i] = NULL;
    }
}

current is passed in by value, so when you alter current in the method you are altering a copy of what was passed in, not the exterior variable. Try passing in a Node** current that is a pointer to your pointer so you can edit the original variable. You would call it like this; initNode(&next); and in the method you would dereference current to be able to edit the original variable.


text:
Q: How to know if my app comes back to background I started developing an app that requires the user to go through login every time.
Mainly I would like to know when the user clicks on my app icon and start it, so I would be able to start the login activity instead of the activity he left open in the last time he used the app.
Thanks :)

A: Well, that question has other implications that arise questions like, why would you want to do so? going again a consistent interaction for the user and along with the way the system works.
Obviating all that and as far as I'm concerned the only way to do so is to take the user to the login screen in all the onResume of all your activities with startActity.

A: According to android documentation, you can acheive that via manifest.xml file.
by setting android:clearTaskOnLaunch="true" for your activity node in your manifest.
say your activity name is MainActivity then your manifest.xml should look like this:
.....
<activity android:name=".MainActivity"
          android:clearTaskOnLaunch="true"
 .....

A: You need to use LifecycleObserver. From this you can know when your application is going in background and when your application come to foreground, no matter in which activity you are. Because it is observing application life cycle. So when app come to foreground then you need to start your LoginActivity so it will be on top of your application and user must have to login as like Banking application.
For LifecycleObserver, you need to register in onCreate() method of Application class of your app using below line of code.
ProcessLifecycleOwner.get().lifecycle.addObserver(appLifecycleObserver)

Create class for AppLifecycleObserver for above object (appLifecycleObserver)
class AppLifecycleObserver(val context: Context) : LifecycleObserver {
  /**
   * Call when your app come to foreground
   */
  @OnLifecycleEvent(Lifecycle.Event.ON_START)
  internal fun onEnterForeground() {
    //goto login activity

  }
  /**
   * Call when your app go to background
   */
  @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  internal fun onEnterBackground() {
  }

}

Dependency gradle required:
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0-rc01'

A: I think you can now it by overriding onpause method on the activity and save the state user has left last time in the shared preference
you can see more about activity lifecycle here -> http://developer.android.com/reference/android/app/Activity.html
and here is the activity lifecycle map

I hope my answer helps you but if you have another question about my answer feel free to ask in the comment :)


text:
Q: Can we offload double pointer to GPU using OpenMP I am new to OpenMP and I am trying to parallelize a simple code with a double loop like this one:
for (int i=0; i<n; i++){
    for (int j=0; j<n; j++){
        c[i][j] = a[i][j] + b[i][j];
    }
}

The data types of a,b and c are and must stay double**.
I tried to convert my code to this:
#pragma omp target teams distribute parallel for collapse(2)\
    map(to: a[0:n][0:n],b[0:n][0:n]) map(from: c[0:n][0:n])
for (int i=0; i<n; i++){
    for (int j=0; j<n; j++){
        c[i][j] = a[i][j] + b[i][j];
    }
}

But I get Aborted (core dumped), could somebody help me please?

A: First of all, note that compilers like GCC show explicitly the problem by printing the message: array section is not contiguous in 'map' clause.
As said in the comments, you need to transfer every contiguous blocks on the target device manually since OpenMP only support contiguous arrays/structures.
The following code should work but it is very inefficient, so do not use it in an application unless the goal is to benchmark it:
for (int i=0; i<n; i++)
{
    double* la = a[i];
    double* lb = b[i];
    double* lc = c[i];

    #pragma omp target teams distribute parallel for \
            map(to: la[0:n], lb[0:n]) map(from: lc[0:n])
    for (int j=0; j<n; j++)
    {
        lc[j] = la[j] + lb[j];
    }
}

Note that is should create a kernel for each line which is awful but it would be still very inefficient without that anyway (see the above comments for more information). Note that OpenMP mappers may be used if the number of blocks is known at compile time (and is relatively small).


text:
Q: Tree component is not rendering properly Nested tree control in angular material is not rendering properly. I have used this link https://material.angular.io/components/tree/examples, but its not rendering same as example shown in link.

app.component.html file contains html code for tree view
app.component.html file

      <mat-tree [dataSource]="dataSource" [treeControl]="treeControl" class="example-tree">

        <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>

            <button mat-icon-button disabled></button>
            {{node.name}}

        </mat-tree-node>

        <mat-nested-tree-node *matTreeNodeDef="let node; when: hasChild">

              <button mat-icon-button matTreeNodeToggle
                      [attr.aria-label]="'toggle ' + node.name">
                <mat-icon class="mat-icon-rtl-mirror">
                  {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
                </mat-icon>
              </button>
              {{node.name}}

              <ng-container matTreeNodeOutlet></ng-container>

        </mat-nested-tree-node>
      </mat-tree>

 Drop Area

app.component.ts file contains typescript code for data source and other tree view initialization code.
app.component.ts file
import { NestedTreeControl } from '@angular/cdk/tree';
import { Component } from '@angular/core';
import { MatTreeNestedDataSource } from '@angular/material/tree';
import { TREE_DATA, FoodNode }  from '../../src/dataSource';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'FPGA-App-new';
  treeControl = new NestedTreeControl<FoodNode>(node => node.children);
  dataSource = new MatTreeNestedDataSource<FoodNode>();

  constructor() {
    this.dataSource.data = TREE_DATA;
  }

  hasChild = (_: number, node: FoodNode) => !!node.children && node.children.length > 0;
}

app.module.ts file contains relevant imported modules
app.module.ts file
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatTreeModule, MatIconModule, MatButtonModule } from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    MatTreeModule, MatIconModule, MatButtonModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

A: I had a similar issue where my tree was being rendered like yours. At first I thought it was an issue with the MatTreeModule but discovered that I need to include the proper CSS in my component's style file.
The fix was to ensure the following styles are applied:
.example-tree-invisible {
  display: none;
}

.example-tree ul,
.example-tree li {
  margin-top: 0;
  margin-bottom: 0;
  list-style-type: none;
}

Source: https://stackblitz.com/angular/earqaagjdamd

A: You have to install material-icons if not yet installed:
 npm install material-icons@latest

then you have to import material-icons into your styles.css:
@import "~material-icons/iconfont/material-icons.css";

then import MatIconModule in your app.module.ts:
 import {MatIconModule} from '@angular/material/icon';
 imports: [    MatIconModule,...]


text:
Q: Start up program file load error I've reate a program, and I put in the programone system to statup with windows... using this idea: http://www.geekpedia.com/tutorial151_Run-the-application-at-Windows-startup.html
But, when the program is started... I recive one message error, when this eror say: it's impossible to load file: start.ini
so, when the system start the program, the program is loaded in C:\windows\system32, becaouse this, the file of my program not is loaded...
to load the file, I use this command to get the file directory: Directory.GetCurrentDirectory() + "\\data\\start.ini"
But, how I can load this file, in this case ?

A: You can save the path to start.ini file to the Registery, and read it on startup. See the MSDN
p.s. the other way is to put a link to you app into the Autorun  folder.


text:
Q: jQuery form validation using a class for specific fields only I'm trying to develop a means of telling form fields that they are required fields via a class of "required".
I would like to use jQuery that will highlight all the fields that are required, when the user submits the form and via the jQuery class, show user all the missed/required fields.
Obviously, as the user enters data into the required fields, the jQuery class is removed from these fields.
I am wondering how to approach this requirement, specifically using Oracle Application Express (Oracle ApEx).

A: There is a really complete jquery plugin for this. It will validate your form depending on the classes you add to your input field:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Check out the demo:
http://jquery.bassistance.de/validate/demo/


text:
Q: Changing a jscript variable each time a php include is loaded I have created a page that displays a product list from a database on my home page. When the user clicks on any of the products, a modal is opened and this modal contains product info, as well as a image gallery.
    $product_handler = new Product ($cao);
    $products = $product_handler->getProducts();
    if($products) {
        /* @var $prod Product */
        foreach ($products as $key => $prod) {

            ?>

            <img class="image-modal"  data-toggle="modal" style="width: 192px; height:192px;"  data-target="#<?php echo $prod->prod_name;?>Modal" src="<?php echo $prod->prod_icon; ?>">
            <a data-toggle="modal"  data-id="<?php echo $prod->prod_name ?>"  data-target="#<?php echo $prod->prod_name;?>Modal" class="image_modal">
<?php echo $prod->prod_name ?>

    <?php
$pres_path= "dub/place/folder/Presentation.php";

include $pres_path;
?>
     <?php
        }
    }

Then within the Presentation.php file the modal is called and this contains all the product info and the image gallery.The page also contains a big chunk of javascript used to navigate the images in the gallery.
In this javascript section I have a variable that is used to determine what the current image is.

The problem I have is that when I click on one product and navigate the gallery,and then close the modal and select another product. It continues on the same number as the one I ended on in the previous modal.
In example. In modal 1 there is 5 slides and I close the modal on slide no. 3.If I then open modal 2 which contains 7 slides. I will start on slide no. 3
The reason for this I think, is because the variable currentImage is used by all of the modals. And thus, problems arise
My question is,
How can I make sure that each time a product is clicked, that the variable currentImage is set to 1

A: Create an own scope for each of your "modals":
(function(){
 var currentImage=1;
 alert(currentImage);//1
 //...
 })();
 alert(currentImage);//undefined

So a "scope model" for all of your modals would look like:
 window.unknownfunction1.currentImage;
 window.unknownfunction2.currentImage;

Before it was:
window.currentImage;


text:
Q: Delta Method In BigQuery or SQL? So I am attempting to construct a delta curve that looks at how MLB players performance changes as they age.

The "delta method" looks at all players who have played in back-to-back years. Many players have several back-to-back year "couplets," obviously. For every player, it takes the difference between their rate of performance in Year I and Year II and puts that difference into a "bucket," which is defined by the age of the player in those two years.

So lets say a player posted a batting average of .300 when he was 25 years old and then posted an average .310 when he was 26. So we take that +.10 difference and we put 25/26 age "bucket".
So I have a table constructed like this:
ID   Name      Age  Average
123  Joe Smith  25  .300
123  Joe Smith  26  .310
123  Joe Smith  27  .312
123  Joe Smith  28  .315

So the output I'm looking for is basically one where I'm creating a new row that identifies all instances where we see the difference in average if a player played back-to-back season (so if someone had an age 25 season but not an age 26 season, they wouldn't be included). I'm sure this involves some sort of CASE statement but I'm a little rusty on all this. If you don't know BigQuery, feel free to respond as you would if this was SQL.

A: Try below for BigQuery Standard SQL
#standardSQL
SELECT ID, Name, Age, Average, bucket, ROUND(diff, 3) AS diff
FROM (
  SELECT *,
    CONCAT(CAST(Age AS STRING), '/', CAST(Age + 1 AS STRING)) AS bucket,
    MAX(Average) OVER(nextYear) - Average AS diff
  FROM yourTable
  WINDOW nextYear AS (PARTITION BY ID ORDER BY Age RANGE BETWEEN 1 FOLLOWING AND 1 FOLLOWING)
)
WHERE IFNULL(diff, 0) <> 0
-- ORDER BY ID, Age

You can test/play with it using dummy data from your question
#standardSQL
WITH yourTable AS (
  SELECT 123 AS ID, 'Joe Smith' AS Name, 25 AS Age, .300 AS Average UNION ALL
  SELECT 123, 'Joe Smith', 26, .310 UNION ALL
  SELECT 123, 'Joe Smith', 27, .312 UNION ALL
  SELECT 123, 'Joe Smith', 28, .315
)
SELECT ID, Name, Age, Average, bucket, ROUND(diff, 3) AS diff
FROM (
  SELECT *,
    CONCAT(CAST(Age AS STRING), '/', CAST(Age + 1 AS STRING)) AS bucket,
    MAX(Average) OVER(nextYear) - Average AS diff
  FROM yourTable
  WINDOW nextYear AS (PARTITION BY ID ORDER BY Age RANGE BETWEEN 1 FOLLOWING AND 1 FOLLOWING)
)
WHERE IFNULL(diff, 0) <> 0
ORDER BY ID, Age

A: In sql I would do a self-join on id and the age+1=age and calculate the difference:
select t1.id, t1.name, t1.age, t2.age, t1.average, t2.average, t2.average-t1.average as diff, concat(t1.age,'/',t2.age) as bucket
from yourtable t1
inner join yourtable t2
on t1.id=t2.id and t1.age+1=t2.age

The inner join will make sure that if there is no completed season for the next year, then the record is not included in the resultset.


text:
Q: Excel: Max value in row that is determined by a lookup I'm trying to create a column that will lookup the text in column A, find the row of this text in another sheet table which is referenced by a name range in row 2, and then find the maximum number in that row on the referenced sheet. Below is the closest I've gotten (which I know isn't good). The formula has gotten more complicated as I've tried more possible ways of making this work. Any suggestions are appreciated.
=max(indirect(address(row(VLOOKUP(A9,INDIRECT(W$2),MATCH('Main Tab'!$R9,dates,1),FALSE)),2)&":"&(address(row(VLOOKUP($G9&": "&$A9,INDIRECT(W$2),MATCH('Main Tab'!$R9,dates,1),FALSE)),10000))))

A: You can probably get there with a method like yours, but there is a simpler way using array formulas.
Sample data (A1:H6):
lion      53    52    40    75    27    25    99
tiger     87    63    75    8     76    82    32
cat       56    63    26    23    84    12    100
dog       66    33    91    17    16    85    1
rabbit    66    64    87    80    20    41    37
bird      56    93    61    19    58    94    73

In J1: dog
In K1: {=MAX(IF($A$1:$A$6=$J1, $B$1:$H$6))} (array formula; confirm with CtrlShiftEnter)
An explanation to help understand the logic:

*

*IF(A1:A6=J1, ...) tests whether the value in the first column is equal to the value in J1.

*

*If yes, it returns the value in the same row of B1:H6.

*If no, it returns false.

*MAX() then takes the maximum of the transformed B1:H6.

E.g., when J1=dog, A1:H6 would look like this:
FALSE    FALSE    FALSE    FALSE    FALSE    FALSE    FALSE    FALSE
FALSE    FALSE    FALSE    FALSE    FALSE    FALSE    FALSE    FALSE
FALSE    FALSE    FALSE    FALSE    FALSE    FALSE    FALSE    FALSE
TRUE     66       33       91       17       16       85       1
FALSE    FALSE    FALSE    FALSE    FALSE    FALSE    FALSE    FALSE
FALSE    FALSE    FALSE    FALSE    FALSE    FALSE    FALSE    FALSE


text:
Q: Is it grammatically correct to use 'now' third person past tense narration? Here's my specific example:

Puffing, Ralphie rested her elbows on the guardrail. Body Woman was now talking to a bald super spy.

(For context, Ralphie is on a balcony looking at Body Woman and the super spy.)
Is this grammatically correct for what is supposed to be a third person past tense narrative, or does it ruin it by bringing in the first tense? I don't want any 'it depends on the writer' nonsense. Just yes or no answers backed with arguments please. Also, if it is not grammatically correct, what should I replace 'now' with in a sentence like this in order to get the point across that there has been a change in the situation and now something is happening which was not happening before? The best answer gets a prize.

A: That is a perfectly valid use of the word "now" and does not change the tense.

Now
(Definition) 1.5 (in a narrative or account of past events) at the time spoken of or referred to


text:
Q: JavaScript Issues when Loading I am trying to add an accordion menu to my company's website and for some reason the HTML and CSS load fine, but the JS does not seem to be loading on the page. I am using a template that works on Code Pen, so I am thinking that most likely it is an issue with where/how I am putting the JS in. Any advice? I have put the following code into the  section of the webpage https://www.nlfxpro.com/meet-our-team/:
<script>
/*!
 * classie - class helper functions
 * from bonzo https://github.com/ded/bonzo
 */

( function( window ) {

'use strict';

// class helper functions from bonzo https://github.com/ded/bonzo

function classReg( className ) {
  return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}

// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;

if ( 'classList' in document.documentElement ) {
  hasClass = function( elem, c ) {
    return elem.classList.contains( c );
  };
  addClass = function( elem, c ) {
    elem.classList.add( c );
  };
  removeClass = function( elem, c ) {
    elem.classList.remove( c );
  };
}
else {
  hasClass = function( elem, c ) {
    return classReg( c ).test( elem.className );
  };
  addClass = function( elem, c ) {
    if ( !hasClass( elem, c ) ) {
      elem.className = elem.className + ' ' + c;
    }
  };
  removeClass = function( elem, c ) {
    elem.className = elem.className.replace( classReg( c ), ' ' );
  };
}

function toggleClass( elem, c ) {
  var fn = hasClass( elem, c ) ? removeClass : addClass;
  fn( elem, c );
}

var classie = {
  // full names
  hasClass: hasClass,
  addClass: addClass,
  removeClass: removeClass,
  toggleClass: toggleClass,
  // short names
  has: hasClass,
  add: addClass,
  remove: removeClass,
  toggle: toggleClass
};

// transport
if ( typeof define === 'function' && define.amd ) {
  // AMD
  define( classie );
} else {
  // browser global
  window.classie = classie;
}

})( window );

//fake jQuery
var $ = function(selector){
  return document.querySelector(selector);
}
var accordion = $('.acc');

//add event listener to all anchor tags with accordion title class
accordion.addEventListener("click",function(e) {
  e.stopPropagation();
  e.preventDefault();
  if(e.target && e.target.nodeName == "A") {
    var classes = e.target.className.split(" ");
    if(classes) {
      for(var x = 0; x < classes.length; x++) {
        if(classes[x] == "acc_title") {
          var title = e.target;

          //next element sibling needs to be tested in IE8+ for any crashing problems
          var content = e.target.parentNode.nextElementSibling;

          //use classie to then toggle the active class which will then open and close the accordion

          classie.toggle(title, 'acc_title_active');
          //this is just here to allow a custom animation to treat the content
          if(classie.has(content, 'acc_panel_col')) {
            if(classie.has(content, 'anim_out')){
              classie.remove(content, 'anim_out');
            }
            classie.add(content, 'anim_in');

          }else{
             classie.remove(content, 'anim_in');
             classie.add(content, 'anim_out');
          }
          //remove or add the collapsed state
          classie.toggle(content, 'acc_panel_col');

        }
      }
    }

  }
});
</script>

A: Your code is execute before the DOM was loaded.
Check you HTML structure.
<!html>
<html>
  <head>
    <!-- Here your style, title, meta -->
    <!-- Here your JS library if need -->
  </head>
  <body>
  <!-- Here your html -->
  <!-- Here your JS code -->
  </body>
</html>

Try to encapsulate your JavaScript code in the DOM ready listner
<script>
  document.addEventListener('DOMContentLoaded', function(){
    // Here your JS code
  });
</script>

This event is fire when the DOM is ready to use.
Update Step2
As it write in your model. The A tag need to be inside the DT tag.


text:
Q: Design an op amp with gain of \$2\cdot V1+4\cdot V2-2\cdot V3-4\cdot V4\$ I was able to do the negative side of the op amp fairly easily, but I can't figure out how one would do the positive side.  Below is what the circuit looks like so far.

simulate this circuit – Schematic created using CircuitLab
Edit: Only one op amp can be used.

A: This is a summing amplifier problem. In the circuit shown, there should be a 400ohm resistor from the + input to ground to balance the feedback resistor, otherwise the currents don't add correctly.
The resistor ratios are OK, but the values should be MUCH higher, especially as a TL081 has a JFET input stage - otherwise the output is driving into a load of 400ohms. I suggest you use values of 10K, 20K and 40K.
Depending on the input voltages, you may need to look at the common mode range and/or the supply voltages - don't assume the opamp inputs are at ground, because in this circuit they ain't!

A: Better you can put the V1 and V2 in series with 200 Ohm and 100 Ohm respectively in the inverting side of the OP-AMP and connect to non-inverting terminal to GND. Only thing is that, the negative terminal of V1 and V2 must be towards the inverting terminal and their positive terminal be grounded so that you are feeding -V1 and -V2 which gets inverted and become +V1 and +V2

A: Ckt for the following question


text:
Q: socat two serial port together I am writing a JUnit test to test my application. The application is written in Java and uses the purejavacomm library. To test the serial parser I want to setup a virtual serial port so the test can communicate with the parser. In addition to simply parsing, it also dynamically connects to the serial port when it becomes available so I do not want to use, say a PipedInputStream.
This library only looks for device files that start with ttyS, ttyUSB, or ttyACM. Because of this, I cannot do the regular (which would produce serial ports in /dev/pts/x):
socat -d -d pty,raw,echo=0 pty,raw,echo=0

I tried doing:
socat /dev/ttyS20 /dev/ttyS21

but it doesn't work. It doesn't exit, or print an error. I tried connecting to /dev/ttyS20 with screen, but it just says, [screen is terminating].
I looked at the user permissions for ttyS20 (and 21), and they both have the group, dialout (user: root), which my user is in (chris).
Am I overlooking something with the permissions? Is there a better way to do this all together?

A: Then what I would suggest is to create a dev folder in your home directory and point the links there.
socat pty,raw,echo=0,link=/home/user/dev/ttyS20 pty,raw,echo=0,link=/home/user/dev/ttyS21

You should be able to access that without root.  If it is a unidirectional communication I usually like to add the -u option.

A: You will want to link the newly created ptys to another location
socat -u -u pty,raw,echo=0,link=/dev/ttyS20 pty,raw,echo=0,link=/dev/ttyS21

After you create the virtual ports with socat, try changing the ownership of both ends of the pipe to allow easier access.
sudo chown user:user /dev/ttyS20
sudo chown user:user /dev/ttyS21

You could also change the permissions with chmod to 777.


text:
Q: How to make a complete Iframe registration / login / userpanel So far i have such code
<form action="register.php" target="login" type=post>
  Account

   <input type=text id="name" name="account" size=20 maxlength=<?php Echo MaxNameLength; ?> />

  Password

   <input type=text id="name" name="password" size=20 maxlength=<?php Echo MaxNameLength; ?> />

  <button type=submit>Register</button>
</form>

I placed it inside an IFrame but when i try to use php with such code:
<?php
  If (IsSet($_GET["account"]["password"])) { $Account = $_GET["account"]; $Password = $_GET["password"];

$AllRight = True;

    For ($I=0; $I<StrLen(WrongChars); $I++) {
      If (StrPos($Account, SubStr(WrongChars,$I,1))) {
        Echo "
Your Name musn't contain the char \"".SubStr(WrongChars,$I,1)."\"
";
        $AllRight = False;
      }
    }
    If (file_exists(AccountFilesPath.$Account.AccountFilesEnding)) {
      Echo "
This Account already exists!
";
      $AllRight = False;
    }
    If ($AllRight) {
      $Text .= "$Password ";

      File_Put_Contents (AccountFilesPath.$Account.AccountFilesEnding, $Text);

      if(!file_exists(AccountFilesPath.$Account.AccountFilesEnding)) {
        echo "
Error during account cration!
";
      }

      Echo "
This Account is created succesfully!
";
    }
  }
?>

yet the responce im getting is a fresh registration page with no work done...
i want my iframe to individually register text files like (user1.txt) with ($Password) inside. Along with having a link to the login, and upon login have a User Control Panel.

A: I don't understand why you are using an iframe for this but I can see that you use $_GET in your php when your form submits $_POST (type="post")
Try changing that in your PHP code and see if it works
Edit*
As stated in the comments this is not a $_GET index $_GET["account"]["password"]
Let's say you stick with POST since your html form submits a POST,you must use something like this:
if(isset($_POST["account"]) && isset($_POST["password"]))

And to be sure what variables you get from your form, I recommend you to print your Post array before any manipulation.
print_r($_POST);


text:
Q: Get the name of a value from an array PHP here is a sample the array I have
Array ( [57] => 0 [58] => 0 [59] => 0 [60] => 0 [61] => 0 [62] => 0 [63] => 0

The value names are randomly generated I want to get the name of each pair out of the array and the value I can get the value using
foreach ($_POST as $songvalue) {
print $songvalue;

}
But how do I get the name of the value

A: If I understand correctly, with :
foreach ($_POST as $key=>$songvalue) {
    print $key;
}

A: foreach($_POST as $key => $value){
 //do thingies. $key is your key name
}

You are welcome :)

A: Use foreach($_POST as $key => $value)


text:
Q: How do search engines merge results from an inverted index? How do search engines merge results from an inverted index?
For example, if I searched for the inverted indexes of the words "dog" and "bat", there would be two huge lists of every document which contained one of the two words.
I doubt that a search engine walks through these lists, one document at a time, and tries to find matches with the results of the lists. What is done algorithmically to make this merging process blazing fast?

A: Since inverted indices are ordered by docId they can be merged very fast. [if one of the word starts at docId 23 and second at docId 100001, you can immediately fast forward to docId 100001 or higher in first list as well. ]
Since the typical document intersections are atmost few million they can be sorted for rank very fast. I searched for 'dog cat' [very common 2 words] which returned only 54 million hits.
Sorting of 10 millon random integers took only 2.3 seconds in my Mac with single threaded code [1 million took 206 ms!] and since we need to typically pick only the top 10 not even the full sort is required.
Here is the code if someone wants to try the speed of sort and too lazy to write code!
import java.lang.*;
import java.math.*;
import java.util.*;

public class SortTest {
   public static void main(String[] args) {
   int count = Integer.parseInt(args[0]);

Random random = new Random();
int[] values = new int[count];
int[] bogusValues = new int[100000]; //screw cache
    for(int i = 0; i < values.length;++i) {
    values[i] = random.nextInt(count);
}
for(int i = 0; i < bogusValues.length;++i) {
    bogusValues[i] = random.nextInt(count);
}
long start = System.currentTimeMillis();
System.out.println(start);
        Arrays.sort(values);
System.out.println(System.currentTimeMillis());
System.out.println(System.currentTimeMillis()-start);
    Arrays.sort(bogusValues);
 }

}

A: Actually search engines do merge these document lists. They gain good performance by using other techniques, the most important of which is pruning: for example, for every word the documents are stored in order of decreasing pagerank, and to get results that have a chance of getting into the first 10 (which will be shown to the user) you may traverse just a fairly small portion of the dog and bat lists, say, the first thousand. (and, of course, there's caching, but that's not related to the very query execution algorithm)
Besides, after all, there are not that many documents about dogs and about bats: even if it's millions, it turns into split seconds with a good implementation.

P.S. I worked at our country's leading search engine, however, not in the very engine of our flagship search product, but I talked to its developers and was surprised to know that query execution algorithms are actually fairly dumb: it turns out that one may squash a huge amount of computation into acceptable time bounds. It is all very optimized of course, but there's no magic and no miracles.


text:
Q: java security configuration for ssl I have the following question on SSL/TLS.
After the server hello, starts the authentication phase of the server.
From various articles/books, it appears that this phase is optional. E.g. in wiki

The server sends its Certificate
  message (depending on the selected
  cipher suite, this may be omitted by
  the server).

But I do not understand what it means to say that it depends on the encryption suite.
So my understanding is either a ServerKeyExchange or a Certificate follows a ServerHello.
So my question is, can the server authentication be omitted all together?
For example to omit client aunthentication in Tomcat, you just configure the connector to not request it.
How can the server authentication be omitted? Does it depend on the java framework I use, if it supports it?
And what does it mean to omit the server authentication? If the certificate is not send then the ServerKeyExchange becomes mandatory, or usually frameworks allow provisioning of a local public key instead if one wants to by pass-authentication phase for performance or because it does not make any sense?
Or does this depends on the encryption suite somehow, as wiki seems to imply?
NOTE:
I understand that server should always be authenticated. The context of my problem though is a client app and server running on the same machine (and java runtime I guess) so it can be considered safe to bypass server authentication (I think).
Any input is highly welcome!
Thanks!

A: In TLS/SSL, server authentication is optional.
If you choose TLS/SSL cipher suite without authn (such as TLS_NULL_WITH_NULL_NULL (turns off authn and encryption) or TLS_DH_anon_XXXX (use only encryption) in TLS specification), server certificate won't be sent.
TLS/SSL without authn doesn't seem to be supported pure-Java connector.
But I think the native-connector with SSLCipherSuite=aNULL supports it.
I don't know it's safe to disable authn, i.e., attacks such as DNS-spoofing might be threats.
I think you'd better to use server authn if performance is not problem.
Or, turning off TLS/SSL itself might be choice.  (Encrypting server-client communication might be meaningless because administrator of the computer can steal certificate files and dump JVM heap.)

A: Authentication and Encryption are important when data travels across an untrusted network or when one of the endpoints is not trusted.  If you application only makes connections on localhost, then Authentication and Encryption aren't important (the fact that your data and application are on locahost implies a trust in localhost).

A: you can get ssl configuration for tomcat 6 from
http://nayanmali.blogspot.com/
you got whole configuration and how to create keytool and how to generate certificate form that


text:
Q: to align rows fetched from shell script output The output from the shell scripts is like :
343434345,5454645645645,ACTIVE,2011-05-25 14:34;refid=134053
90092;pep.state=ACTIVATED
343434345,5454645645645,ACTIVE,2011-05-25 14:34;refid=134053
90092;pep.state=ACTIVATED

And it gets pasted in the editplus in identical manner.
But I want my output to be in complete line instead of two lines. Like :
343434345,5454645645645,ACTIVE,2011-05-25 14:34;refid=13405390092;pep.state=ACTIVATED
343434345,5454645645645,ACTIVE,2011-05-25 14:34;refid=13405390092;pep.state=ACTIVATED

P.S. Data been fetched from database.
How can that be possible ? Pls advise !

A: (g)awk to the rescue:
awk 'NR % 2 == 1 { saved_line=$0 ; next } { print saved_line $0 }' INPUTFILE

will do.
It will save every odd lines to a variable, then prints it and the next line. Note: it can be done more than one way, e.g. this does the same:
awk '{printf("%s",$0) ; getline ; printf("%s\n",$0)} INPUTFILE
HTH


text:
Q: C# async, Stop all tasks when one is finished without the access to the code I'm writing a small application that uses Provider Model pattern in .NET. Each provider has one method to implement in order to plug-in in my application.
I want to run all providers' specific work (the implemented method) in different threads BUT when one task is finished all other tasks need to stop executing.
I am using async/await model in .NET with CancellationToken for cancelling a task.
tasks.Add(Task.Run(() =>
                {
                        if (token.IsCancellationRequested)
                            token.ThrowIfCancellationRequested();

                        return provider.DoWork();

                }, token));

while (tasks.Count > 0)
        {
            var t = await Task.WhenAny(tasks);

            tasks.Remove(t);

            var result = await t;

            if (!string.IsNullOrEmpty(result))
            {
                tokenSource.Cancel();
                return result;
            }
        }

Some of the provider.DoWork() methods can be very slow and to stop the thread in which DoWork method executes I have to check token.IsCancellationRequested within DoWork method but I can't because the methods are written from somebody else, for example.
The check of token.IsCancellationRequested outside DoWork doesn't really matter in that case.
To sum up, when one task is finished, other tasks have to be stopped but without access to the code running in each thread.
Looking forward to hearing your thoughts about that.

A: There are a myriad of problems associated with abruptly terminating a thread in a process - essentially, that should only be done as a last resort when the process is so sickly that you're about to kill the entire thing anyway. Anything other than that, and you're at grave risk of causing significant problems if you interfere. So: that leaves graceful elective exit. You mention that you are already using cancellation tokens; really, that's all you can do (safely, at least). It is up to the different implementations to check for cancellation and exit. If you can't rely on the tasks periodically checking for cancellation: you are a bit stuck.
Basically, there is no easy answer to what you describe.

A: There are several different possible ways to stop arbitrary code, none of which are ideal.
First, you can approach this on a thread level. In other words, give each provider a separate thread and call Thread.Abort when you want it to stop. Unfortunately, there is a whole myriad of problems with this approach: two of the more well-known issues are a possibility of deadlock, and entering an odd state where a type can no longer be instantiated in your AppDomain. For this reason, Thread.Abort is considered "evil" and a definite code smell.
Moving one level higher, you can approach this on an AppDomain level. In this case, you give each provider a separate AppDomain. The advantage of this approach is that you can shut down an AppDomain more cleanly than you can a thread. Unfortunately, some things can still slip through the cracks: in particular, unmanaged resources can leak into your process from an AppDomain.
Which leaves you with the most reliable solution: approaching this on a process level. That is, you give each provider a separate process and use inter-process communication to control it. A process can be shut down cleanly, since the OS is responsible for cleaning up. Unfortunately, this approach has the most overhead and is the most difficult to program.
A robust hosting solution must support at least the last one. ASP.NET, for example, supports all three: request threads can be aborted in some situations (e.g., the client disconnects), the AppDomain can be recycled, and this be escalated to where the entire worker process is recycled. However, I recommend that you do not write your own hosting platform with escalation policies.
What I recommend is to 1) provide the CancellationToken to your providers and encourage them to use it, and 2) after you signal the token, just let them run to completion.


text:
Q: How to create route with hyphen from page name in nuxt I wanted to have route like privacy-policy or terms-condition in nuxt without having the page name likePrivacy-Policy or Terms-Condition . Is there a simple way to do that without customizing the route or  anything.

A: If you do have a page that is called BoringPage.vue but want something more fancy, you could write this
<router>
{
  alias: [
    '/cool-page',
  ]
}
</router>

<template>
...
</template>

and have access to the BoringPage via /cool-page.
All you need to do, is to install the router-extras module.

A: Create file _slug.vue in pages directory
<template>
  <h1>{{ this.slug }}</h1>
</template>

<script>
  export default {
    async asyncData({ params }) {
      const slug = params.slug // When calling /privacy-policy the slug will be "privacy-policy"
      return { slug }
    }
  }
</script>

Nuxt dynamic pages: https://nuxtjs.org/docs/2.x/directory-structure/pages#dynamic-pages


text:
Q: When using setTimeout do you have to clearTimeout? Someone told me that when you use setTimeout you must clear it with clearTimeout. I can understand before the timeout runs out, but why after? Or is it untrue?

A: You don't actually need to use clearTimeout, you only use it if you wish to cancel the timeout you already set before it happens.
It's usually more practical to use clearInterval with setInterval because setInterval usually runs indefinitely.

A: clearTimeout is only necessary for cancelling a timeout.  After the timeout fires, it can safely be left alone.  clearInterval is much more typically necessary to prevent it from continuing indefinitely.

A: No, setTimeout stops running after 1 call. In order to stop setInterval however, you must use clearInterval. If you create an endless loop of setTimeout then clearTimeout could be used.

A: No reason to clear it after it's completed. Your friend might have been confused with setInterval.

A: It's not true - there's no harm in clearing a timeout after it has finished, but it's not necessary.
Per the specification:

If handle does not identify an entry in the list of active timers of the WindowOrWorkerGlobalScope object on which [clearTimeout] was invoked, the method does nothing.

In other words, it's a no-op; nothing happens, and no error will be thrown.

A: It is always best practice to cleartimeout after using setTimeout.
let's take a scenario you are using setTimeout on /abc
page. and you set a time of 10s. and now you move to /something page before the timeout is completed(less than 10s). but setTimeout is still running so now you are on /something page and timeout ends the time and the callback function will run on /something page in the callback function, you might be using a window object which may affect your /something page and result in an error or unexpected result.
conclusion- always use cleartimeout to remove unexpected errors.
Please add your thoughts if I am wrong


text:
Q: Send file with flask and return a data without refreshing the html page I'm developing a web application that takes a grayscale input and return a colorized version of that image using machine learning. For that, the web app is with a python backend linking the front end html pages using the Flask microframework.
I'm sending the image I choose to process in python and then return the image name to display it from its directory. My question is how can I make the previous operations happen without reloading the html page?

A: I made a minimal working example, which does the exact thing you're asking:
from flask import Flask, render_template_string, request, jsonify, url_for
import os
from werkzeug.utils import secure_filename

if not os.path.isdir("/static"):  # just for this example
    os.makedirs("/static")

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        fname = secure_filename(file.filename)
        file.save('static/' + fname)
        # do the processing here and save the new file in static/
        fname_after_processing = fname
        return jsonify({'result_image_location': url_for('static', filename=fname_after_processing)})

    return render_template_string('''
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>title</title>

<form enctype="multipart/form-data" method="post" name="fileinfo">
  Some user provided information
  <input type="text" name="some_info" size="12" maxlength="32" />

  File to upload:
  <input type="file" name="file" required />
  <input type="submit" value="Upload the file!" />
</form>

''')

app.run()

I'm not checking for file extensions or overwriting files, so you should secure this feature quite a bit more. But the basic infrastructure is there.


text:
Q: Why does my computer power off suddenly and without warning? My computer is about 7 years old. Its has an Asus A7N266-VM motherboard and an AMD Athlon XP 2400+ CPU. My problem is that my computer suddenly and randomly switches off on its own. There is no blue screen, no error messages, the pc just goes off as though somebody pulled the plug. The motherboard power indicator LED remains ON. It might happen anytime from within 5-10 mins of starting up, to maybe an hour or two later. Sometimes it works perfectly fine and never turns off. And once it shuts itself off, i can't power it back on. If i press the power button to start the computer, it turns off again in about 2 seconds before even the POST can start. If i pull the plug and try again later or shake up the chassis a but and retry, it might boot up again and run for some random period of time before the same story repeats.
Another (maybe) related problem which i have been facing for a longer time is that my computer cannot be shutdown. After windows(xp) shows "Windows is shutting down..", the system powers off and promptly restarts. So all I can do is pull the plug at the right instant!
Any ideas/suggestions?

A: I think overheating is very likely, if as you say, it shuts down then doesn't turn on straight away(it could be cooling down). I have heard of that as a symptom or possible symptom of a system overheating and may have encountered it myself once or twice.  Typical candidate for overheating would be CPU.
Run speedfan, and see if you see a Temp go up and up and reach a certain point, then the computers shuts off!!
or touch the heatsink and see if it is too hot to touch.. ! (the inside of a computer won't kill you.. it's DC and not high voltage. Though many might turn a computer off before doing so.. it's fine.. i've done it!
You may want to take precautions for static. Some people worry about that.

A: If it is a old computer it might have lots of dust and cak inside the case, causing it to overheat. Take the case off and have a look, then give it a clean if need be.

A: If it's not heat, it may be a bad heat sensor. See if there's any log entries about why the box shuts down.
(I'd still go with replacing the PSU first though.)

A: Make sure the internal fan is working.  If its unable to dissipate the heat, the processor will overheat causing the computer to shutdown.

A: A LOT of cases of faulty RAM are mis-diagnosed as overheating, for instance - check that your RAM strips are clean, free from dust, and properly seated in their slots, and disable the "Fast Boot" option in your BIOS to see if any problems are reported at boot-up.
You can also run a Memory tester (I use http://www.memtest.org/).
On several occasions I have experienced, random reboots have been caused by the way XP handles serious system crashes - rebooting rather than displaying the BSOD (check Control Panel / System / Advanced / Startup And Recovery for the checkbox to disable this behaviour).
If you now experience BSOD messages rather than reboots, you now at least have more information to post regarding the problem :).

A: This sort of thing is hard to diagnose.  If shaking the case can temporarily fix it, it might be a bad cable, or a cable that isn't solidly plugged in.  The simplest, quickest thing to try is to unplug all the cables, clean the connectors with isopropyl alcohol and DRY THOROUGHLY, then plug them back in.  Do NOT unplug them all and clean them in a big batch unless you're an expert, because it's too easy to forget how to plug them back in. :)

A: That motherboard is known to be affected by the 'bad capacitors' issue so it may be that too.

A: I have experience with such a problem. My problem was the CPU overheating. When the CPU reaches a certain degree, the computer powers off immediately. Try checking the fan/cooler and the power supply.

A: Got another power supply you can swap in for testing?  If not debris in the case, could be a power supply failing.

A: Bad capacitors might be it for such and old motherboard. You can diagnose it by opening the case and looking at the capacitors, which might be bent from the top. You can see pictures from this wikipedia article.
If you are not electronics expert, I suggest that you buy a new motherboard.


text:
Q: TypeError: __new__() got an unexpected keyword argument 'deny_new' Yo tengo un bot de Discord en Python y funcionaba bien. Hoy me advirtieron de que no estaba encendido y al abrir la terminal de Python me encuentro con un error (habia corrido el codigo antes y andaba de maravilla). Al intentar reiniciar el bot salio el error de nuevo.
Este es el error:
TypeError: __new__() got an unexpected keyword argument 'deny_new'
Se que mi codigo no es, siempre corrio perfecto y no le hice ninguna modificacion.

A: Buenas me sucedió lo mismo justamente hace un momento, pruebe estos comandos los cuales me sirvieron para arreglar dicho error:

*

*apt-get update && apt-get upgrade

*python3 -m pip install -U discord.py

A: He encontrado una solucion, desinstala mediante pip discord.py y vuelve a instalarlo. Necesitas la versions 1.3.4 o superior para que funcione.


text:
Q: Viewing deleted files in Vault Is there a way to view the contents and history of deleted files in the SourceGear Vault Client?  The only way I have found is to undelete the file, view the file, and then delete the file again.
I'm currently using Vault 4.1.2.

A: To view the contents of a deleted file, you can Get an old version of the folder that contained the deleted file (before it was deleted) into an alternative directory. That will put a copy of the deleted file in that directory for you to examine.
As far as I know, there is no way to look at the history of a deleted file unless you undelete it.


text:
Q: How to calculate a Voltage divider's resistance values from a required current I have this exercise (not homework!) where I need to find at what point, using a pot, I will let enough current pass through a BJT base to let 70mA cross a relay's coil. I have trouble determining how to do this.

I know I first need to calculate the required BJT base current, which is 100 uA given that the transistor used in the exercise has a gain of 700.
Then, I am not sure how to use the variable voltage divider to determine the voltage at the BJT's base node, which will let me calculate the potentiometer's resistance at that point.
Can someone help me understand? Should I use KCL?
Thanks!

A: If you estimate the Hfe of the transistor as 100 then 70mA Ice requires 700uA Ibe.  Assuming that the Vbe drop will be about 700mV, the 200R resistor will draw 3.5mA and so the more positive part of the potential divider needs to supply 4.2mA.  It has a voltage drop of 11.3V (12 - 0.7) and so the resistance should be 2690R.  The Hfe of the transistor may be significantly different from this, but since the majority of the divider current flows through the 200R resistor, the circuit won't be particularly sensitive to the Hfe.


text:
Q: Type hinting a list of specific strings in Python I have a function as shown below:
from typing import List, Literal, Union

def foo(possible_values: List[Union[Literal['abcd', 'efgh', 'ijkl']]]):
    return {}

Now this is how I want the code to behave:
whenever the possible_values parameter gets values other than ["abcd", "efgh","ijkl"]
Eg:
res = foo(possible_values=["abc", "efgh"])

It should throw an error as abc is not defined in the function signature.
However,
res = foo(possible_values=["abcd", "efgh"])

should work fine as they are subset of what is defined.
Currently, with the above code, it just accepts any arbitrary list of strings.

A: If you want to constrain values to a predefined set, you might want to use Enum. Like mentioned by others, type hinting won't enforce check and error natively in python, you'll have to either implement it in your function's code, or use a library allowing annotation-based control. Here is an example.
from typing import List
from enum import Enum

# Let's define your possible values as an enumeration. Note that it also inherits from
# str, which will allow to use its members in comparisons as if they were strings
class PossibleValues(str, Enum):
    abcd = 'abcd'
    efgh = 'efgh'
    ijkl = 'ijkl'

Now your function. Note the type-hinting.
def foo(possible_values: List[PossibleValues]):
    # We unroll the enum as a set, and check that possible_values is a subset of it
    if not set(PossibleValues).issuperset(possible_values):
        raise ValueError(f'Only {[v.value for v in PossibleValues]} are allowed.')
    # Do whatever you need to do
    return {}

Now when you use it:
foo(['abcd', 'efgh'])
# output: {}
foo(['abc', 'efgh'])
# ValueError: Only ['abcd', 'efgh', 'ijkl'] are allowed.


text:
Q: floating point negative variable not setting to zero when assigned javascript I have created a button that should decrease the value in a given text field by units of 0.5, except when the field is empty or is 0. ie it should stay 0 on further clicks after it reaches 0 instead of going into negative values. But it still continues to go into negative values.
The function for this button is
function minusButton(n)
{
    var fieldname = "auc_dec"+n;
    //used to get id tag for element, is working fine in a separate plus button

    var entry = document.getElementById(fieldname).value;
    if(entry!='')
    {
        entry = Number(entry) - 0.5;
        document.getElementById(fieldname).value = entry;
    }
    else if(Number(entry)<0)
    {
        entry = "0";
        document.getElementById(fieldname).value = "0";
    }
}

A: Problem is because you've checked that if entry is not '' decrease it. So it is going to first if and entry getting decreased.
I got this working for me change your function accordingly
HTML:-
<input type="text" id="auto"/>
<button onclick="minusButton()">minusButton</button>

Javascript
function minusButton(){
  var entry = document.getElementById('auto').value;
  if(entry=='' || Number(entry)<=0)
  {
      entry = "0";
      document.getElementById('auto').value = "0";
      return;
  }
  entry = Number(entry) - 0.5;
  document.getElementById('auto').value = entry;
}

A: Try changing the if ... else statement to:
var entry =
document.getElementById(fieldname).value;

if (Number(entry) <= 0) {
entry = Number (entry);
document.getElementById(fieldname).value = entry;
} else  {
entry = Number (entry) - 1.5;
document.getElementById(fieldname).value = entry;
}

I'm not sure if this will work, but its worth a try...


text:
Q: Package in Java When do we actually use the package keyword? What does it mean?
Suppose I write the following code:
package masnun;
public class masnun{
    public static void main(String args[]) {
            System.out.println("Hello maSnun!");
        }

}

What does this package thing do? I get a masnun.class file that doesn't run. I am new to Java. Can somebody please explain?
Thanks

A: It's very likely for a software to have classes named Logger, Database, Connection, Table etc.
Packages separate the scope of these classes, so that you don't have issues with duplicate
classnames.
A few examples:

*

*java.*

*org.apache.**

*com.yourcompany.yourproject.

If you wan't to use classes from a destinct package you need to import them .i.g.
import java.util.Date

or
import java.sql.Date

A: It is such a way to organize your source files. A package contains multiple class file, a class file contains only a public class, a class contain multiple methods and variable.

A: The package statement in Java is used to group several related classes. If you have classes that deal exclusively with Database interaction, it would be logical to put them all under
com.example.myapp.persistence

This also provides the benefice of name spacing, remember that at runtime part of a java class identity is its fully qualified name, that is, the class name preceded by its package name like in
com.example.myapp.persistence.UserDAO

When you're application grows to accommodate more than a couple of classes, it is both practical and a good practice to organize them in packages

A: As I'm not a fan of these other answers, I'll write my own.

Real World Examples:
Think of a "package" as an easy way for a java class to reference another.
Let's say I have this big box in my attic. I have a calculator, compass, protractor, etc. I can label this box MathTools.
Another example would be taking all your pictures and putting them in the Pictures folder in your documents. From there, you could split them into Spring Break 2009 or [Insert Name Here]'s Party.
How does this relate to Java? Well, let's look at the java.util package (you can reference this with import java.util.*;. You have ArrayLists, Strings, Random, etc. which are used in most Java programs (common "utilities", if you prefer). There are all neatly organized into the same package, so that programmers can easily reference them (import java.util.*;).

Easy Application:
Let's assume that we can find all the files to a small dice simulator in C:/Program Files/Java Project/my/proj/ (it's likely that this file doesn't exist on your computer, but just pretend for a moment).
You have 3 files: Main.java, Dice.java, and DiceRoller.java. All of which are shown below:

"C:/ProgramFiles/Java Project/my/proj/main/Main.java":
package my.proj.main;

import my.proj.sims.Dice;

public class Main
{
    public static void main(String[] args)
    {
        DiceRoller roller = new DiceRoller();
        roller.rollAndShow(4);
    }
}

"C:/ProgramFiles/Java Project/my/proj/sims/Dice.java":
package my.proj.sims;

import java.util.Random; // I used the Random class, but you can also use the Math class if you prefer (java.lang.Math)

public class Dice
{
    public Dice()
    {
    }

    public int roll()
    {
        Random rand = new Random();
        return rand.nextInt(6) + 1; // Rolls a random number 1-6
    }
}

"C:/ProgramFiles/Java Project/my/proj/sims/DiceRoller.java":
package my.proj.sims;

public class DiceRoller
{
    public DiceRoller ()
    {
    }

    // Rolls and prints the result of 'n' number of rolls
    public void rollAndShow(int n)
    {
        Dice dice = new Dice();

        for (int i = 0; i < n; i++)
        {
            System.out.println(dice.roll()); // You should never use S.o.p in a method - it's bad practice, but it's easier this way if you don't yet understand the concept of objects
        }
    }
}

Things to notice:

*

*Main.java is packaged into my.proj.main

*Dice.java is packaged into my.proj.sims

*Main.java needs to import my.proj.sims.Dice in order to create a Dice object and use its methods because it's in a different package from Dice.java.

*DiceRoller.java does not need to import my.proj.sims.Dice because it is in the same package as Dice.java and the compiler will automatically associate the two.

Import is a command to load the functionality of a class into the current file. Look at Dice.java, for example. In order for it to create a Random object, which has the method nextInt(), it needs to import the Random class from the java.util.* package.

You might notice that some people would prefer to use java.util.* instead of java.util.Random, java.util.ArrayList, etc. What the * essentially means is any class within java.util. Running import java.util.* will import the Random, String, ArrayList, etc. classes.

A: "Packages are nothing more than the way we organize files into different directories according to their functionality, usability as well as category they should belong to." from: http://www.jarticles.com/package/package_eng.html
Basically,  in your example, you are saying class masnun is package of package masnun.  So essentially in other classes you could reference this class by import masnun;  Which imports the class masnun which resides in masnun package.

A: In Layman term, Lets suppose that there are multiple department in a college like science , arts etc. Now each department has some employee. In terms of object there can be multiple Employee class so there is restriction in java that we can't put two class as same name .So programmer should make different packages to store different class with same name in application.


text:
Q: IF and else if to paste data into three different sheets I am trying to copy rows onto three different sheets based on criteria in column AZ. I can get the first IF statement to work but the else ifs copy the information not in the first row of the designated sheet but where the previous sheet ended.
Here is what I have
Private Sub CommandButton1_Click()

Dim Cell As Range

With Sheets(2)

    For Each Cell In .Range("AZ2:AZ" & .Cells(.Rows.Count, "AZ").End(xlUp).Row)

        If Cell.Value = 1 Then
            .Rows(Cell.Row).Copy Destination:=Sheets("2X4").Rows(Cell.Row)
        ElseIf Cell.Value = 2 Then
            .Rows(Cell.Row).Copy Destination:=Sheets("2X6").Rows(Cell.Row)
        ElseIf Cell.Value = 3 Then
            .Rows(Cell.Row).Copy Destination:=Sheets("2X6H").Rows(Cell.Row)
        End If
   Next Cell
End With

End Sub

A: Picking up on @Marcucciboy2's comment you could use something like this.
Private Sub CommandButton1_Click()

Dim Cell As Range, v1, v2

v1 = Array("2X4", "2X6", "2X6H"): v2 = Array(2, 2, 2)

With Sheets(2)
    For Each Cell In .Range("AZ2:AZ" & .Cells(.Rows.Count, "AZ").End(xlUp).Row)
        If Cell.Value = 1 Or Cell.Value = 2 Or Cell.Value = 3 Then
            .Rows(Cell.Row).Copy Destination:=Sheets(v1(Cell.Value - 1)).Range("A" & v2(Cell.Value - 1))
            v2(Cell.Value - 1) = v2(Cell.Value - 1) + 1
        End If
    Next Cell
End With

End Sub


text:
Q: CircuiTikZ inductor style
Hello, friends, once more.
I guess this is an easy one for you, I would like to know how to get both styles for the inductor, like in the picture. I like both, but specially the first one. Thanks in advance.
I have not found this specific issue, I know the second one is gotten by [cute inductor] but not a clue about the first one.

A: You can specify the desired symbol via the options:

Code:
\documentclass{article}
\usepackage[american]{circuitikz}
\begin{document}
\begin{tikzpicture}
    \draw (0,0) to[cute inductor] (3,0) ;
    \node [below=5pt] at (1.5,0) {cute inductor};

    \draw (4,0) to[american inductor] (7,0) ;
    \node [below=5pt] at (5.5,0) {american inductor};
\end{tikzpicture}
\end{document}

A: I'm not sure if it helps, but here is a solution for the first symbol without circuitikz. I adjusted the symbol I normally use slightly to be able to let the semicircles go on for more than 180 degrees.
\documentclass[tikz]{standalone}

\tikzset{
    inductor/.style args={#1}{
        sloped,
        allow upside down,
        minimum height=4mm,
        minimum width=10mm,
        path picture={%
            \pgfmathsetmacro{\addangle}{#1}
            \pgfmathsetmacro{\radius}{.8/(2+6*cos(\addangle))}
            \draw[white] (-4.5mm,0) -- (4.5mm,0);
            \draw[line join=bevel] (-5mm,0)-- (-4mm,0)
                arc (180:-\addangle:\radius)
                arc (180+\addangle:-\addangle:\radius)
                arc (180+\addangle:-\addangle:\radius)
                arc (180+\addangle:0:\radius)
                -- (5mm,0);
        }
    },
    inductor/.default={40}
}

\begin{document}
    \begin{tikzpicture}
        \draw (0,0) -- node[inductor]{} ++(2,0) node[right]{\verb|inductor|};
        \draw (0,-1) -- node[inductor={0}]{} ++(2,0) node[right]{\verb|inductor={0}|};
    \end{tikzpicture}
\end{document}

This is the result:


text:
Q: Wix 3.5 - change/repair does not request elevation I'm having a strange problem with WIX: when I install/uninstall my package, the UAC is invoked correctly and everything works fine. However, when I go through change/repair scenarios, the installer does not request UAC Elevation and the machine-wide settings are not updated (just not changed; even the feature state remains the same next time I run the installer).
When I run the msiexec already elevated, everything works just fine.
the InstallScope is set to perMachine

A: If you launch from Programs and Features your install is automatically elevated. It sounds like your install is behaving correctly when done through Install but not Change. Check the verbose log to see the action states of your Components. Chances are the verbose log file will show differences.


text:
Q: How to change a macOS menubar icon? I'm trying to change a macOS menubar icon at the click of a button based on this question.
However, when I run the app and click the button, I get a Could not cast value of type 'SwiftUI.AppDelegate' (0x20dfafd68) to 'MenuBarTest.AppDelegate' (0x10442c580). error on this line:
let appDelegate = NSApplication.shared.delegate as! AppDelegate

Main Swift File
@main
struct MenuBarTestApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, NSApplicationDelegate {
    var statusItem: NSStatusItem?
    var popOver = NSPopover()

    func applicationDidFinishLaunching(_ notification: Notification) {
        let menuView = MenuBarView()

        popOver.behavior = .transient
        popOver.animates = true
        popOver.contentViewController = NSViewController()
        popOver.contentViewController?.view = NSHostingView(rootView: menuView)

        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

        if let MenuButton = statusItem?.button {
            MenuButton.image = NSImage(named: "settings_bw")
            MenuButton.image?.size = NSSize(width: 18.0, height: 18.0)
            MenuButton.action = #selector(MenuButtonToggle)
        }
    }

    func setIcon(colorType:String) {
        var icon = NSImage(named: "settings_color")

        if colorType != "color" {
            icon = NSImage(named: "settings_bw")
        }

        statusItem?.button?.image = icon
    }

    @objc
    func MenuButtonToggle(sender: AnyObject) {
        if popOver.isShown {
            popOver.performClose(sender)
        } else {
            if let MenuButton = statusItem?.button {
                self.popOver.show(relativeTo: MenuButton.bounds, of: MenuButton, preferredEdge: NSRectEdge.minY)
                popOver.contentViewController?.view.window?.makeKey()
            }
        }
    }
}

MenuBar View
struct MenuBarView: View {
    var body: some View {
        VStack {
            Button(action: {
                let appDelegate = NSApplication.shared.delegate as! AppDelegate
                appDelegate.setIcon(colorType: "color")
            }, label: {
                Text("Change Icon")
            })
        }
        .frame(width: 150, height: 100)
    }
}

A: First, I'll answer the question as asked, but then I'll follow up with why it actually doesn't matter because it's solving the wrong problem.
Accessing the App Delegate in a SwiftUI lifecycle app
When you're using SwiftUI to manage your app lifecycle, you don't use an app delegate directly. SwiftUI will set the application's app delegate to an instance of its own class, SwiftUI.AppDelegate. This is what you saw when trying to cast it to MenuBarTest.AppDelegate. You can't cast it to your class, because it's not an instance of your class.
As a backwards compatibility feature, SwiftUI's app delegate lets you provide your own delegate instance to that it will forward to. This is wired up with the NSApplicationDelegateAdaptor property wrapper. If you want to access an instance, that delegate instance property is the way to get at it (not NSApplication.shared.delegate).
Don't even use the App Delegate
You can disregard everything I said so far, because this is just a bad design, and you shouldn't use it. The App Delegate should be strictly limited to code related to managing the life cycle of your app and how it interacts with the system. It should not be a kitchen-junk-drawer of any code that fits.
Having random code right in the App Delegate is the AppKit equivalent to putting all your code in the main() function of a C program. It's done for brevity, but rarely a good idea. This is what you'll often see in tutorials, which aim to keep file and line count at a minimum, to illustrate some other point (e.g. Related to menu bar configuration, in this case).
As you'll notice, none of the code in this app delegate does much that's specific to the App life cycle. It just calls out to NSStatusBar. This code can just be put in any other appropriate place, like any other stateful SwiftUI code.


text:
Q: Why I can not call super in define_method with overloading method? When I run code below it raise error:

implicit argument passing of super from method defined by define_method() is not supported. Specify all arguments explicitly. (RuntimeError).

I am not sure what is the problem.
class Result
  def total(*scores)
    percentage_calculation(*scores)
  end

  private
  def percentage_calculation(*scores)
    puts "Calculation for #{scores.inspect}"
    scores.inject {|sum, n| sum + n } * (100.0/80.0)
  end
end

def mem_result(obj, method)
  anon = class << obj; self; end
  anon.class_eval do
    mem ||= {}
    define_method(method) do |*args|
      if mem.has_key?(args)
        mem[args]
      else
        mem[args] = super
      end
    end
  end
end

r = Result.new
mem_result(r, :total)

puts r.total(5,10,10,10,10,10,10,10)
puts r.total(5,10,10,10,10,10,10,10)
puts r.total(10,10,10,10,10,10,10,10)
puts r.total(10,10,10,10,10,10,10,10)

A: The error message is quite descriptive. You need to explicitly pass arguments to super when you call it inside of define_method block:
mem[args] = super(*args)