text:
Q: Rotate screen in mac os with terminal I want to rotate screen in mac os with the help of commands in terminal.I was able to do so in linux with xrandr commands but not in mac os.

A: I wrote a terminal util for macOS that lets you rotate, change resolution, and position monitors on macOS. When I switched from Linux to macOS I really missed XRandR.
displayplacer - also available via Homebrew brew tap jakehilborn/jakehilborn && brew install displayplacer

A: I think there's no built-in way to do this, but fb-rotate is a command line utility that should be able to do the job.


text:
Q: DeepEqual treats array initialized with back tick differently? My question is quite simple, I use back tick to initiate a string array, but I found that golang treats this array differently:
import (
    "fmt"
    "reflect"
)

func main() {
    x := []string{`hello world`, "me"}
    y := []string{"hello", "world", "me"}
    fmt.Println(x)
    fmt.Println(y)
    fmt.Println(reflect.DeepEqual(x, y))
}

The output is:
[hello world me]
[hello world me]
false

This makes me confused: should I make sure all string arrays are initiated in the same way?

A: Those are slices, not arrays, and your first slice has 2 elements, and the second has 3 elements, so how could they be equal?
Try printing them like this:
fmt.Printf("%d %q\n", len(x), x)
fmt.Printf("%d %q\n", len(y), y)

Output:
2 ["hello world" "me"]
3 ["hello" "world" "me"]

fmt.Prinln() will print all values of the passed slice, printing a space between elements. And first element of x is a string which equals to the first 2 elements of y joined with a space, that's why you see equal printed content for the slices.
When you use the same 3 strings to initialize your first slice with backticks, they will be equal:
x = []string{`hello`, `world`, "me"}
y = []string{"hello", "world", "me"}
fmt.Printf("%d %q\n", len(x), x)
fmt.Printf("%d %q\n", len(y), y)
fmt.Println(reflect.DeepEqual(x, y))

Output:
3 ["hello" "world" "me"]
3 ["hello" "world" "me"]
true

Try these on the Go Playground.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to always open PrimeNg's p-calendar on today's date ''I am using PrimeNg's calendar in my Angular Application.  I am using multiple selectionMode and binding the calendar to an array of dates from the database.  The calendar starts on the latest date in the range from the database but I want it to always start off with today's date and then the user can navigate backwards and forwards to see the previously selected dates from the database.  I set the defaultDate but it doesn't make any difference.
Please help.
Thanks,
my html:
<p-calendar [(ngModel)]="myDates" selectionMode="multiple" [inline]="inline" selectOtherMonths="true" [defaultDate]="defaultDate"></p-calendar>

my code:
public myDates: Date[] = [];
public defaultDate: Date = new Date();

constructor()
{
    this.myDates.push(new Date('01-01-2017'));
    this.myDates.push(new Date('01-02-2017'));
    this.myDates.push(new Date('01-07-2017'));
}

A: For me works!
In html
<p-calendar [(ngModel)]="date1"></p-calendar>

in TS
export class CalendarDemo {

    date1: string;

    ngOnInit() {
        let today = new Date();
        this.date1 = today.getMonth() + '/' + today.getDate() + '/' + today.getFullYear();
    }

}

A: HTML
[minDate]="minDateValue"
Ts
this.minDateValue = new Date();


text:
Q: Why does std::map not have an insert function of type insert(key &k, val &v) Why does std::map not support an insert like the following:
std::map<obj1, obj2> map_int;

void insert_map(obj1 &key, obj2 &val)
{
    map_int.insert(key, val);
}

I know that the above is incorrect. I want to know what prevents from designing the insert function like that. It is more intuitive than creating a pair IMO.

A: It's called emplace():

std::map<std::string, std::string> m;

// uses pair's template constructor
m.emplace("d", "ddd");

A: In C++17, you can use:
map_int.try_emplace(key, val);

This actually returns some useful information:
std::pair<std::map<obj1, obj2>::iterator, bool> p = map_int.try_emplace(key, val);

*

*p.first is an iterator that points to the element with the given key.

*p.second indicates whether the insertion took place.

You can achieve a similar effect in C++11 with map_int.emplace(key, val), but there are some subtle differences (related to copying/moving of values). Moreover, try_emplace allows for convenient construction of arbitrary elements:
struct X { X(int, char, bool); };

std::map<int, X> m;
m.try_emplace(10, 20, 'x', false);  // constructs X(20, 'x', false) if new

A similar operation in C++11 would look like this:
m.emplace(
    std::piecewise_construct,
    std::forward_as_tuple(10),
    std::forward_as_tuple(20, 'x', false));

A: std::map does have an insert() method (several, in fact), it just has a different signature than what you are expecting.  You need to pass it a std::pair containing the desired key and value, eg:
std::map<obj1, obj2> map_int;

void insert_map(obj1 &key, obj2 &val)
{
    map_int.insert(std::make_pair(key, val));
}


text:
Q: updating node to 8.1.4 fails heroku build I updated node v7.2.1 to v8.1.4. I got exceptions saying "Cannot find module 'async' and 'moment' after updating so I install them using npm install command (as suggested by stackoverflow thread".)
I tested the application everything seems working on my localhost but when i deployed it to Heroku it cause build failed with this error message.
-----> Node.js app detected
-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       NPM_CONFIG_PRODUCTION=true
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=true
-----> Installing binaries
       engines.node (package.json):  v8.1.4
       engines.npm (package.json):   unspecified (use default)

       Resolving node version v8.1.4 via semver.io...
       Downloading and installing node 8.1.4...
       Using default npm version: 5.0.3
-----> Restoring cache
       Skipping cache restore (new-signature)
-----> Building dependencies
       Installing node modules (package.json)

       > lwip@0.0.9 install /tmp/build_b8b26cc33675c474632f5536a0d0ddaf/RugCoPro-rugcopro-d2ada6e26415ce13c992c071360307b40214a4bc/node_modules/lwip
       > node-gyp rebuild

       make: Entering directory `/tmp/build_b8b26cc33675c474632f5536a0d0ddaf/RugCoPro-rugcopro-d2ada6e26415ce13c992c071360307b40214a4bc/node_modules/lwip/build'
       CXX(target) Release/obj.target/lwip_decoder/src/decoder/init.o
       CXX(target) Release/obj.target/lwip_decoder/src/decoder/util.o
       CXX(target) Release/obj.target/lwip_decoder/src/decoder/buffer_worker.o
       ../src/decoder/buffer_worker.cpp: In constructor 'DecodeBufferWorker::DecodeBufferWorker(Nan::Callback*, v8::Local<v8::Object>&, buf_dec_f_t)':
       ../src/decoder/buffer_worker.cpp:8:58: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       _height(0), _channels(0), _trans(false), _metadata("") {
       ^
       CXX(target) Release/obj.target/lwip_decoder/src/decoder/jpeg_decoder.o
       CXX(target) Release/obj.target/lwip_decoder/src/decoder/png_decoder.o
       CXX(target) Release/obj.target/lwip_decoder/src/decoder/gif_decoder.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jmemnobs.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jcomapi.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdapimin.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdapistd.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdatadst.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdatasrc.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdcoefct.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdcolor.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jddctmgr.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdhuff.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdinput.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdmainct.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdmarker.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdmaster.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdpostct.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdsample.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jerror.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jfdctflt.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jfdctfst.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jfdctint.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jidctflt.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jidctfst.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jidctint.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jutils.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jmemmgr.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdarith.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jdmerge.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jaricom.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jquant1.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/jpeg/jquant2.o
       CC(target) Release/obj.target/lwip_decoder/src/lib/png/png.o
       In file included from ../src/lib/png/png.c:14:0:
       ../src/lib/png/pngpriv.h:805:4: error: #error ZLIB_VERNUM != PNG_ZLIB_VERNUM "-I (include path) error: see the notes in pngpriv.h"
       #  error ZLIB_VERNUM != PNG_ZLIB_VERNUM     ^
       make: *** [Release/obj.target/lwip_decoder/src/lib/png/png.o] Error 1
       make: Leaving directory `/tmp/build_b8b26cc33675c474632f5536a0d0ddaf/RugCoPro-rugcopro-d2ada6e26415ce13c992c071360307b40214a4bc/node_modules/lwip/build'
       gyp ERR! build error
       gyp ERR! stack Error: `make` failed with exit code: 2
       gyp ERR! stack     at ChildProcess.onExit (/tmp/build_b8b26cc33675c474632f5536a0d0ddaf/RugCoPro-rugcopro-d2ada6e26415ce13c992c071360307b40214a4bc/.heroku/node/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:258:23)
       gyp ERR! stack     at emitTwo (events.js:125:13)
       gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
       gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:197:12)
       gyp ERR! System Linux 3.13.0-123-generic
       gyp ERR! command "/tmp/build_b8b26cc33675c474632f5536a0d0ddaf/RugCoPro-rugcopro-d2ada6e26415ce13c992c071360307b40214a4bc/.heroku/node/bin/node" "/tmp/build_b8b26cc33675c474632f5536a0d0ddaf/RugCoPro-rugcopro-d2ada6e26415ce13c992c071360307b40214a4bc/.heroku/node/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
       gyp ERR! cwd /tmp/build_b8b26cc33675c474632f5536a0d0ddaf/RugCoPro-rugcopro-d2ada6e26415ce13c992c071360307b40214a4bc/node_modules/lwip
       gyp ERR! node -v v8.1.4
       gyp ERR! node-gyp -v v3.6.2
       gyp ERR! not ok
       npm ERR! code ELIFECYCLE
       npm ERR! errno 1
       npm ERR! lwip@0.0.9 install: `node-gyp rebuild`
       npm ERR! Exit status 1
       npm ERR!
       npm ERR! Failed at the lwip@0.0.9 install script.
       npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

       npm ERR! A complete log of this run can be found in:
       npm ERR!     /app/.npm/_logs/2017-07-13T16_28_01_508Z-debug.log
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       If you're stuck, please submit a ticket so we can help:
       https://help.heroku.com/

       Love,
       Heroku
         !     Push rejected, failed to compile Node.js app.  !     Push failed

I am new in it so could anyone let me know what could be the issue?
Thank you very much.

A: From the build log it looks like a problem with installing lwip package,. This is a know issue documented on Github.
Looks like there is no official solution yet, but there are many workarounds proposed. One is to use patched lwip package containing updated libpng and zlib dependencies. In your package.json you need to put
"lwip": "https://github.com/Pajk/lwip#development"

You should check the discussion on Github, maybe other workaround will work for you.


text:
Q: Check if Visual C++ 2010 is installed - No Work For my program, I want it to check if Visual C++ is already installed and from a little bit of Googling, I can check if they are installed by checking the registry key as stated here:
http://blogs.msdn.com/b/astebner/archive/2010/05/05/10008146.aspx
The thing is, when I actually run the program, nothing happens. I tried running it as an Admin, nothing still happens. Here is my code:
Imports Microsoft.Win32

Public Class Form1
    Public Sub Form1_Load()
        Dim regKey As RegistryKey
        regKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\VisualStudio\10.0\VC\VCRedist\x64", True)
        If Not regKey Is Nothing Then
            MsgBox("Found")
        Else
            MsgBox("Not Found")
        End If
    End Sub
End Class

Im not sure if either im typing it right or what is the problem.

A: According to the MSDN link you should be reading from the Local Machine key, not the Current User key:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\10.0\VC\VCRedist\x64]

You should try changing the regKey line in your code as follows:
regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE...
' change this --> ^^^^^^^^^^^^

EDIT - regarding your form not doing anything: Your Form1_Load function is never being called because it doesn't have the right signature. Change your Form1_Load function signature to this:
Protected Overrides Sub OnLoad(e As EventArgs)
    Dim regKey As RegistryKey
    ...

You might have to run Visual Studio as an admin to be able to read the registry from the Local Machine key.


text:
Q: What is \363\353\377\377\377\177? (gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"

It doesn't look like ascii nor multibyte,what's that?

A: It's not text. It looks like the address you're examining contains another pointer to something on the stack. Try it as (char **)0x7fffffffe9c8, or some other double pointer type.
Edit: To elaborate, OP is examining non-text data in a debugger and asking the encoding. The correct answer is simply that it's not text. It's an integer 0x7fffffffebf3 and it's almost certainly a pointer to a string (since it's not aligned and points somewhere on the stack), meaning that the original pointer was probably of type char ** not char *.

A: These are octal character escapes. They are usually used to insert bytes into a string that don't have a meaning as text or need to have a certain binary value. \377 for instance is the hexadecimal value ff or decimal 255 which would be this ÿ in ASCII but most likely has a very different meaning in this context.

A: The part that you asked can be the shell code to that address.

A: try p/x
This should print value in hexa decimal format


text:
Q: Subproperties in SPARQL query I have this wikidata query, that tries to find all the companies owned directly or indirectly by the Walt Disney company.
SELECT ?company ?companyLabel WHERE {
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  ?company (wdt:P127|wdt:P749)* wd:Q7414.
  ?company wdt:P31/wdt:P279* wd:Q4830453.
}

I'm trying to find if company is owned by Disney (P127) or where Disney is the parent organization (P749).
Property P749 is a subproperty of P127. There may be other subproperties of "owned by" that I don't know about.
Can I make a query that returns all companies that has relation that has any subproperty of "owned by" in relation to Disney? I also need to return the subsidiaries of the direct subsidiaries, and the subsidiaries of those subsidiaries and so on.

A: You can do this by means of a recursive property path:
?company ?p wd:Q7414.
?p rdfs:subPropertyOf* P:127 .


text:
Q: How to use OR in regular expressions I have some strings like "abc", "def", "xyz" and they may be followed by numbers.
For example:
abc123 or xyz92
If I use:
re.findall("abc|def|xyz[0-9]+",text)

then it will only return xyz followed by digits, for the rest I only get the strings.
How to match all of them without doing it manually like:
re.findall("abc[0-9]+|def[0-9]+|xyz[0-9]+",text)

A: Use parenthesis, along with ?: to create a non-capturing group:
(?:abc|def|xyz)[0-9]+

Debuggex Demo
Further, if it is possible that your strings will not be followed by numbers, you should use * (0 or more), instead of + (1 or more). This way abc and abc123 will both match:
(?:abc|def|xyz)[0-9]*

Debuggex Demo
This is your current regex:
abc|def|xyz[0-9]+

Debuggex Demo


text:
Q: Using a Combination of Wildcards and Stemming I'm using a snowball analyzer to stem the titles of multiple documents. Everything works well, but their are some quirks.
Example:
A search for "valv", "valve", or "valves" returns the same number of results. This makes sense since the snowball analyzer reduces everything down to "valv".
I run into problems when using a wildcard. A search for "valve*" or "valves*" does not return any results. Searching for "valv*" works as expected.
I understand why this is happening, but I don't know how to fix it.
I thought about writing an analyzer that stores the stemmed and non-stemmed tokens. Basically applying two analyzers and combining the two token streams. But I'm not sure if this is a practical solution.
I also thought about using the AnalyzingQueryParser, but I don't know how to apply this to a multifield query. Also, the using AnalyzingQueryParser would return results for "valve" when searching for "valves*" and that's not the expected behavior.
Is there a "preferred" way of utilizing both wildcards and stemming algorithms?

A: This is the simplest solution and it would work -
Add solr.KeywordRepeatFilterFactory in your 'index' analyser.
http://lucene.apache.org/core/4_8_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilterFactory.html
Also add RemoveDuplicatesTokenFilterFactory at the end of the 'index' analyzer
Now in your index you will always have the stemmed and the non stemmed form for each token on the same position and you are good to go.

A: I used 2 different approach to solve this before

*

*Use two fields, one that contain stemmed terms, the other one containing terms generated by say, the StandardAnalyzer. When you parse the search query if its a wildcard search in the "standard" field, if not use the field with stemmed terms. This may be harder to use if you have the user input their queries directly in the Lucene's QueryParser.

*Write a custom analyzer and index overlapping tokens. It basically consist of indexing the original term and the stem at the same position in the index using the PositionIncrementAttribute. You can look into SynonymFilter to get some example of how to use the PositionIncrementAttribute correctly.
I Prefer solution #2.

A: I don't think that there is an easy(and correct) way to do this.
My solution would be writing a custom query parser that finds the longest string common to the terms in the index and to your search criteria.
class MyQueryParser : Lucene.Net.QueryParsers.QueryParser
{
    IndexReader _reader;
    Analyzer _analyzer;

    public MyQueryParser(string field, Analyzer analyzer,IndexReader indexReader) : base(field, analyzer)
    {
        _analyzer = analyzer;
        _reader = indexReader;
    }

    public override Query GetPrefixQuery(string field, string termStr)
    {
        for(string longestStr = termStr; longestStr.Length>2; longestStr = longestStr.Substring(0,longestStr.Length-1))
        {
            TermEnum te = _reader.Terms(new Term(field, longestStr));
            Term term = te.Term();
            te.Close();
            if (term != null && term.Field() == field && term.Text().StartsWith(longestStr))
            {
                return base.GetPrefixQuery(field, longestStr);
            }
        }

        return base.GetPrefixQuery(field, termStr);
    }
}

you can also try to call your analyzer in GetPrefixQuery which is not called for PrefixQuerys
TokenStream ts = _analyzer.TokenStream(field, new StringReader(termStr));
Lucene.Net.Analysis.Token token = ts.Next();
var termstring = token.TermText();
ts.Close();
return base.GetPrefixQuery(field, termstring);

But, be aware that you can always find a case where the returned results are not correct. This is why Lucene doesn't take analyzers into account when using wildcards.

A: The only potential idea I have beyond the other answers is to use the dismax against the two fields, so you can just set the relative weights of the two fields.  The only caveat is that some versions of dismax didn't handle wildcards, and some parsers are Solr specific.


text:
Q: JQuery script to total values from input boxes, checkboxes and option values from select element I'm trying to write what I think must be a simple JQuery script to display a running sum total of options selected by a user in an order form.  I have assigned values to all the checkboxes, radio buttons and option values from my drop downs and now want to display the sum total in a div so a user can see the total.
Here is my pathetic first attempt.  It doesn't work and I'm not surprised... just can't quite get my around why.

Here is the updated form code:

$(document).ready(function() {
    var baseWarranty = $("input.basewarranty").val();
    var multiFlat = $("option.multiflat").toarray[];
    var multiyr = $("option.multiyr").toarray[];
    var newConst = $("option.newconst").toarray[];
    var warrantyOptions = $("input.warrantyoptions").toarray[];
    var optionsChecked = $(baseWarranty: selected, multiFlat: selected, multiyr: selected, newConst: selected, warrantyOptions: checked).val();
    $(baseWarranty, multiFlat, multiyr, newConst, warrantyOptions).change(function() {
      if (optionsChecked) {
        $("#wty_option_child2").append(optionsChecked);
      }
    });
  }
});

      Closing Date

      <input type="date" id="closingdate" name="closingdate" required>

      Type of Home

      <input type="radio" id="Single Family" name="hometype" value="singlefamily" required>Single Family

      <input type="radio" id="Townhome/Condo/Mobile Home" name="hometype" value="towncondomobile">Townhome/Condo/Mobile Home

      <select form="input_form" name="multitype" id="duplex_triplex_fourplex" value="Multi-Flat Warranty Options" class="selectboxes">
        <option class="multiflat" value="" selected disabled hidden>Duplex/Triplex/Fourplex</option>
        <option class="multiflat" value="duplex_gold">Duplex Gold - $720</option>
        <option class="multiflat" value="duplex_platinum">Duplex Platinum - $855</option>
        <option class="multiflat" value="duplex_diamond">Duplex Diamond - $945</option>
        <option class="multiflat" value="triplex_gold">Triplex Gold - $1040</option>
        <option class="multiflat" value="triplex_platinum">Triplex Platinum - $1235</option>
        <option class="multiflat" value="triplex_gold">Triplex Diamond - $1365</option>
        <option class="multiflat" value="triplex_gold">Fourplex Gold - $1360</option>
        <option class="multiflat" value="triplex_platinum">Fourplex Platinum - $1615</option>
        <option class="multiflat" value="triplex_gold">Fourplex Diamond - $1785</option>
      </select>

      Select Warranty Type

      <input class="basewarranty" type="radio" id="Gold" name="warrantytype" value="400" required>Gold - $400

      <input class="basewarranty" type="radio" id="Platinum" name="warrantytype" value="475">Platinum - $475

      <input class="basewarranty" type="radio" id="Diamond" name="warrantytype" value="525">Diamond - $525

      <input class="basewarranty" type="radio" id="Sellers" name="warrantytype" value="Sellers">Sellers Warranty - $0

      <select form="input_form" name="multiyear" id="multiyear" value="Multi Year Warranties" class="selectboxes">
        <option class="multiyr" value="0" selected disabled hidden>Multi-Year Warranties</option>
        <option class="multiyr" value="760" id="2yr_Gold">2yr. Gold Warranty - $760</option>
        <option class="multiyr" value="1120" id="3yr_Gold">3yr. Gold Warranty - $1120</option>
        <option class="multiyr" value="903" id="2yr_Platinum">2yr. Platinum Warranty - $903</option>
        <option class="multiyr" value="1330" id="3yr_Platinum">3yr. Platinum Warranty - $1330</option>
        <option class="multiyr" value="998" id="2yr_Diamond">2yr. Diamond Warranty - $998</option>
        <option class="multiyr" value="1470" id="3yr_Diamond">3yr. Diamond Warranty - $1470</option>
      </select>
      <select form="input_form" name="newconstruction" id="newconstruction" value="New Construction Warranties" class="selectboxes">
        <option class="newconst" value="" selected disabled hidden>New Construction Warranties</option>
        <option class="newconst" value="400" id="2yr_nc_gold">2yr. Gold New Constr. - $400</option>
        <option class="newconst" value="520" id "3yr_nc_gold">3yr. Gold New Constr. - $520</option>
        <option class="newconst" value="660" id="4yr_nc_gold">4yr. Gold New Cons"tr. - $660</option>
        <option class="newconst" value="475" id="2yr_nc_plat">2yr. Platinum New Constr. - $475</option>
        <option class="newconst" value="618" id="3yr_nc_plat">3yr. Platinum New Constr. - $618</option>
        <option class="newconst" value="784" id="4yr_nc_plat">4yr. Platinum New Constr. - $784</option>
        <option class="newconst" value="525" id="2yr_nc_diam">2yr. Diamond New Constr. - $525</option>
        <option class="newconst" value="683" id="3yr_nc_diam">3yr. Diamond New Constr. - $683</option>
        <option class="newconst" value="866" id="4yr_nc_diam">4yr. Diamond New Constr. - $866</option>
      </select>

Warranty Notes - Any instructions or information about the order or payment arrangements

<input type="text" id="notes" name="warrantynotes">

Options

    <input class="warrantyoptions" type="checkbox" id="greenplus" name="optiontype[]" value="70">$70 Green Plus

    <input class="warrantyoptions" type="checkbox" id="termite" name="optiontype[]" value="75">$75 Subterranean Termite Treatment

    <input class="warrantyoptions" type="checkbox" id="freezer" name="optiontype[]" value="50">$50 Freezer-Standalone

    <input class="warrantyoptions" type="checkbox" id="wetbar" name="optiontype[]" value="25">$25 Wet Bar Refrigerator/2nd Fridge

    <input class="warrantyoptions" type="checkbox" id="poolspa" name="optiontype[]" value="150">$150 Pool/Spa Combo

    <input class="warrantyoptions" type="checkbox" id="addpoolspa" name="optiontype[]" value="150">$150 Additional Pool or Spa

    <input class="warrantyoptions" type="checkbox" id="saltpool" name="optiontype[]" value="300">$300 Salt Water Pool w/Spa Combo

    <input class="warrantyoptions" type="checkbox" id="wellpump" name="optiontype[]" value="100">$100 Well Pump

    <input class="warrantyoptions" type="checkbox" id="septicpump" name="optiontype[]" value="75">$75 Septic /Ejector Pump/Tank Pumping

    <input class="warrantyoptions" type="checkbox" id="waterline" name="optiontype[]" value="90">$90 External Water Line Repair

    <input class="warrantyoptions" type="checkbox" id="waterlineandsewer" name="optiontype[]" value="195">$195 External Water/Sewer Line Repair

Warranty Total:

A: Have a look at this
It was NOT trivial. Especially not after I noticed the jQuery

const getCheckedValue = fld => {
  let val = $("option:checked",fld).text();
  if (val) val = val.split("- $")[1]
  return isNaN(val) ? 0 : +val;
}

$("#input_form").on("input",function(e) {
  const dtf = getCheckedValue("#duplex_triplex_fourplex");
  const multiyear = getCheckedValue("#multiyear");
  const newconstruction = getCheckedValue("#newconstruction");

  const $warrentyField = $("[name=warrantytype]:checked");
  const warrenty = $warrentyField.length>0 ? +$warrentyField.val() : 0;

  const optiontypes = $("[name^=optiontype]:checked")
  .map(function() { return isNaN(this.value) ? 0 : +this.value })
  .get();
  const optionType = optiontypes.length>0 ? optiontypes.reduce((a,b) => a+b) : 0;

//  console.log(dtf,warrenty,multiyear,newconstruction,optionType)
  $("#total").text(dtf+warrenty+multiyear+newconstruction+optionType);
})

<form class="input-form" name="textinput" id="input_form" method="POST">

              Closing Date

              <input type="date" id="closingdate" name="closingdate" required>

              Type of Home

              <input type="radio" id="Single Family" name="hometype" value="singlefamily" required>Single Family

              <input type="radio" id="Townhome/Condo/Mobile Home" name="hometype" value="towncondomobile">Townhome/Condo/Mobile Home

              <select form="input_form" name="multitype" id="duplex_triplex_fourplex" value="Multi-Flat Warranty Options" class="selectboxes">
                <option value="0" selected disabled hidden>Duplex/Triplex/Fourplex</option>
                <option value="duplex_gold">Duplex Gold - $720</option>
                <option value="duplex_platinum">Duplex Platinum - $855</option>
                <option value="duplex_diamond">Duplex Diamond - $945</option>
                <option value="triplex_gold">Triplex Gold - $1040</option>
                <option value="triplex_platinum">Triplex Platinum - $1235</option>
                <option value="triplex_gold">Triplex Diamond - $1365</option>
                <option value="triplex_gold">Fourplex Gold - $1360</option>
                <option value="triplex_platinum">Fourplex Platinum - $1615</option>
                <option value="triplex_gold">Fourplex Diamond - $1785</option>
              </select>

              Select Warranty Type

              <input type="radio" id="Gold" name="warrantytype" value="400" required>Gold - $400

              <input type="radio" id="Platinum" name="warrantytype" value="475">Platinum - $475

              <input type="radio" id="Diamond" name="warrantytype" value="525">Diamond - $525

              <input type="radio" id="Sellers" name="warrantytype" value="Sellers">Sellers Warranty - $0

              <select form="input_form" name="multiyear" id="multiyear" value="Multi Year Warranties" class="selectboxes">
                <option value="0" selected disabled hidden>Multi-Year Warranties</option>
                <option value="760" id="2yr_Gold">2yr. Gold Warranty - $760</option>
                <option value="1120" id="3yr_Gold">3yr. Gold Warranty - $1120</option>
                <option value="903" id="2yr_Platinum">2yr. Platinum Warranty - $903</option>
                <option value="1330" id="3yr_Platinum">3yr. Platinum Warranty - $1330</option>
                <option value="998" id="2yr_Diamond">2yr. Diamond Warranty - $998</option>
                <option value="1470" id="3yr_Diamond">3yr. Diamond Warranty - $1470</option>
              </select>
              <select form="input_form" name="newconstruction" id="newconstruction" value="New Construction Warranties" class="selectboxes">
                <option value="0" selected disabled hidden>New Construction Warranties</option>
                <option value="400" id="2yr_nc_gold">2yr. Gold New Constr. - $400</option>
                <option value="520" id "3yr_nc_gold">3yr. Gold New Constr. - $520</option>
                <option value="660" id="4yr_nc_gold">4yr. Gold New Cons"tr. - $660</option>
                <option value="475" id="2yr_nc_plat">2yr. Platinum New Constr. - $475</option>
                <option value="618" id="3yr_nc_plat">3yr. Platinum New Constr. - $618</option>
                <option value="784" id="4yr_nc_plat">4yr. Platinum New Constr. - $784</option>
                <option value="525" id="2yr_nc_diam">2yr. Diamond New Constr. - $525</option>
                <option value="683" id="3yr_nc_diam">3yr. Diamond New Constr. - $683</option>
                <option value="866" id="4yr_nc_diam">4yr. Diamond New Constr. - $866</option>
              </select>

        Warranty Notes - Any instructions or information about the order or payment arrangements

        <input type="text" id="notes" name="warrantynotes">

        Options

            <input type="checkbox" id="greenplus" name="optiontype[]" value="70">$70 Green Plus

            <input type="checkbox" id="termite" name="optiontype[]" value="75">$75 Subterranean Termite Treatment

            <input type="checkbox" id="freezer" name="optiontype[]" value="50">$50 Freezer-Standalone

            <input type="checkbox" id="wetbar" name="optiontype[]" value="25">$25 Wet Bar Refrigerator/2nd Fridge

            <input type="checkbox" id="poolspa" name="optiontype[]" value="150">$150 Pool/Spa Combo

            <input type="checkbox" id="addpoolspa" name="optiontype[]" value="150">$150 Additional Pool or Spa

            <input type="checkbox" id="saltpool" name="optiontype[]" value="300">$300 Salt Water Pool w/Spa Combo

            <input type="checkbox" id="wellpump" name="optiontype[]" value="100">$100 Well Pump

            <input type="checkbox" id="septicpump" name="optiontype[]" value="75">$75 Septic /Ejector Pump/Tank Pumping

            <input type="checkbox" id="waterline" name="optiontype[]" value="90">$90 External Water Line Repair

            <input type="checkbox" id="waterlineandsewer" name="optiontype[]" value="195">$195 External Water/Sewer Line Repair

Warranty Total:

</form>


text:
Q: How do I use ajax to auto refresh a section of page without manually invoking a function within javascript?
var xmlhttp;

//Set up ajax first so he knows which guy to play with
function loadXMLDoc(url,cfunc)
{
    //Code to catch modern browsers
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }

    //Code to catch crap browsers
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    //Set up
    xmlhttp.onreadystatechange=cfunc;
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
}

//Set a function to deploy when something calls myFunction()
function myFunction()
{
    loadXMLDoc("../../../support/ajaxTest.txt",function()
    {
        //Fires off when button pressed
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("statusRefresh").innerHTML=xmlhttp.responseText;
            setInterval( "alert('Hello I did something but i needed to be invoked by a button first')", 5000 );
        }

    });
}

I want to call restful java service to refresh a 'status'. I need ajax to auto refresh the this status once the page has been hit. The Refresh method isnt instantaneous, for it has to talk with other machines.

A: function autoRefresh()
{
    var url    = "../../../support/ajaxTest.txt";
    var target = document.getElementById("statusRefresh");

    var doRefresh = function()
    {
        loadXMLDoc(url, function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                target.innerHTML=xmlhttp.responseText;
            }
        }
    });

    setInterval( doRefresh, 5000 );
}

and
document.onload = autoRefresh;

A: more information is needed such as what is your goal, what do you currently have......what are you trying to do......If its a script thats triggered by something from example a user viewing your page or click a button then use that button to triiger the function to auto refresh
Another way is to use a crob job


text:
Q: Is there any way to define controllers in gate definitions? I am setting up a new project and I want to use gates and policies. I know how to use it by Laravel documentation but I want to go furthermore.
We have a boot method in AuthServiceProvider where we should define gates and policies.
Can we define controllers in gates something like this?
Gate::define(SomeController::class, function ($user) {
   if($user->something) {
     return false;
   }
   return true;
});

A: If you want to protect specific routes (prevent unauthorized users from hitting your controllers), middleware is your best option. Gates/Policies are there to protect models/actions.
<?php

namespace App\Http\Middleware;

use Closure;

class MyCustomMiddleware
{
    public function handle($request, Closure $next)
    {
        if($request->user->something) {
            return false;
       }

       return true;
    }
}

More details on how to create and register middleware here:
https://laravel.com/docs/5.8/middleware


text:
Q: Splash screen with circular progress bar I'm applying the splash screen as a style that is executed by AndroidManifest and is changed by main activity before loading the first layout. So the splash screen style loads the following layer-list:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
            android:opacity="opaque"
            android:layout_height="match_parent"
            android:layout_width="match_parent">

    <!-- The background color, preferably the same as your normal theme -->
    <item android:drawable="@color/PrimaryDarkColor"/>

    <!-- Your product logo - 144dp color version of your app icon -->
    <item>
        <bitmap
            android:src="@drawable/splash"
            android:id="@+id/splash"
            android:gravity="center"/>
    </item>

</layer-list>

I would like to add an circular progress bar under the bitmap. I tried to follow differents tutorial but I don't have a xml where set progressbar before main activity starts.
Could you help me ?


text:
Q: Is "freaking" considered at least a little offensive? Check out this video
There the red hair women(Aubrey) asked about how many "freaking" kids does another women(Teresa) have? Is it just an offensive way for someone to use "freaking" when they are talking about someone kids? I found no resentment after the question is asked, and i don't know if i am too sensitive.
edit:updated the link

A: Some words are taboo; we sometimes refer to them with names like "the F-word" or "the A-word", or even (oh, my!) "the C-word", because we know that they have some potential for offense regardless of context, and if we're polite, we want to avoid violating the taboo ourselves.
Fricking ranks much lower on the profanity scale.  It's not really polite, and it can certainly be used in a rude manner, but it lacks most of the built-in potential for offense that makes us avoid saying certain other words.  I imagine that for most speakers, whether or not it's offensive depends on context.
In this case, the speaker doesn't intend any offense, and none is taken.  Quite the opposite!  From her tone of voice and the context of her words, it seems that the speaker is using emphatic swearing:

Here's the thing about Teresa: she has amazing heart, she does give a hundred and ten percent, she has--I don't even know, how many fricking kids do you have?

The idiomatic phrase I don't even know as well as fricking both serve to emphasize the question.  She may or may not remember the exactly how many children Teresa has, but the way she phrases her question lets us know that she thinks the answer is a lot.
Out of context, that question might indeed be offensive.   But after all that lavish praise, it's hard to mistake her intent: in short, although it's phrased as a question, she's pointing out to everyone else how many children Teresa has and including this fact in her list of compliments.  Emphasizing the question with a tame word like fricking can't be offensive, because she's emphasizing a compliment!

A: I agree with most of what Snailboat says but I think some cautions are needed on her conclusion.
Yes, "fricking" or "freaking" are basically milder substitutes for the "F-word". They are thus LESS offensive than that word. But this does not make them inoffensive. Listeners will generally assume that you were considering using the more vulgar word but substituted this milder alternative.
Among friends who have a high tolerance for vulgar language, these would be very mild words. But among people who do not use vulgar language, these words could still be offensive. If one gang member said to another, "Then I shot the mother with his own freaking gun", this would be considered very mild language. If a reporter at a press conference asked the president, "Hey, what's with that freaking weird bill you proposed?", this would likely be startlingly offensive.
In general, if you want to avoid offending people and you do not know their tolerance for vulgar language, I'd avoid using words that have any hint of vulgarity. Of course if your goal is to be shocking or you want to offend and insult someone, that's a different story.

A: Originally, "freaking" was considered a substitute to the more vulgar curse word starting with an 'F', so I would say it is not offensive but the offensiveness also relies heavily on the interpretation of the person hearing/reading it. It has become more and more used in society, and therefore acceptable. Just keep in mind the register and context in which you use it; You wouldn't use this word in the workplace but you would use it when around your friends.
EDIT: @snailboat has a better answer - We were typing ours at the same time.


text:
Q: Criar/alterar entidades em lote Estou lendo um livro de Angular 5 + Asp.NET Core 2.0 (apesar de eu estar usando Angular 7 e Asp.NET Core 2.1), e estou tentando fazer o sistema que esse livro ensina a fazer. É um sistema de Quiz, onde você pode criar seus quizzes, possuindo várias perguntas, cada pergunta possuindo várias respostas.
Já criei a web api para o CRUD básico para cada tipo de entidade: Quiz, Pergunta e Resposta.
Lembrando que cada Quiz possui perguntas, e cada pergunta possui respostas.
Seguindo o livro, para eu criar uma pergunta, o quiz já deve existir no banco de dados. O mesmo vale para as respostas: para criar uma, sua pergunta já deve estar criada.
Eu gostaria de fazer um ambiente onde o usuário pudesse inserir TODAS as informações do quiz, das perguntas e das respostas antes de enviar os dados para o servidor. Ou seja, gostaria que existisse a possibilidade de criar o quiz, as perguntas e as respostas no lado do cliente e, quando o usuário estiver pronto, salvar tudo o que tem pra salvar de uma só vez.
Faz sentido fazer dessa forma? É viável?
Se sim, eu devo criar um loops para enviar as perguntas e as respostas para o servidor? Ou devo enviar tudo em um único objeto e tratar os dados do lado do servidor?
Tentei fazer um loop no Angular, mas acho que o javascript não se dá muito bem com callbacks de pedidos assíncronos dentro de loops...

A: Você pode sim mandar tudo em um objeto apenas.
Há muita discussão sobre isso quando se está criando APIs RESTFul. Pois se tem por convenção que cada objeto deve ter seu próprio Controlador e que os métodos POST recebam apenas um objeto.
Mas isso vai sempre de acordo com as necessidades do programador/software.
Se for enviar tudo de uma vez, você pode montar e enviar o JSON desta forma por exemplo:
var Quiz = {
   nome: "Quiz 01",
   perguntas: [
      {
         nome: "Pergunta01",
         respostas: [
            {
               nome: "resposta A"
            },
            {
               nome: "resposta B"
            }
          ]
      },
      {
         nome: "Pergunta 02",
         respostas: [
            {
               nome: "resposta A"
            },
            {
               nome: "resposta B"
            }
          ]
      }
    ]
  }

Espero ter ajudado.


text:
Q: Reta de regressão ajustada considerando diferentes fatores no ggplot2 Estou tentando reproduzir o gráfico abaixo, em que as retas internas são as retas de regressão ajustadas:

No entanto, por algum fator não está sendo plotado o que deveria, ou seja, está sendo apresentado uma única reta, e mais, as diferentes concentrações da variável "teor" não estão sendo plotadas como na imagem acima, veja o resultado abaixo:

dados = read.table("datanew.csv", header = T, sep=";", dec=","); head(dados)
dados$Trat <- factor(dados$Trat)
dados$Teor <- factor(dados$Teor)
dadosnew$Tempo = as.factor(dadosnew$Tempo)

my.formula <- y ~ x
p = ggplot(dadosnew, aes(x = Tempo, y = massaseca, group = Fator)) +
  stat_summary(geom = "point", fun = mean) +
  stat_smooth(method = "lm", se=FALSE,  formula=y ~ poly(x, 2, raw=TRUE)) + stat_poly_eq(formula = my.formula,
                                                                                eq.with.lhs = "As-italic(hat(y))~`=`~",
                                                                                aes(label = paste(..eq.label.., ..rr.label.., sep = "*plain(\",\")~")),
                                                                                parse = TRUE, size = 5, label.y = 35)+
  labs(title = "",
       x = "Time (Minutes)",
       y = "Weight (mg)") + theme_bw() +
  theme(axis.title = element_text(size = 23,color="black"),
        axis.text = element_text(size = 18,color="black"),
        text = element_text(size = 50,color="black"),
        legend.position = "none") + facet_wrap(~Fator)
p

A: Em primeiro lugar, para ler os dados é melhor, mais simples, usar a função help("read.csv"), que é a versão de read.table para ficheiros CSV com sep = ";" e "dec = ",". Nos ficheiros CSV há sempre nomes de coluna, portanto header = TRUE.
Além disso, converto todas as colunas de classe "character" para fator com um vetor de nomes de colunas a converter, não é necessário fazê-lo uma a uma.
dados <- read.csv2("datanew.csv")

i <- c("Trat", "Teor")
dados[i] <- lapply(dados[i], factor)

Agora o gráfico.
Retirei o stat_poly_eq porque se há 5 níveis de Trat para cada Fator, teríamos 5 equações em cada faceta e o gráfico fica mais difícil de ler.
library(ggplot2)

shape_brks <- unique(dados$Trat)
shape_vals <- rep(c(0, 2:5), 2)

p <- ggplot(dados, aes(x = Tempo, y = massaseca, shape = Trat)) +
  stat_summary(geom = "point", fun = mean) +
  stat_smooth(method = "lm", se = FALSE,
              formula = y ~ poly(x, 2, raw = TRUE),
              linetype = "dashed",
              size = 0.5) +
  scale_shape_manual(name = "Trat",
                     breaks = shape_brks,
                     values = shape_vals) +
  labs(title = "",
       x = "Time (Minutes)",
       y = "Weight (mg)") +
  facet_wrap(~ Fator) +
  theme_bw() +
  theme(axis.title = element_text(size = 23, color = "black"),
        axis.text = element_text(size = 18, color = "black"),
        text = element_text(size = 50, color = "black"),
        legend.position = "none")
p


text:
Q: Is there an equivalent of the Sum of Divisors function for addition (Sum of m-tuples of Addends)? I play KenKen casually and get annoyed by addition cages that require 3 addends. I first came up with a formula for finding the number of ways to sum to a number with 2 addends, which was pretty easy. The number of ways to sum to $n$ with 2 addends, with positive integers only, and with no repeat addends is:

The number of ways to sum to $n$ with 3 addends, with positive integers only, and with no repeat addends is:

I spent a few hours coming up with that second formula for 3 addends. I don't have proofs for either of these formulas.
Does anyone know if something like this already exists? Can anyone help me with a proof or help me come up with a more generalized formula for $m$ addends?


text:
Q: buddypress groups geo location Been googling for hours and can't find the solution to my problem. Basically what I need to do is display the buddypress groups by ip or using geo location, like if I am from Alabama when I logged in I will be seeing the group called "Alabama Group" and no one else. And this goes on for different location as they will be presented in a group.
I've search for plugins but I don't know how to use them in groups nor they can be used in buddypress, I think an if statement would do the trick but not sure how to do the rest of the IP's.
What do guys think is the best  way to handle this? Thanks!


text:
Q: SQL query for update rows in a table and insert those as new rows This is want to achieve:-

*

*Get some rows(x) from a table t.

*Change one col value(f) in all those x rows.

*Then insert those x as new rows in the same table t.

This procedure is not working with this error:-

You can't specify target table 't' for update in FROM clause

This is my procedure
DELIMITER //
DROP procedure IF EXISTS copy_values //
CREATE PROCEDURE copy_values(
IN source_id char(36),
IN dest_id char(36))
BEGIN
INSERT INTO t (a, b, c, d, e, f)
VALUES (
    (SELECT a FROM t WHERE t_cid=source_id),
    (SELECT b FROM t WHERE t_cid=source_id),
    (SELECT c FROM t WHERE t_cid=source_id),
    (SELECT d FROM t WHERE t_cid=source_id),
    (SELECT e FROM t WHERE t_cid=source_id),
    dest_id
    );
END //
DELIMITER ;

Can you suggest an alternative query for solving this use case?

A: An INSERT ... SELECT ... should work.
...
INSERT INTO t
            (a,
             ...
             e,
             f)
            SELECT a,
                   ...
                   e,
                   dest_id
                   FROM t
                   WHERE t_cid = source_id;
...


text:
Q: Mongodb get number of results I am having trouble with finding out how to get a number of documents in my result from the query. All I can do now is
long count = collection.countDocuments();

Result from this is always same.
My next command is pagination
FindIterable<Document> iterDoc = collection.find(query).skip(skip).limit(size);

But I want to know the number of results from
collection.find(query)

But for the FindIterable document there isn't countDocuments() function. The point of this is I want to know a number of pages for my pagination. Is there some MongoDB function for counting results?
Thank you and sorry for my English.

A: You can write a function something like this
public long getFieldCountInCollection(String field, Object value) {
            BasicDBObject query = new BasicDBObject();
            query.put(field, value);
            return mongoCollection.count(query);
}

Note that the parameter field denotes the key name that you have in your collection, and the value denotes the expected value that is present in the collection. If there is no such record meeting the condition, you will get 0 as the result of this function call.


text:
Q: Free Virtual Machine for mac OS X 10.5.8 (Leopard) Are there any free VM's out there for Mac OS X 10.5.8 (Leopard)? I've looked at virtual box, but it only works for 10.6 (Snow Leopard) and onwards. I really don't want to pay to upgrade my OS either. Also looked at VMWare, which isn't free.
Update: currently working myw ay thru Virtual Box version 3.0

A: There are older versions available for Leopard: link. Can't test and verify though, have no Mac at that version available.


text:
Q: is the number of colums limited for an Entity? I might have an Entity with possibly thousands of columns, and was wondering if it would pose any problem (nothing will be indexed):

*

*Will queries be slower if the number of columns increases?

*Can there be in theory an unlimited number of columns?

A: While I never had thousands of columns to know about the speed and performance, as it looks from the data viewer on the dashboard the number of columns should be unlimited:

A: Considering that the GAE Datastore is essentially a very large key-value store right down to property level, in principle an unlimited number of properties are allowed.  Just not all together in one record for space reasons, as others already said.
Datastore is schemaless, but many libraries such as JDO, JPA and Objectify aim to "fix" this "deficiency" by introducing some schema of their own.  That is unhelpful in your scenario.
I suggest you bypass those libraries and directly call the Datastore low-level API as per this example instead.  You can avoid the overheads of indexing if you change the setProperty calls to setUnindexedProperty as often as possible.  Remember to test for a null return from a getProperty call for a property that may be absent in some records.


text:
Q: Having trouble with jQuery toggle function for dropdown menu I have a dropdown menu that slides up and down when toggled to reveal it's menu items. The problem is that when i go to click one of the menu items after the menu has slid down, it is recognized as a toggle and the menu slides up without opening the link of the menu item.
HTML

            Carbohydrates, proteins & fats

Carbohydrates

Proteins

Fats

dropdown script:
$(document).ready(function () {
    $('.dropdown').toggle(
        function () {
            //show its submenu
            $('ul', this).slideDown(300);
        },
        function () {
            //hide its submenu
            $('ul', this).slideUp(300);
        }
    );

});

I'd appreciate any help with this.

A: Why are you individually closing/opening the menu items?  Everything gets hidden anyway when the parent
 element is hidden -- why do anything after that?
I think you want to disable event bubbling.

EDIT 1: You're over-complicating things. Try this:
$(document).ready(function () {
    $('.dropdown').toggle();
});

EDIT 2: Can you be more specific about what you want? If you want a particular element, when clicked, to control the motion of a particular list, try this:
$(document).ready(function () {
    $('a.someLink').click(function() {
       $('.dropdown').toggle();
    });
});

A: Try moving the triggering link outside of the dropdown items
Carbohydrates, proteins & fats

Carbohydrates

Proteins

Fats

And then slightly modify your jquery
$(document).ready(function () {
    $('.dropdown').toggle(
        function () {
            //show its submenu
            $('ul', $(".divdropdown")).slideDown(300);
        },
        function () {
            //hide its submenu
            $('ul', $(".divdropdown")).slideUp(300);
        }
    );
});

A: Unfortunately none of the above answers were working for me. I found a solution shortly afterwards.
HTML

            Carbohydrates, proteins & fats

Carbohydrates

Proteins

Fats

jquery script
$(document).ready(function() {
        $('.dropdown').click(function() {
                        // When the event is triggered, grab the current element 'this' and
                        // find it's children '.sub_navigation' and display/hide them
            $(this).find('.sub_navigation').slideToggle();
        });

        $(".disablelink").click(function(e) {
            e.preventDefault();
        });

    });

That solution is working perfectly for me. I added in e.preventDefault(); to stop the page jumping up and down when i clicked on the link.


text:
Q: IE8 AngularJS directive call .getContext on canvas I'm currently using AngularJS 1.4.7 and I'm trying to integrate Chartjs. Everything works as expected in most modern browsers (Chrome, Firefox, IE 9 >, etc). However I got a problem with IE8.
My current setup is that I've created an directive on the canvas element. Which calls the scoped method donutify.
 app.directive('donutify', ['$timeout', function ($timeout) {
    var def = {
        restrict: 'A',
        terminal: true,
        transclude: false,
        link: function (scope, element, attrs) {
            $timeout(function () {
                scope.donutify(attrs.id)
            }, 0);
        }
    };
    return def;
}]);

In the donutify method I'm trying to access the method of the current canvas.
$scope.donutify = function (id)
    {
        var donut = $("#" + id);

        if (donut.length)
        {
            var context = donut.get(0).getContext("2d");
        ...

This works in all browser except in IE8. If I print out the donut object, I can see it exists, however it doesn't has the getContext method available. The error message thrown in console is:
TypeError: Object doesn't support this property or method
Can anyone help?


text:
Q: iOS pickerview value change based on radio button I want to be able to produce a certain value to a label based on a pickerview and a set of radio buttons. Is there an easier way to accomplish this for iOS than that way?  I'm going to be providing a value and have some conversion choices with the radio button.
Thanks

A: Not really a programming or a code review question, but how about two text fields each with a picker view underneath?  The text fields present quantity and the pickers select units.  Run the conversion in both directions, remembering which text field was most recently the first responder and computing the value of the other.


text:
Q: Google Play Services not imported correctly I know. Many similar questions. I have not found any answer that solves this one.
How do I get the Google Play Services lib to work in Eclipse 3.7.1 with Android SDK Tools 23.0.2?
Tried alot of combinations. First, to get the lib to import correctly. I've tried these methods beside the obvious flawed from Google. (I've also removed the write-protection from all files)

*

*Copy the code to the workspace and use File --> import --> Android --> Used ex... then checked the COPY-box.

*Copy the folder to another place and then import into the workspace and linking it.
Then in my project I added the meta-data-thing into my  in androidmanifest.xml.
In my project I've clicked Properties --> Android --> In the lower panel I've added the Google Services Project that I've imported.
Now everything builds. (I've seen that many people have trouble with that.)
In properties, under the option Java Build Path the libraries are checked under the tab "Order and export".
The method I use in my main activity is
   GooglePlayServicesUtil.isGooglePlayServicesAvailabl(..)...

When I run the application I get an exception, NoClassDefFoundError.
And for sure, the class is not in the APK. I've checked, but some other classes under from gms.internal exists?!
In my project under Android dependencies is the 1k output from the imported lib. Under Android private libraries is the full jar.
Update: Solved this by downloading the latest version of http://www.eclipse.org. (The update function didn't find anything).


text:
Q: Can someone help me fix this popup overlay? it pops up inside dropdown list, but i want it to overlay over full screen, for unique list item can someone give me a idea how to make this done?
I want to create unique popup that is going to be activate via  tag, inside dropdown list... but popup is not showing at full screen, its showing inside popup.
this is code
.popup .overlay {
    position:fixed;
    top:0px;
    left:0px;
    width:90%;
    height:95%;
    background:rgba(0,0,0,0.7);
    z-index:1;
    display:none;
  }

  .popup .content {
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%) scale(0);
    background:#fff;

    max-width: 550px;
    width:95%;
    height:180vw;
    margin: 50px auto;
    /* width:95vw;
    height:180vw; */
    z-index:2;
    text-align:center;
    padding:20px;
    box-sizing:border-box;
    font-family:"Open Sans",sans-serif;
  }

  .popup .close-btn {
    cursor:pointer;
    position:absolute;
    right:20px;
    top:20px;
    width:30px;
    height:30px;
    background:#222;
    color:#fff;
    font-size:25px;
    font-weight:600;
    line-height:30px;
    text-align:center;
    border-radius:50%;
  }

  .popup.active .overlay {
    display:inline;
  }

  .popup.active .content {
    transition:all 300ms ease-in-out;
    transform:translate(-50%,-50%) scale(1);
  }

  button {
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    padding:15px;
    font-size:18px;
    border:2px solid #222;
    color:#222;
    text-transform:uppercase;
    font-weight:600;
    background:#fff;
  }

{{something}}

Prikazi proizvod

×

Ime_Proizvoda

`

my goal is to show this popup over whole screen, but that all LI have unique popup screen with unique photo...Thanks!
ps sorry if i didnt explain well , or if this request looks messy, this i my 1st stack overflow question xD


text:
Q: Is there a way to trace click once application I am trying to build a WPF click once application and going to host it on a server, then will install it to 10 client. May I know is there any way to trace the client version from server level? Example, today I had updated server version to 1.15, but i am not able to know when or had the client update to latest version 1.15.

A: There is no built-in way in ClickOnce, however you can either monitor downloads of you application manifest file (.application) on your web server or check the ApplicationDeployment.IsFirstRun ("The value of this property is reset whenever the user upgrades from one version to the next.") property every time your application launches and call an API you would setup on your server that logs the installation.
If you go with that, make sure that you handle all exception in the logging call and that the execution keeps going even if the logging fails.
You could also switch to manual updating using the methods on the ApplicationDeployment.CurrentDeployment object to completely decide how the update process is handled but it will add a layer of complexity to you application.


text:
Q: color selected rows in a bar plot I have a bar plot, which could be created with this code:
hplot = barh(data(:,1));

This plots all bars in the same color.
Now I want to plot the bars wih row numbers 1, 4 and 5 in red and all others in blue.
How could I achieve that?

A: Have a look at this. There's nothing ready to use directly.
http://www.mathworks.co.uk/support/solutions/en/data/1-1T6UHS/


text:
Q: Probability of players winning table-tennis game before deuce I'm stuck on a homework assignment and would really appreciate if someone could point out where I'm going wrong, or if there's not actually anything wrong with the approach I'm taking, and I'm just unnecessarily second-guessing myself.
Player A and Player B play a table-tennis game, which ends when the first person scores 11 points. If the scores are 10-10 a deuce occurs which then ends when someone takes a two-point lead. Let $p = 0.55$ the probability Player A has of winning any given round in the game. Assume independence for each round. What is the probability that Player A wins the game?
My approach: Player A can win the game in any of the rounds from 11-20, and after round 20, if a deuce occurs, then the number of possible rounds that might be played before they win diverges to infinity. Forgetting about the deuce stage for the moment, I formulated the probability of them winning before the deuce stage as follows:
$$P(Player\space A\space wins\space before\space deuce)=\sum_{n=11}^{20}{n\choose 11}0.55^{11}0.45^{n-11}$$ However this number turns out to be approximately $0.931$. This seems incorrect to me. For comparison I also ran: $$P(Player\space B\space wins\space before\space deuce)=\sum_{n=11}^{20}{n\choose 11}0.45^{11}0.55^{n-11}$$ And the result I got was approximately $0.779$.  Now, I know that the probability that a deuce doesn't occur is given by: $$P(no\space deuce) = 1-P(deuce) = 1-{20\choose 10}0.55^{10}0.45^{10}\approx0.84.$$ And my belief is that since the outcomes which make up either Player A winning before the deuce or Player B winning before the deuce collectively exhaust the outcomes in which the games ends and no deuce occurs then the following relation should hold: $$P(Player\space A\space wins\space before\space deuce) + P(Player\space B\space wins\space before\space deuce) = P(no\space deuce)$$ However, this isn't the case.
Any help correcting this reasoning would be lovely.


text:
Q: How do I write this program in scheme? How do I write every element in a list twice such that:
(double '(a((b)(c d)(((e)))))) --> '(a a((b b)(c c d d)(((e e)))))

I currently have this so far but it's not quite right.
(define double
  (lambda (x)
    (cond ((null? x) '())
          ((list? x)(append (double (car x)) (double cdr x)))
          (else (cons x (cons x '()))))))

A: You were close to the answer, the key point is that we have to double the elements when the car of the list is an atom, not when the list itself is an atom, in this way we can modify the list that we're building as output. Here's a fixed version:
(define double
  (lambda (x)
    (cond ((null? x) '())
          ((list? (car x)) ; ask about the car of the list. It's better to use pair?
           (cons (double (car x)) ; use cons, not append
                 (double (cdr x))))
          (else (cons (car x) (cons (car x) (double (cdr x)))))))) ; double the car

It works as expected:
(double '(a ((b) (c d) (((e))))))
=> '(a a ((b b) (c c d d) (((e e)))))


text:
Q: Sending requests with different headers using HttpClient There is a similar SO question here which talks about the performance of HttpClient objects and recommends to use one HttpClient instance per application. My project requires me to send multiple webservice requests to the same URI but each with a different set of headers. Should I create a new HttpClient instance for every request, knowing the fact that DefaultRequestHeaders will be same for all requests if I use a static instance.

A: You can:

*

*Set default headers on your global instance

*Create multiple global (logical) instances with different default configurations

*Set (additional) headers per request

*Create new HttpClient using IHttpClientFactory

Docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.1
Global Default Headers
Here you create one client instance and add headers that will be applied to all requests.
 var client = new HttpClient();
 client.DefaultRequestHeaders.Add("Content-Type", contentTypeValue);

Multiple Preconfigured Instances
In this dotnet core 2.1 example, we register a preconfigured named instance:
services.AddHttpClient("github", c =>
{
    c.BaseAddress = new Uri("https://api.github.com/");
    // Github API versioning
    c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
    // Github requires a user-agent
    c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
});

Later we'll inject IHttpClientFactory, and get this pre configured client like so:
var client = _clientFactory.CreateClient("github");

An alternative to named client are "typed clients": https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0#typed-clients. Both approaches will keep the basic configuration at one place.
Headers per Request
If your headers belong to a single request only, simple set them per request.
var client = new HttpClient();

var request = new HttpRequestMessage();
request.Headers.Add("Content-Type", "text/plain");

var response = await client.SendAsync(request);

Using this approach you can use a shared HttpClient instance.
IHttpClientFactory
If you want a new "clean" HttpClient instance, the recommended approach for asp.net core is to inject IHttpClientFactory and use _clientFactory.CreateClient().
public class MyService {
  public MyService (IHttpClientFactory clientFactory)
  {
    _clientFactory = clientFactory;
  }
  public async Task DoSomething()
  {
    var client = _clientFactory.CreateClient();
    // do request
  }
}


text:
Q: Howto create the pdf hash ahead of time using iText IExternalSignatureContainer I'm using iText 7 for applying signatures to pdf documents. I also use my own implementation of IExternalSignatureContainer in order to integrate the certificates into the PKCS7 CMS since the signing service only returns a PKCS1 signature.
The signature process is asynchrony (user has to authenticate) i'd like to do the following:

*

*Prepare the document (PdfReader)

*Get the hash value of the document back to the user

*Throw the document away (PdfReader)

*Let the user authenticate (Not directly related with the iText signing process) and create the signature (PKCS1)

*If the user is authenticated, Prepare the document again and apply the signature.

Reason for this is that i don't have too keep the prepared document in memory and also for batch signing.
My problem is that the hash value created is always different. (Even if i set the date/time via pdfSigner.SetSignDate to the same value) or every PdfReader/PdfSigner instance.
            //Create the hash of of the pdf document
            //Part of my IExternalSignatureContainer Sign method
            //Called from iText pdfSigner.SignExternalContainer
            //The produced hash is always different
            byte[] hash = DigestAlgorithms.Digest(pdfStream, DigestAlgorithms.GetMessageDigest(hashAlgorithm));

Question: Is there a way to

*

*Produce the hash of a pdf document "ahead of time" on one instance of the PdfReader

*Create the signature

*Apply the signature on a different instance of the PdfReader

Attached is a complete example of the process (Including the signature creation which actually needs to be done by a different service)
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using iText.Kernel.Pdf;
using iText.Signatures;
using Org.BouncyCastle.X509;
using X509Certificate = Org.BouncyCastle.X509.X509Certificate;

namespace SignExternalTestManuel
{
    class Program
    {
        const string filePath = @"c:\temp\pdfsign\";
        public static string pdfToSign = Path.Combine(filePath, @"test.pdf");
        public static string destinationFile = Path.Combine(filePath, "test_signed.pdf");
        public static string LocalUserCertificatePublicKey = Path.Combine(filePath, "BITSignTestManuel5Base64.cer");
        public static string LocalCaCertificatePublicKey = Path.Combine(filePath, "BITRoot5Base64.cer");
        public static string privateKeyFile = Path.Combine(filePath, "BITSignTestManuel5.pfx");
        public static string privateKeyPassword = "test";

        public static void Main(String[] args)
        {
            PdfReader reader = new PdfReader(pdfToSign);
            using (FileStream os = new FileStream(destinationFile, FileMode.OpenOrCreate))
            {

                StampingProperties stampingProperties = new StampingProperties();
                stampingProperties.UseAppendMode();
                PdfSigner pdfSigner = new PdfSigner(reader, os, stampingProperties);
                pdfSigner.SetCertificationLevel(PdfSigner.NOT_CERTIFIED);

                IExternalSignatureContainer external = new GsSignatureContainer(
                    PdfName.Adobe_PPKLite,
                    PdfName.Adbe_pkcs7_detached);

                pdfSigner.SetSignDate(new DateTime(2021, 2, 22, 10, 0, 0));

                pdfSigner.SetFieldName("MySignatureField");
                pdfSigner.SignExternalContainer(external, 32000);
            }
        }
    }

    public class GsSignatureContainer : IExternalSignatureContainer
    {
        private PdfDictionary sigDic;

        public GsSignatureContainer(PdfName filter, PdfName subFilter)
        {
            sigDic = new PdfDictionary();
            sigDic.Put(PdfName.Filter, filter);
            sigDic.Put(PdfName.SubFilter, subFilter);
        }

        /// <summary>
        /// Implementation based on https://kb.itextpdf.com/home/it7kb/examples/how-to-use-a-digital-signing-service-dss-such-as-globalsign-with-itext-7#HowtouseaDigitalSigningService(DSS)suchasGlobalSign,withiText7-Examplecode
        /// </summary>
        /// <param name="pdfStream"></param>
        /// <returns></returns>
        public byte[] Sign(Stream pdfStream)
        {
            //Create the certificate chaing since the signature is just a PKCS1, the certificates must be added to the signature
            X509Certificate[] chain = null;

            string cert = System.IO.File.ReadAllText(Program.LocalUserCertificatePublicKey);
            string ca = System.IO.File.ReadAllText(Program.LocalCaCertificatePublicKey);
            chain = CreateChain(cert, ca);

            X509CrlParser p = new X509CrlParser();

            String hashAlgorithm = DigestAlgorithms.SHA256;
            PdfPKCS7 pkcs7Signature = new PdfPKCS7(null, chain, hashAlgorithm, false);

            //Create the hash of of the pdf document
            //Part of my IExternalSignatureContainer Sign method
            //Called from iText pdfSigner.SignExternalContainer
            //The produced hash is always different
            byte[] hash = DigestAlgorithms.Digest(pdfStream, DigestAlgorithms.GetMessageDigest(hashAlgorithm));

            byte[] signature = null;

            //Create the hash based on the document hash which is suitable for pdf siging with SHA256 and a X509Certificate
            byte[] sh = pkcs7Signature.GetAuthenticatedAttributeBytes(hash, null, null, PdfSigner.CryptoStandard.CMS);
            //Create the signature via own certificate
            signature = CreateSignature(sh, Program.privateKeyFile, Program.privateKeyPassword);
            pkcs7Signature.SetExternalDigest(signature, null, "RSA");
            return pkcs7Signature.GetEncodedPKCS7(hash, null, null, null, PdfSigner.CryptoStandard.CMS);
        }

        public void ModifySigningDictionary(PdfDictionary signDic)
        {
            signDic.PutAll(sigDic);
        }

        private static X509Certificate[] CreateChain(String cert, String ca)
        {
            //Note: The root certificate could be omitted and it would still work
            X509Certificate[] chainy = new X509Certificate[2];
            X509CertificateParser parser = new X509CertificateParser();
            chainy[0] = new X509Certificate(parser.ReadCertificate(Encoding.UTF8.GetBytes(cert))
                .CertificateStructure);
            chainy[1] = new X509Certificate(parser.ReadCertificate(Encoding.UTF8.GetBytes(ca))
                .CertificateStructure);
            return chainy;
        }

        #region "Create signature, will be done by an actual service"
        private byte[] CreateSignature(byte[] hash, string privateKeyFile, string privateKeyPassword)
        {
            //Sign data directly with a X509Certificate
            X509Certificate2 rootCertificateWithPrivateKey = new X509Certificate2();
            byte[] rawData = System.IO.File.ReadAllBytes(privateKeyFile);
            rootCertificateWithPrivateKey.Import(rawData, privateKeyPassword, X509KeyStorageFlags.Exportable);

            using (var key = rootCertificateWithPrivateKey.GetRSAPrivateKey())
            {
                return key.SignData(hash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            }
        }
        #endregion

    }
}

A:
Question: Is there a way to

*

*Produce the hash of a pdf document "ahead of time" on one instance of the PdfReader

*Create the signature

*Apply the signature on a different instance of the PdfReader

This use case currently is not supported by iText, in each pass in particular

*

*a different PDF ID is generated,

*a different modification time is used, and

*in case of AES encrypted PDFs the random numbers used for encryption are different.

It is possible to patch iText to use the same values in each pass, but before patching a library you should consider whether you can adapt your architecture to make a patch unnecessary.
In your case, for example, if you cannot keep the original PdfSigner instance, an alternative approach could be to have the original PdfSigner after hashing store its result file with dummy signature bytes (e.g. new byte[0]). Then, after retrieving the signature container, you can inject it into the stored file in a different service using PdfSigner.signDeferred as long as both service can access shared storage (or the first service can at least forward the file the the storage of the second service).


text:
Q: Best practices for dealing with shifting, inconsistent seasonality This question is related to a previous post I've looked at (Calculation of seasonality indexes for complex seasonality), but deals with more granular data (daily instead of weekly), and transforming holiday seasons (instead of just holiday) creating a larger question about the reasoning behind dummy variables.
As an introduction, I'm looking to forecast daily retail sales for a highly cyclical e-commerce company.  Each year, buying patterns shift for several reasons:

*

*Calendar shift (where, for example, 5/17/13 is a Friday, while 5/17/12 is a Thursday);

*Shifting of holidays set by the day of the week (i.e. Labor Day, Thanksgiving, Mother's Day);

*Shifts in the time and length of shopping seasons (i.e. in 2012, there were 32 calendar days, 21 workdays, and the season started on Nov. 28 in the holiday shopping season, while this year, there are 26 calendar days, 17 workdays, and the season starts on Nov. 29). These changes affect the overall shape and size of the seasonal curve, and not just the behavior at or near the holiday.
Among the retail forecasters I've encountered, there's a few options for dealing with forecasting shifting seasonality:

*

*One is to only use exact calendar equivalent years to parcel out seasonality -- for example, 2013 exactly matched 2002 in terms of the placing of holidays. Then, you apply a 365-day ARIMA on the data. But, in e-commerce (and overall) a lot has happened since 2002 that affects how seasonality looks.

*The second is exponential smoothing with dummy variables.  But, as consumer behavior doesn't just change on the holiday (or the days approaching it), but relates to how far the holiday is in relation to other shifting dates (and the day of the week), you hit the problems of either creating a boatload of dummy variables for the distance from and to each holiday that can over-specify your model (and not make it easily generalizable to the year you want to forecast), or get a "general" seasonality that usually under-preforms.  You could also do a fractional polynomial to approximate the curve by days until (or between) one holiday or another, but this creates the usual problems with fracpolys -- notably over-fitting and wildly strange results at certain points in and out of the sample.

*The third option I've seen is to adjust the data from previous years to match the size of each holiday season by, in the case when the holiday shopping season is a week shorter than previous years, taking out a week and then adding back that revenue across the remaining season, or doing the reverse when the season is a week longer.  After that's done, you can do a seasonal decomposition to parcel out the seasonality.  The issue with this is that it involves a ton of subjectivity, and assumes that shoppers will evenly spread the lost week, rather than "back load" their behavior as the holiday more quickly approaches. Fixing the "back load" would then create even more subjectivity of when shoppers will start responding to the proximity to the holiday (such as Christmas).
So, I'm wondering the experience of other forecasters (especially those with retail experience) with this issue of shifting seasonality by day.
Looking forward to your thoughts. I can also add some dummy data if you want to see exactly what I'm talking about if you'd like.


text:
Q: To open Project Properties WIndow (Java Build Path) automatically using code I am developing an Eclipse plugin which would create a new Java project and few classes inside it.
Once the plugin wizard closes (after I click finish in the final page), i need the Project Properties window of this particular project to be opened automatically.
I must achieve that through code, any examples please?

A: Use org.eclipse.ui.dialogs.PreferencesUtil
PreferencesUtil.createPropertyDialogOn(shell, element, null, null, null).open();

will display the full Properties dialog. The parameters allow you to choose the initial page and filter the pages shown.
The element parameter would be the IProject for the project.
You can find existing property page ids using the Eclipse Search dialog. Select the Plug-in Search tab and enter the property page extension point id org.eclipse.ui.propertyPages in the Search string. Set Search For to Extension Point, set Limit To to References and Scope to Workspace.

Perform the search to get the plug-ins which use this extension point. Opening a search result will open the plugin.xml for the plugin at the extension point.

A: I got the final answer. This is how it goes:
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
MessageDialog.openInformation(shell, "Project Proeperties", "Properties window will open next");

String propertyPageId = "org.eclipse.jdt.ui.propertyPages.BuildPathsPropertyPage";
PreferenceDialog dialog = PreferencesUtil.createPropertyDialogOn(shell, iProject, propertyPageId, null, null);
    dialog.open();


text:
Q: LexikJWTAuthenticationBundle with ionic app I have seen many post on this subject, but i can't make a correct request, regardless all of my tests.
I hope anyone could help me on this.
My current configuration :
I work with wamp - apache 2.4.9 -- php 5.5.12
I work with symfony3
i add all rewrite rules in my vhost :
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.)
RewriteRule . - [e=HTTP_AUTHORIZATION:%1]

On backend, my security.yml is :
firewalls:

        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        api_doc:
            pattern: ^/api/doc
            anonymous: true

        api_login:
            pattern:  ^/api/login
            provider: fos_userbundle
            stateless: true
            anonymous: true
            form_login:
                check_path:     /api/login_check
                require_previous_session: false
                success_handler:          lexik_jwt_authentication.handler.authentication_success
                failure_handler:          lexik_jwt_authentication.handler.authentication_failure

        api:
            pattern:   ^/api
            stateless: true
            provider: fos_userbundle
            lexik_jwt:
                authorization_header:
                    enabled: true
                    prefix:  Bearer
                query_parameter:
                    enabled: true
                    name:    Bearer
                throw_exceptions:        true
                create_entry_point:      true

Configuration  of fosuserbundle :
fos_user:
    db_driver: orm
    firewall_name: main
    user_class: UserBundle\Entity\User
    group:
        group_class: UserBundle\Entity\Group
        form:
            type: UserBundle\Form\Type\GroupFormType
    profile:
        form:
            type: UserBundle\Form\Type\ProfileFormType

And side of client, i use ionic with angular js, and i try to get the token with :
 var loginData = {
                username: this.login.username,
                password: this.login.password
            };

            console.debug(loginData);

            $http({
                url: 'http://app.local/app_dev.php/api/login_check',
                method: 'POST',
                data: loginData,
                headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
                ignoreAuthModule: true
            })
                .success(function (data) {
                    console.log("Success -- login ok with ".data);
                    $scope.token = data;
                })
                .error(function (data) {
                    console.log("ERROR -- login fail with ", data);
                    $scope.token = data;
                });

that's always return me 'bad credentials'
But my test with curl send me a token
curl -X POST http://app.local/api/login_check -d _username=username -d _password=pass

I have test to prefix _ my login data, change configuration
If anyone have an idea ??

EDIT :
Maybe i have found my problem.
This request curl work fine :
curl -X POST http://app.local/api/login_check -d _username=username -d _password=pass

But this one doesn't work :
 curl -X POST http://app.local/app_dev.php/api/login_check -d '{"username": "user", "password": "pass"}'

I search one solution for solve it, but i guess angular http method cannot send two parameters

EDIT 2 :
This request works fine :
curl -X POST http://app.local/app_dev.php/api/login_check -d '{"_username": "user", "_password": "pass"}' -H "Content-Type: application/json"

I search a solution for copy this request with angular http object

EDIT 3 :
I make my angular request like this :
var loginData = {
                _username: this.login.username,
                _password: this.login.password
            };
            $http({
                url: 'http://app.local/app_dev.php/api/login_check',
                method: 'POST',
                data: loginData,
                headers: {'Content-Type': 'application/json'}
            })
                .success(function (data) {
                    console.log("Success -- login ok with ".data);
                })
                .error(function (error) {
                    console.log("ERROR -- login fail with ", error);
                });

And my javascript console print an error :
XMLHttpRequest cannot load http://app.local/app_dev.php/api/login_check. Response for preflight has invalid HTTP status code 404

EDIT 4 :
I ddin't found the solution ...
It seems CORS request is the problem. i try do reset all headers in my mobile app, nothing has changed.
I try to install nelmioCorsBundle for authorize OPTIONS headers and control my configuration, nothing has changed
I have installed the sandbox (https://github.com/slashfan/LexikJWTAuthenticationBundleSandbox) and i have exactly the same problem.
When i try to execute curl request, i can get my token. When i use angular/ionic app, i have the error :
https://github.com/slashfan/LexikJWTAuthenticationBundleSandbox
XMLHttpRequest cannot load http://app.local/app_dev.php/api/login_check. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:8100', but only one is allowed. Origin 'http://localhost:8100' is therefore not allowed access.

If anyone have a new idea ?? i don't know what i can test now :s
PS : which version of angular is working with demo app in the LexikJWTAuthenticationBundleSandbox ?

A: In the first (working) request you are using _username as field with value "username" and _password as field with value "pass".
In the second you are using username (instead of _username) as field with value "user" and password (instead of _password) as field with value "pass".
Change your second request to:
curl -X POST http://app.local/app_dev.php/api/login_check -d '{"_username": "username", "_password": "pass"}'

And it should work.
EDIT
Add the option -H "Content-Type: application/json, that gives:
curl -X POST http://app.local/app_dev.php/api/login_check  -H "Content-Type: application/json" -d '{"_username": "username", "_password": "pass"}'

And it should work!
EDIT
It seems to be a CORS related issue.
Try to add the following in your angular application, before doing the POST request:
app.config(function ($httpProvider) {
    $httpProvider.defaults.headers.common = {};
    $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.put = {};
    $httpProvider.defaults.headers.patch = {};
});

Where app is your angular module (i.e. var app = angular.module(...)).


text:
Q: Update view in Fragment ViewPager from Activity crash In my Activity have a ViewPager and a button update:

public class Main7Activity extends AppCompatActivity {
    ViewPager vp;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main7);
        btn = findViewById(R.id.btn_update);
        vp = findViewById(R.id.vp);
        final AdapterEx adapterEx = new AdapterEx(getSupportFragmentManager());
        vp.setAdapter(adapterEx);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (vp.getCurrentItem() == 1 && adapterEx != null) {
                    AdapterEx fa = (AdapterEx) vp.getAdapter();
                    FragmentTow mstPeopleFragment = (FragmentTow) fa.getItem(vp.getCurrentItem());
                    mstPeopleFragment.update();
                }
            }
        });
    }

    private class AdapterEx extends FragmentStatePagerAdapter {
        public AdapterEx(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int i) {
            switch (i) {
                case 0:
                    return new FragmentOne();
                case 1:
                    return new FragmentTow();
                default:
                    return new FragmentTow();
            }

        }
        @Override
        public int getCount() {
            return 2;
        }
    }
}

In FragmentTwo I have two text: groups and teams, I want when page show FragmentTwo and click button update in activity, text teams will show and text groups will disable in FragmentTwo.
Here is code in FragmentTwo:

public class FragmentTow extends Fragment {
    TextView textTeam;
    TextView textGroup;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_two, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        textTeam = view.findViewById(R.id.tv_team);
        textGroup = view.findViewById(R.id.tv_group);
    }
    public void  update(){
        textTeam.setVisibility(View.GONE);
        textGroup.setVisibility(View.VISIBLE);
    }
}

and here is xml in FragmentTwo fragment_two.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_team"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="groups"
        android:textSize="50sp" />

    <TextView
        android:id="@+id/tv_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Teams"
        android:textSize="50sp"
        android:visibility="gone" />
</FrameLayout>

When click button update in Activity I will call update() function in FragmentTwo but it's crash with log: Process: com.example.test2, PID: 32755
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setVisibility(int)' on a null object reference
        at com.example.test2.FragmentTow.update(FragmentTow.java:29)
        at com.example.test2.Main7Activity$1.onClick(Main7Activity.java:30)
I try debug and see when I get fragment from activity it will return FragmentTwo in another local in stack so text in FragmentTwo will NullPointerException when call update().
How I can update text in FragmentTwo when click button in Activity?

A: In
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_groups, container, false);
}

Is R.layout.fragment_groups the layout of your FragmentTwo? If not, textTeam and textGroup will be null
EDIT
Try this:
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    textTeam = getView().findViewById(R.id.tv_team);
    textGroup = getView().findViewById(R.id.tv_group);
}

A: You can simply try to get the TextViews from the fragment in your Main7Activity using mstPeopleFragment.getView() like so:-
textTeam = mstPeopleFragment.getView().findViewById(R.id.tv_team);
textGroup = mstPeopleFragment.getView().findViewById(R.id.tv_group);

then update them accordingly,so add this instead:-
//inside your btn listener in Main7Activity.java

FragmentTow mstPeopleFragment (FragmentTow)fa.getItem(vp.getCurrentItem());

textTeam = mstPeopleFragment.getView().findViewById(R.id.tv_team);
textGroup = mstPeopleFragment.getView().findViewById(R.id.tv_group);

textTeam.setVisibility(View.GONE);
textGroup.setVisibility(View.GONE);

But remember to keep them inside your button listener else it wouldn't work.

A: I find solution. Update new AdapterEx with code:

AdapterEx extends FragmentPagerAdapter {

    ArrayList<Fragment> fragments = new ArrayList<>();

    public void addFragments(Fragment fragment) {
        this.fragments.add(fragment);
    }

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

And when click update I call
FragmentTow fragmentTow = (FragmentTow) viewPagerAdapter.getItem(1);
  fragmentTow.update();
Thank every one for your time!
Thank you so much!


text:
Q: What is the correct place for driver sources? I have some sources I want to compile using make. The sources will be compiled into a driver I'm going to use. What is the correct place for such files? /usr/share? /opt? /usr/local/...?
Edit: the driver is going to be a kernel driver, and I'll be using dkms for the installation. The distro I'll be using is Ubuntu, but I'll might also use it for other distros in the future

A: It's really up to you but normally sources are stored in /usr/src as mentioned in the comments. Since system-wide installed applications could install their sources in this directory as well, to avoid possible conflicts, you could use /usr/local/src instead but again in the end no one stops you from storing sources anywhere you want as long as you remember where they are and there are no conflicts. You may as well create /src - easy to find, easy to cd to.


text:
Q: How to pass :current_user in Graphql resolver I have QueryType
Types::QueryType = GraphQL::ObjectType.define do
  name 'Query'

  field :allProjects, function: Resolvers::Projects
end

And Resolver like this
require 'search_object/plugin/graphql'

module Resolvers
  class Projects
    include SearchObject.module(:graphql)

    type !types[Types::ProjectType]

    scope { Project.all }

    ProjectFilter = GraphQL::InputObjectType.define do
      name 'ProjectFilter'

      argument :OR, -> { types[ProjectFilter] }
      argument :description_contains, types.String
      argument :title_contains, types.String
    end

    option :filter, type: ProjectFilter, with: :apply_filter
    option :first, type: types.Int, with: :apply_first
    option :skip, type: types.Int, with: :apply_skip

    def apply_first(scope, value)
      scope.limit(value)
    end

    def apply_skip(scope, value)
      scope.offset(value)
    end

    def apply_filter(scope, value)
      branches = normalize_filters(value).reduce { |a, b| a.or(b) }
      scope.merge branches
    end

    def normalize_filters(value, branches = [])
      scope = Project.all
      scope = scope.where('description ILIKE ?', "%#{value['description_contains']}%") if value['description_contains']
      scope = scope.where('title ILIKE ?', "%#{value['title_contains']}%") if value['title_contains']
      branches << scope

      value['OR'].reduce(branches) { |s, v| normalize_filters(v, s) } if value['OR'].present?
      branches
    end
  end
end

I want to access current_user in the resolver so i can access current_user.projects not Project.all.  I am very new to graphql and learning.
Everything works but i just need to understand the whole flow on how i can get old of the ctx in the resolver.

A: First you need to set the current_user in the context. This happens in your GraphqlController.
class GraphqlController < ApplicationController
  before_action :authenticate_user!

  def execute
    variables = ensure_hash(params[:variables])
    query = params[:query]
    operation_name = params[:operationName]
    context = {
      current_user: current_user,
    }
    result = HabitTrackerSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
    render json: result
  rescue => e
    raise e unless Rails.env.development?
    handle_error_in_development e
  end

  # ...
end

Once it's done, you can access the current_user from a query (or a mutation) simply by writing:
context[:current_user]

To make things even simpler, you can add a current_user method toTypes::BaseObject (app/graphql/types/base_object.rb) and you'll be able to call current_user from the #resolve methods.
module Types
  class BaseObject < GraphQL::Schema::Object
    field_class Types::BaseField

    def current_user
      context[:current_user]
    end
  end
end


text:
Q: Can I force Windows 11 not to have a separate taskbar icon for an opened Visual Studio project? This might seem the very definition of a 1st World Problem but it's driving me nuts!

So the right-hand icon is my opened Visual Studio project, and to its left is the icon for Visual Studio 2022.  In previous versions of Windows (10) and VS (2019) there was a single Visual Studio icon, which was either plain (no open VS projects) or decorated with a mark at the bottom to show that there was an open project.  I'd like to return to that happy place but I can't figure out how.  There is no property that I can find on the Taskbar nor in VS itself.

A: For me, this seems to be a Windows 11 bug. I have the same problem for another program than VS. After unpinning the old icon and pinning the new, the problem is solved for a few days until it occures again. Hope it will be fixed soon.

A: The answer (so far) seems to be, as @phuzi said, to unpin VS2022.  I then closed the project and repinned VS 2022.  There is now only one icon - result.


text:
Q: How to get a publicly accessible url for a timeline item attachment? I wondered how could I get a publicly accessible url for a timeline item attachment (like an image) that doesn't require authentication to access it?

A: This is unfortunately not possible as image attachments are private to the user: they indeed require an access token to be retrieved.
The only way you could make the image publicly available is by providing some sort of proxy that would fetch the image using a stored token and returning it to the requester.


text: Q: External storage not detected on macbook air 2015 So I have a MacBook Air late 2015 that I recently got from a friend, but neither of the usb ports work for usb storage nor does the sd card slot work. However whatever I connect does show up in the system information. Just not in the Disk Utilities nor in the finder. I've already reset the SMC and reinstalled the OS. I honestly don't know what to do now.