text:
Q: MenuControl in asp.net from database I have a menu control in my Master page.T he name of the menu and corresponding url is coming from the database. If a menu has a sub menu it is also showing properly.
But the problem arises if a sub menu has a child menu.
My database table has 4 columns
MenuId || MenuName || ParentId || URL.
and the code is
 private void getMenu()
 {
     DataSet ds = new DataSet();
     DataTable dt = new DataTable();
     ds = objSec.ShowMenu(s_UserId);

     dt = ds.Tables[0];
     DataRow[] drowpar = dt.Select("ParentID=" + 0);

     foreach (DataRow dr in drowpar)
     {
         menuBar.Items.Add(new MenuItem(dr["MenuName"].ToString(), dr["MenuID"].ToString(),
         "", dr["URL"].ToString()));
     }

     foreach (DataRow dr in dt.Select("ParentID >" + 0))
     {
         try
         {
             MenuItem mnu = new MenuItem(dr["MenuName"].ToString(), dr["MenuID"].ToString(),
              "", dr["URL"].ToString());
              menuBar.FindItem(dr["ParentID"].ToString()).ChildItems.Add(mnu);
         }
         catch (Exception ex)
         {
         }
      }
    }

A: The approach in your sample might lead to incorrect results if sub-items are contained in the table before their parent-item. In addition, the empty catch-block might hide any errors. Therefore, I'd recommend another approach.
Instead of looping the table, you can also use recursion to fill the control. This removes the amount of duplicated code:
private void getMenu()
{
    DataSet ds = objSec.ShowMenu(s_UserId);
    DataTable dt = ds.Tables[0];
    AddMenuItems(dt, 0, menu.Items);
}

private void AddMenuItems(DataTable dt, int parentId, MenuItemCollection items)
{
    DataRow[] rows = dt.Select("ParentID=" + parentId.ToString());
    foreach(var dr in rows)
    {
        var id = (int) dr["MenuID"];
        var menuItem = new MenuItem(dr["MenuName"].ToString(), id.ToString(),
                                    "", dr["URL"].ToString());
        items.Add(menuItem);
        // Add subitems
        AddMenuItems(dt, id, menuItem.ChildItems);
    }
}

The sample first calls the AddMenuItems method for the top-level items (ParentID = 0). After each item is added, its children are added by calling the AddMenuItems method again (hence the term "recursive"), providing the id of the top-level item as parent. For each 2nd level child, the method is called again and so on.


text:
Q: Why anchors' position doesn't change after ARKit reconciling the recorded world map with the current environment? Environment: ARKit 2.0, iPhone X, iOS 12.1
While running an ARSeesion at the ARWorldMappingStatusMapped state,

*

*A few custom anchors at specified positions (#A) were added to the world map via ARSession.AddAnchor.

*The world map was saved to a file.

Then close the app and restart the ARSession,

*

*configuration Loaded the saved world map and assigned it to ARKitWorldTrackingSessionConfiguration.initialWorldMap

*run option reset tracking and remove existing anchors

*Then restart the session by calling ARSession.runWithConfiguration with the configuration and run option above.

*When the state of ARSession indicates that it has reconciled the recorded world map with the current environment, read the positions of anchors (#B) from ARWorldMap.anchors.

But I found that positions of read anchors (#B) are not changed compared to positions when they were saved (#A). That's incorrect. Why?
Because the initial position of the phone is the position of coordinate origin. And the app was once closed and the phone was moved to another place. So the position of coordinate origin changed after restarting the ARSeesion. Then ARSession should also reconcile the positions of ARAnchors saved in the world map to proper places, thus the positions of ARAnchors should have been changed.

A: From the initialWorldMap documentation:

If successful, the tracking state becomes ARCamera.TrackingState.normal after a short time, indicating that the current world coordinate system and anchors match those from the recorded world map.

The position of those anchors should be the same, however the origin of the world coordinate system should change after relocalization.

A: I found the cause. The initial session, whose initialWorldMap is nil and run option is 0, started after I restarted the session for reconciling. So it conflicted with the reconciling session. Which cancels reconciling. Thus the positions of loaded anchors will not change because they are unknown to the ARSession.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to use the "impersonate" function with a string (username) rather than intptr? The System.Security.Principal.WindowsIdentity.Impersonate function takes a System.intptr parameter, which seems awfully useless in my situation (with my limited understanding).
I am developing an intranet application that uses integrated security to authorize users page-by-page against a role associated with their Windows Identity.  I have no passwords or anything of the sort.  Simply a Windows username.  For testing purposes, how could I possibly impersonate a Windows user based on their username?  The "impersonate" method jumped out at me as obvious, but it takes an unexpected parameter.
Thanks in advance :)

A: In a nutshell, no.  But you are on the right track.  You either have to get the user by simulating a login with LoginUserA ( C Win32 Api ) or set your IIS site to Windows Authentication.
In that case, your Page will have a property named User of type IPrincipal, which you can then use to run as that user.  For example ( sorry, C# code ).
IPrincipal p = this.User;
WindowsIdentity id = (WindowsIdentity)p.Identity;
WindowsImpersonationContext wic = id.Impersonate();
try {
    // do stuff as that user
}
finally {
     wic.Undo();
}

A: Are you using anything windows-specific from the WindowsPrincipal or is it just a handy way to get auth/auth without having to manage users? If you need to be windows-based, Serapth has the right method. If you are just really using it as a convenient auth/auth store, then you should probably write your code to interface with IPrincipal. You can then inject your own implementations of IPrincipal with the desired values into either the HttpContext.User or Thread.CurrentThread.Principal depending on the nature of your tests and app.

A: User tokens (the value that the IntPtr in Impersonate represents) represent more than the username. They are a handle into an internal windows context that include information about the user, authentication tokens, current security rights, etc. It's because of this that you can't impersonate without a password. You have to actually "log in" to create a token via the LogonUser method.
What I've done in the past is create a special "Test" user account with a password that I can just keep in code or a config file.

A: You shouldn't need to impersonate to check role membership.  Simply use the constructor for a WindowsIdentity that takes a UPN (userPrincipalName) constructed from the username according to your UPN conventions, then create a WindowsPrincipal from that identity and use IsInRole to check membership in a group.  This works on W2K3 and a Windows 2003 domain, but not in other circumstances.
var userIdentity = new WindowsIdentity( username + "@domain" );
var principal = new WindowsPrincipal( userIdentity );
var inRole = principal.IsInRole( "roleName" );

You may also want to consider using either the standard or a custom role provider that will allow you to use the Roles interface to check membership.


text:
Q: Jquery Datatable drag and drop rows I implemented jquery datatables using
https://www.datatables.net/examples/api/select_row.html

Now I want to drag and drop rows.
I used jquery sortable and i did with normal table.
http://jsfiddle.net/mKaFe/126/

How can I implement that for jquery datatable.
Can it be achieved in jquery datatables?
Thanks in Advance


text:
Q: Insert linefeed in sed (Mac OS X) How do I insert a newline in the replacement part of sed?
This code isn't working:
sed "s/\(1234\)/\n\1/g" input.txt > output.txt

where input.txt is:
test1234foo123bar1234

and output.txt should be:
test
1234foo123bar
1234

but insted I get this:
testn1234foo123barn1234

NOTE:
This question is specifically about the Mac OS X version of "sed", and the community has noted that it behaves differently than, say, Linux versions.

A: The solaris version of sed I could convince to work this way (in bash):
echo test1234foo123bar1234 | sed 's/\(1234\)/\
\1/g'

(you have to put the line break directly after the backslash).
In csh I had to put one more backslash:
echo test1234foo123bar1234 | sed 's/\(1234\)/\\
\1/g'

The Gnu version of sed simply worked using \n:
echo test1234foo123bar1234 | sed 's/\(1234\)/\n\1/g'

A: Perl provides a richer "extended" regex syntax which is useful here:
perl -p -e 's/(?=1234)/\n/g'

means "substitute a newline for the zero-width match following the pattern 1234". This avoids having to capture and repeat part the expression with backreferences.

A: Your sed version apparently does not support \n in RHS (right-hand side of substitution). You should read THE SED FAQ maintained by Eric Pement to choose one of possible solutions. I suggest trying first inserting literal newline character.
Below is the quote from it.

4.1. How do I insert a newline into the RHS of a substitution?
Several versions of sed permit \n to be typed directly into the RHS, which is then converted to a newline on output: ssed, gsed302a+, gsed103 (with the -x switch), sed15+, sedmod, and UnixDOS sed. The easiest solution is to use one of these versions.
For other versions of sed, try one of the following:
(a) If typing the sed script from a Bourne shell, use one backslash \ if the script uses 'single quotes' or two backslashes \\ if the script requires "double quotes". In the example below, note that the leading > on the 2nd line is generated by the shell to prompt the user for more input. The user types in slash, single-quote, and then ENTER to terminate the command:
 [sh-prompt]$ echo twolines | sed 's/two/& new\
 >/'
 two new
 lines
 [bash-prompt]$

(b) Use a script file with one backslash \ in the script, immediately followed by a newline. This will embed a newline into the "replace" portion. Example:
 sed -f newline.sed files

 # newline.sed
 s/twolines/two new\
 lines/g

Some versions of sed may not need the trailing backslash. If so, remove it.
(c) Insert an unused character and pipe the output through tr:
 echo twolines | sed 's/two/& new=/' | tr "=" "\n"   # produces
 two new
 lines

(d) Use the G command:
G appends a newline, plus the contents of the hold space to the end of the pattern space. If the hold space is empty, a newline is appended anyway. The newline is stored in the pattern space as \n where it can be addressed by grouping \(...\) and moved in the RHS. Thus, to change the "twolines" example used earlier, the following script will work:
 sed '/twolines/{G;s/\(two\)\(lines\)\(\n\)/\1\3\2/;}'

(e) Inserting full lines, not breaking lines up:
If one is not changing lines but only inserting complete lines before or after a pattern, the procedure is much easier. Use the i (insert) or a (append) command, making the alterations by an external script. To insert This line is new BEFORE each line matching a regex:
 /RE/i This line is new               # HHsed, sedmod, gsed 3.02a
 /RE/{x;s/$/This line is new/;G;}     # other seds

The two examples above are intended as "one-line" commands entered from the console. If using a sed script, i\ immediately followed by a literal newline will work on all versions of sed. Furthermore, the command s/$/This line is new/ will only work if the hold space is already empty (which it is by default).
To append This line is new AFTER each line matching a regex:
 /RE/a This line is new               # HHsed, sedmod, gsed 3.02a
 /RE/{G;s/$/This line is new/;}       # other seds

To append 2 blank lines after each line matching a regex:
 /RE/{G;G;}                    # assumes the hold space is empty

To replace each line matching a regex with 5 blank lines:
 /RE/{s/.*//;G;G;G;G;}         # assumes the hold space is empty

(f) Use the y/// command if possible:
On some Unix versions of sed (not GNU sed!), though the s/// command won't accept \n in the RHS, the y/// command does. If your Unix sed supports it, a newline after aaa can be inserted this way (which is not portable to GNU sed or other seds):
 s/aaa/&~/; y/~/\n/;    # assuming no other '~' is on the line!

A: Get a GNU sed.
$ brew install gnu-sed

Then your command will work as expected:
$ gsed "s/\(1234\)/\n\1/g" input.txt
test
1234foo123bar
1234

nb: you may get GNU sed thanks to mac ports too.

A: Here's a single-line solution that works with any POSIX-compatible sed (including the FreeBSD version on macOS), assuming your shell is bash or ksh or zsh:
sed 's/\(1234\)/\'$'\n''\1/g' <<<'test1234foo123bar1234'

Note that you could use a single ANSI C-quoted string as the entire sed script, sed $'...' <<<, but that would necessitate \-escaping all \ instances (doubling them), which is quite cumbersome and hinders readability, as evidenced by @tovk's answer).

*

*$'\n' represents a newline and is an instance of ANSI C quoting, which allows you to create strings with control-character escape sequences.

*The above splices the ANSI C-quoted string into the sed script as follows:

*

*The script is simply broken into 2 single-quoted strings, with the ANSI C-quoted string stuck between the two halves:

*'s/\(1234\)/\' is the 1st half - note that it ends in \, so as to escape the newline that will be inserted as the next char. (this escaping is necessary to mark the newline as part of the replacement string rather than being interpreted as the end of the command).

*$'\n' is the ANSI C-quoted representation of a newline character, which the shell expands to an actual newline before passing the script to sed.

*'\1/g' is the 2nd half.

Note that this solution works analogously for other control characters, such as $'\t' to represent a tab character.

Background info:

*

*The POSIX sed specification: http://man.cx/sed

*

*BSD sed  (also used on macOS) stays close to this spec, while GNU sed offers many extensions.

*A summary of the differences between GNU sed and BSD sed can be found at https://stackoverflow.com/a/24276470/45375

A: Unfortunately, for me, sed seems to ignore \ns in the replacement string.
$ echo test1234foo123bar1234 | sed "s/\(1234\)/\n\1/g"
testn1234foo123barn1234

If that happens for you as well, an alternative is to use:
$ echo test1234foo123bar1234 | sed "s/\(1234\)/\\`echo -e '\n\r'`\1/g"

This should work anywhere and will produce:
test
1234foo123bar
1234

For your example with an input.txt file as input and output.txt as output, use:
$ sed "s/\(1234\)/\\`echo -e '\n\r'`\1/g" input.txt > output.txt

A: Try this:
$ echo test1234foo123bar1234 | sed "s/\(1234\)/\n\1/g"
test
1234foo123bar
1234

From Sed Gnu doc
g
    Apply the replacement to all matches to the regexp, not just the first.

A: You may also use the $'string' feature of Bash:
man bash | less -p "\\$'"

printf  '%s' 'test1234foo123bar1234'  | sed $'s/\\(1234\\)/\\\n\\1/g'

A: The newline in the middle of the command can feel a bit clumsy:
$ echo abc | sed 's/b/\
/'
a
c

Here are two solutions to this problem which I think should be quite portable
(should work for any POSIX-compliant sh, printf, and sed):
Solution 1:
Remember to escape any \ and % characters for printf here:
$ echo abc | sed "$(printf 's/b/\\\n/')"
a
c

To avoid the need for escaping \ and % characters for printf:
$ echo abc | sed "$(printf '%s\n%s' 's/b/\' '/')"
a
c

Solution 2:
Make a variable containing a newline like this:
newline="$(printf '\nx')"; newline="${newline%x}"

Or like this:
newline='
'

Then use it like this:
$ echo abc | sed "s/b/\\${newline}/"
a
c


text:
Q: How to save results on multiple tables? I'm trying to save an exam for each course and here is what I've tried. The error that I'm getting is error page 404 is not found and also the data is not saving in the db.
Here is my controller
public function exam($course_id, Request $id)
        {
            $course = Course::where('id', $id)->firstOrFail();
            $answers = [];
            $exam_result = 0;
            foreach ($request->get('question') as $question_id => $answer_id) {
                $question = ExamQuestion::find($question_id);
                $correct_answer = ExamOption::where('exam_questions_id', $question_id)
                    ->where('id', $answer_id)
                    ->where('is_correct', 1)->count() > 0;
                $answers[] = [
                  //this comes from the exam_results_answers
                    'exam_question_id   ' => $question_id,
                    'exam_option_id' => $answer_id,
                    'corect' => $correct_answer
                ];
                if ($correct_answer) {
                    $exam_result += $question->score;
                }
            }
            //this comes from exam result and is correct
            $exam_result = ExamResult::create([
                'exam_id' => $course->exam->id,
                'employee_id' => \Auth::id(),
                'result' => $exam_result
            ]);
            $exam_result->answers()->createMany($answers);
            return redirect()->route('learn.show', [$course->curriculum_id, $id])->with('message', 'Test score: ' . $exam_resut);
        }

Here is the blade
<form action="{{ route('exam.save', [$courses->id]) }}" method="post">
              {{ csrf_field() }}

                @foreach($courses->exam->question as $question)

{{$loop->iteration}} . {{$question->question}}

                @foreach($question->exam_options as $option)
                 <input type="radio" name="question[{{ $question->id }}]" value="{{ $option->id }}"/>  {{ $option->text }}

                @endforeach

                @endforeach

                 <input type="submit" value=" Submit results " />
               </form>

Here are the routes
  Route::get('/exam/{id}', 'EmployeeCoursesController@view_exam')->name('exam.show');
Route::post('/exam/{id}', 'EmployeeCoursesController@exam')->name('exam.save');

A: Looking at the parameters in your exam() function, I believe this line:
$course = Course::where('id', $id)->firstOrFail();

Should actually be:
$course = Course::where('id', $course_id)->firstOrFail();

firstOrFail() will throw a 404 if it does not resolve a model from the database.


text:
Q: Is regex for Hive different from the normal regex? I am using Hive to analyse a web log that looks like this
415503 - - [10/Jun/1998:00:48:00 +0000] "GET /english/images/nav_sitemap_off.gif HTTP/1.1" 200 416

I used the regex below to load this to the hive table which works fine
([^ ]*) ([^ ]*) ([^ ]*) (-|\\[[^\\]]*\\]) ([^ \"]*|\"[^\"]*\") (-|[0-9]*) (-|[0-9]*)

But if i check for this regex in https://www.regex101.com/, this regex doesn't match with my string.
If i remove some backslashes in the block
(-|\\[[^\\]]*\\])

it is validated.
I think we have to put \ to escape strings when i comes to regex in Hive? But how do i validate this before creating the database?

A: Hive uses Java regex syntax. Try http://www.fileformat.info/tool/regex.htm for testing purposes.
see Apache Hive - REGEXColumnSpecification for details.


text:
Q: How two different elements belong to a polynomial implies the polynomial is a proper ideal? This is an example from Galois Theory.

If F is a field, then a nonzero polynomial p(x) ∈ F[x] is irreducible
  if and only if (p(x)) is a prime ideal.
proof:
Suppose p(x) is irreducible.
If ab ∈ p, then p | ab
Euclid's lemma implies that p | a or p | b.
Thus, a ∈ (p) or b ∈ (p).
Finally, p is a proper ideal.

I'm ok with the prove till a ∈ (p) or b ∈ (p).
But then why p is a proper ideal? The question only give us p(x) is a polynomial in a field.

A: If $p$ is irreducible, then by definition it is not a unit, so $1\not\in (p)$ and $(p)$ is a proper ideal.

A: Your proof is making me nervous.  Irreducible usually means a non-unit $p$ with $p=ab \Rightarrow a\in U(R)$ or $b \in U(R)$ (for integeral domains).  Prime is a non-unit with $p\mid ab \Rightarrow p\mid a$ or $p \mid b$.  Euclid's lemma is for primes rather than irreducibles usually, but since the integers are a PID they are equivalent, so it is not that big of a deal, but outside of the integers, this causes some confusion I think.  Your use of Euclid's lemma seems to be essentially already assuming $p(x)$ is prime rather than irreducible.
Polynomial rings over a field are Euclidean Domains which are PIDs which are UFDs.  Even in a UFD, irreducible implies prime, but here I think the PID proof of irreducible implying prime is worth mentioning.
You can actually show if $p(x)$ is irreducible, then $(p(x))$ is maximal and hence prime.  Suppose $(p(x)) \subseteq I \subseteq F[x]$ with $p(x)$ irreducible.  Since $F[x]$ is a PID, $I=(f(x))$ for some $f(x)$.  But $p(x) \in I$, so $p(x)=f(x)g(x)$ for some $g(x)$.  Since $p(x)$ is irreducible, either $f(x)$ is a unit or $g(x)$ is a unit.  If $f(x)$ is a unit, then $I=(f(x))=F[x]$ since any ideal containing a unit, must be the whole ring.  If $g(x)$ is a unit, then $(p(x))=(f(x))$.  This shows $(p(x))$ is maximal.


text:
Q: Laravel Symbolic Link in Shared hosting problem I am using shared hosting.
I have installed my laravel application and i am using unisharp Laravel File Manager.
With the manager, I uploaded file "happy.jpg". it produced url "http://unpluggedworldofmine.com/storage/photos/1/happy.jpg" but i cannot access to the file.
instead, when i use
"http://unpluggedworldofmine.com//storage/app/public/photos/1/happy.jpg", i can see that i has been uploaded properly.
it looks like there is problem with .htaccess
RewriteEngine on

RewriteRule ^/?$ /public/ [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*) /public/$1 [L]

AS i am using shared hosting, i cannot change configuration in httd or others.
i used
php artisan storage:link

to set up link.
can anyone help me with this?
Thanks


text:
Q: Trouble adding and populating field on the fly in ESRI feature layer I'm trying to build a mashup consisting of a Census tiger web feature layer, and some JSON. I want to make a map of the feature layer, then add a new field to the layer, and populate from the JSON. Here is the url to the feature layer:
https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2015/MapServer/82
My JSON data is a simple array of objects:
   var data =  [{"P0010001":"4779736","P0050010":"185602","NAME":"Alabama","state":"01"},{"P0010001":"710231","P0050010":"39249","NAME":"Alaska","state":"02"},...]

I then start my webmap, etc:
require([stuff],function(stuff){
    var map = new Map...
    var featurelayer = new FeatureLayer etc
    map.addLayer(featurelayer);
});

Then below this I try to add a field to the layer, and populate with JSON. Here's what i've tried:
for(var i = 0; i < layer.graphics.length; i++)
                            {
                                for(var j = 0; j < new_data.length; j++)
                                {
                                    if(layer.graphics[i].attributes.STATEFP == new_data[j].state)
                                    {
                                        layer.graphics[i].attributes.NEWFIELD = new_data[j].P0010001;
                                    }
                                }
                            }

But this didn't work. I tried logging Object.keys(layer) and got a long list of keys, of which one is graphics, however, graphics doesn't seem to have any information with it.
I also tried calling map.redraw() after the loop, but that didn't help. There is an example similar to what I'm trying to do here: http://cartographicperspectives.org/index.php/journal/article/viewFile/cp76-hunt/1311 and they use arr.forEach, which is apparaenlty part of dojo?? I'm trying to accomplish the join using vanilla js.
So I also tried the layer.attr() method in the ESRI api. Since its a layer method I assume I need an array of graphics to use it. But when I call console.log(layer.graphics.length) i get 0.
So is it possible to programmatically add a field, and do a join such as this to a feature layer? I.e. add a field and populate it from JSON?

A: I think you're close, just a few notes about what you need to do to get this working:

*

*The major note is that you need to wrap your code that looks at the attributes in on on event handler, so you're waiting until the layer's data is actually loaded before you try to change it.

*I could not find STATEFP in your service ... looks like STATE is what you want.

*Just a note that you have to include outFields: '*' (or at least all the fields you want to check against) when doing this type of looping. If not, your layer.graphics[i].attributes.STATE will never be found

I have all of the above incorporated into a sample. You can see it working by clicking on Alabama or Alaska and see your "NEWFIELD" in the list:
https://jsfiddle.net/gavinr/cgsken5y/


text:
Q: Android cannot resolve R error and Some file crunching failed error for images
Error:Execution failed for task ':app:mergeDebugResources'.

Some file crunching failed, see logs for details

and other logs:

:app:clean :app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE
  :app:checkDebugManifest :app:preReleaseBuild UP-TO-DATE
  :app:prepareComAndroidSupportAnimatedVectorDrawable2340Library
  :app:prepareComAndroidSupportAppcompatV72340Library
  :app:prepareComAndroidSupportSupportV42340Library
  :app:prepareComAndroidSupportSupportVectorDrawable2340Library
  :app:prepareDebugDependencies :app:compileDebugAidl
  :app:compileDebugRenderscript :app:generateDebugBuildConfig
  :app:mergeDebugShaders :app:compileDebugShaders
  :app:generateDebugAssets :app:mergeDebugAssets
  :app:generateDebugResValues UP-TO-DATE :app:generateDebugResources
  :app:mergeDebugResources AAPT err(Facade for 4833051): libpng error:
  Not a PNG file AAPT err(Facade for 4833051): libpng error: Not a PNG
  file AAPT err(Facade for 16006587): libpng error: Not a PNG file

I have those images now:
b3_1.jpg
b3_3.jpg
giphy.gif
ic_back.png
ic_forward.png
ic_launcher.png
ic_mainactivity_logout.png
ic_mainactivity_result.png
img_mainactivity_background_placeholderimg.jpg
s.png

I tried to change all image names to good ones.
I put ic_ to the beginning, can it be problem? I wanted to make them icon. They are already in use also.
I changed one or two images with jpg to png, with refactor. Can it be reason?
Now R class seems unimported. I did not change anything. I only rebulded cleaned after all tries.

A: When packing your resources, Gradle has detected that one of your PNG images is not a PNG, it's probably a JPG or GIF with the wrong extension.
As you have very few images, try to locate the offending file and rename it appropriately.
"refactoring" a image file does not change its structure, just the name. If you want to convert a JPG to a PNG you must use an external tool.


text:
Q: Requiring an annotation field when some other field has a specific value If I have a field annotation defined as such:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface  LineField {
    public int at();
    public int length();
    public String literal() default "[unassigned]";
    public boolean isId() default false;

}

Is it possible in the api itself to have 'literal' be non-optional when  'isId' is set as true,
example :
//Valid
    @LineField(at = 0, length = 1, isId = true, literal = "6")
    private String recordTypeCode;

//Invalid
      @LineField(at = 0, length = 1, isId = true)
    private String recordTypeCode;


text:
Q: Working Directory for local github actions in subdirectory I'm trying to keep multiple github actions in the same monorepo using subdirectories, and run them like:
workflow.yml
// [...]
jobs:
  run_my_script:
    runs-on: ubuntu-latest
    steps:
      - name: Check out current repo
        uses: actions/checkout@v2
      - uses: ./my_action2
        with:
          my_input_var: "david"

./my_action2/action.yml
// [...]
runs:
  using: "composite"
  steps:
    # Checkout files in this repo
    - name: Checkout
      uses: actions/checkout@v1

    - name: Run myscript
      run: python myscript.py "${{ inputs.my_input_var }}" # location: ./my_action2/myscript.py
      shell: bash

The problem I'm having is that my action uses a python script in it's subdirectory, but the uses: action appears to run from the GITHUB_WORKING_DIR of the workflow and not the directory of the action itself.
python: can't open file 'myscript.py': [Errno 2] No such file or directory

I've looked through most of the working-directory questions surrounding github actions, but I'm still stumped.
I've also tried adding working-directory: ./my_action2 to the job's defaults: but it looks like it's not propagating to run: commands within the uses: step.
My workaround in the meantime has been to add an input for myaction2_working_directory in the workflow, and then add working-directory: ${{ inputs.myaction2_working_directory }} to every run: command in the action. This seems inelegant and repetitive. Is there a better way to do this?

A: I had similar problem and for my composite actions I just added a first step as:
run: cd  ${{ inputs.working_directory }}
and then all next steps are running in it.
I couldn't find a better way and having working-directory copy pasted was also something I didn't like.

A: contrary to the answer by Grzegorz, you cannot just run: cd foo and then expect all following steps to have a working directory of foo.  as far as i can tell, the only way to do this is with the "workaround" the OP already posted -- add an input named e.g. working-directory to your action and then add working-directory: ${{ inputs.working-directory }} to every step.  see https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#runsstepsworking-directory


text:
Q: Is this process possible with an excel formula I'm trying to create a sort of excel formula
1.) Go within a Table
2.) Identify all rows that contain "Specific first name" & " Specific last name"
3.) Then, from those previously identified rows, identify if those rows also contain "Dental"
4.) If the row does contain "Dental" take the appropriate cell in THAT row that contains the dental amount, ( because the dental amount is not the cell directly after/to the right of the the cell that contains dental.
First name and last name will be cell references.
If I can create this formula, I plan to create a Macro that places this formula in the proper cells

A: Here/screenshot(s) refer:
<Response structured as follows: M1(a/b) sum/count followed by M2 (sum/count resp.).

M1 -- utilises 'Filter approach' recommended in commentary (@Tragamor) - will explore this first - per screenshot, M1 (cell O6):
NB: requires Office 365 compatible version of Excel (see M2 for different approach in this regard)...

=LET(q_,FILTER(Table1,--ISNUMBER(MATCH("*"&Table1[Fld0_type]&"*",Table3[Dental assoc.],0))*ISNUMBER(MATCH("*"&Table1[Fld2_Name]&"*",Table2[Names],0))),COUNT(INDEX(q_,,MATCH("*"&"cost"&"*",Table1[#Headers],0))))

Noting length may seem cumbersome but mainly attributable to field/table referencing preferences/convention (and dynamism)
Analogous count (P6) is provided for on similar basis/formulation:
**note omission RE: index 'row' argument -- purposeful as this (or 0 for that matter) generally returns all rows from data in question.

=LET(q_,FILTER(Table1,--ISNUMBER(MATCH("*"&Table1[Fld0_type]&"*",Table3[Dental assoc.],0))*ISNUMBER(MATCH("*"&Table1[Fld2_Name]&"*", Table2[Names],0))),COUNT(1*ISNUMBER(INDEX(q_,,MATCH("*"&"cost"&"*",Table1[#Headers],0)))))

M1(b) - outside of scope per commentary provided (screenshot above).

M2 - Absconds from filter method (CELL o8 as in 'oscar 8'):

=SUM(Table1[Fld 3_cost]*ISNUMBER(MATCH("*"&Table1[Fld0_type]&"*",Table3[Dental assoc.],0))*(ISNUMBER(MATCH(Table1[Fld2_Name],Table2[Names],0))))

Likewise, we have analogous 'count' record (cell p10):

=COUNT(1*(Table1[Fld 3_cost]*ISNUMBER(MATCH("*"&Table1[Fld0_type]&"*",Table3[Dental assoc.],0))*(ISNUMBER(MATCH(Table1[Fld2_Name],Table2[Names],0)))))

Notes:
Wildcard '*' in match functions (i.e. 'Tom' will match with Tomas (weird spelling for that name, normally has 'h' in it but all the same☺)


text:
Q: const Class * const Function() What does the second const do? What does the second const do in the structure below? (it's just an example function).
I understand that the first const makes the function return a constant object. But I can't figure out what the const before the identifier does.
First I though that it returned a constant pointer to a constant object, but I'm still able to reassign the returned pointer, so I guess that isn't the case.
const SimpleClass * const Myfunction()
{
   SimpleClass * sc;
   return sc;
}

A: const SimpleClass * const Myfunction()
{
    return sc;
}

decltype(auto) p = Myfunction();
p = nullptr; // error due to the second const.

But the truth is that not many people uses decltype(auto), and your function will be normally called like:
const SimpleClass *p = Myfunction();
p = nullptr; // success, you are not required to specify the second const.

const auto* p = Myfunction();
p = nullptr; // success, again: we are not required to specify the second const.

And...
const SimpleClass * const p = Myfunction();
p = nullptr; // error

const auto* const p = Myfunction();
p = nullptr; // error

A: Second const means that returned pointer is constant itself whereas first const means that memory is unmodifiable.
Returned pointer is temporary value (rvalue). That's why it doesn't matter whether it's const or not since it cannot be modified anyway: Myfunction()++; is wrong. One way to "feel" second const is to use decltype(auto) p = Myfunction(); and try to modify p as José pointed out.
You might be interested in Purpose of returning by const value? and What are the use cases for having a function return by const value for non-builtin type?


text:
Q: Delete an Alarm using AlarmManager.cancel() not working I'm trying to cancel an Alarm using AlarmManager.cancel() but apparently it is not working. I've read somewhere that I have to use PendingIntent.FLAG_UPDATE_CURRENT which as seen on the code, is what I used. In setting the alarm, I want the program to set an alarm automatically using code, hence the code below.
setAlarm Function:
public void setAlarm(DateTime date, String message) {
        Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
        i.putExtra(AlarmClock.EXTRA_MESSAGE, message);
        i.putExtra(AlarmClock.EXTRA_HOUR, date.getHourOfDay());
        i.putExtra(AlarmClock.EXTRA_MINUTES, date.getMinuteOfHour());
        i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
        PendingIntent pendingIntent = PendingIntent.getActivity(appContext.getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager manager = (AlarmManager) appContext.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);
        return;
    }

cancelAlarm Function:
public void cancelAlarm(DateTime date, String message) {
        Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
        i.putExtra(AlarmClock.EXTRA_MESSAGE, message);
        i.putExtra(AlarmClock.EXTRA_HOUR, date.getHourOfDay());
        i.putExtra(AlarmClock.EXTRA_MINUTES, date.getMinuteOfHour());
        i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
        PendingIntent pendingIntent = PendingIntent.getActivity(appContext.getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager manager = (AlarmManager) appContext.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        manager.cancel(pendingIntent);
        return;
    }

Any ideas? I'm at my wit's end. Thanks in advance!

A: When you set the alarm you do this:
manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);

This sets the alarm to go off at System.currentTimeMillis(), which will make the alarm go off immediately. Your call to cancel the alarm doesn't work because by the time you make the call to cancel, the alarm has already gone off and doesn't exist anymore.


text:
Q: SELECT TableName.Col1 VS SELECT Col1 This might be a weird question but didnt know how to research on it. When doing the following query:
  SELECT Foo.col1, Foo.col2, Foo.col3
  FROM Foo
  INNER JOIN Bar ON Foo.ID = Bar.BID

I tend to use TableName.Column instead of just col1, col2, col3
Is there any performance difference? Is it faster to specify Table name for each column?
My guess would be that yes it is faster since it would take some time to lookup the column name and and differentiate it.
If anyone knows a link where I could read up on this I would be grateful. I did not even know how to title this question better since not sure how to search on it.

A: First of all: This should not matter. The time to look up the columns is such a miniscule fraction of the total processing time of a typical query, that this might be the wrong spot to look for additional performance.
Second: Tablename.Colname is faster than Colname only, as it eliminates the need to search the referenced tables (and table-like structures like views and subqueries) for a fitting column. Again: The difference is inside the statistical noise.
Third: Using Tablename.Colname is a good idea, but for other reasons: If you use Colname only, and one of the tables in your query gets a new column with the same name, you end up with the oh-so-well-known "ambiguous column name" error. Typical candidates for such a columns often are "comment", "lastchanged", and friends. If you qualify your col references, this maintainability problem simply disappears - your query will work as allways, ignoring the new fields.

A: If it's faster, the difference is surely negligible, like a few microseconds per query. All the data about the tables mentioned in the query has to be loaded into memory, so it doesn't save any disk access. It's done during query parsing, not during data processing. Even if you run the query thousands of times, it might not make up for the time spent typing those extra characters, and certainly not the time we've spent discussing it. :)
But it makes the queries longer, so there's slightly more time spent in communications. If you're sending the query over a network, that will probably negate any time saved during parsing. You can reduce this by using short table aliases, though:
SELECT t.col1, t.col2
FROM ReallyLongTableName t

As a general rule, when worrying about database performance you only need to concern yourself with aspects whose time is dependent on the size number of rows in the tables. Anything that's the same regardless of the amount of data will fall into the noise, unless you're dealing with extremely tiny tables (in which case, why are you bothering with a database -- use a flat file).


text:
Q: ValueError: shapes (20,1) and (2,1) not aligned: 1 (dim 1) != 2 (dim 0) I am a bit new to machine learning and am trying to do linear regression without using linear_model.LinearRegression() via sklearn. I think I am nearing the end of my coding and getting prepared to plot the line but I am getting the error "ValueError: shapes (20,1) and (2,1) not aligned: 1 (dim 1) != 2 (dim 0)". I printed out my 20 by 1 matrices to confirm and neither of them have any extra dimensions or anything so I'm not sure why it is giving me (2,1) in the error message or why the dimensions don't match up. Does anyone have any recommendations on how to "align" these matrices? I am using Python 3.5.1.
Edit:
I have looked at a lot of the other ValueError topics in stackoverflow but I am having trouble really understanding the recommendations. If possible, laymen's terms would be greatly appreciated.
Per Georgy I narrowed the code down to just the lines of code needed to cause the error message. alpha, iters, and theta were left alone to show all the variables required to be passed into the functions.
Edit 2: Alright, attempt 2 to reduce the example code. Thank you for working with me on this. I put a try-except statement around this line of code:
theta = theta -(alpha/len(X)) * np.sum((X @ theta.T - y) * X, axis=0)

Said line is nestled in a for loop using i as the variable. Said line is giving me the following error:
Traceback (most recent call last):
  File "C:\Users\YungL\Desktop\linearRegression.py", line 30, in <module>
    slope_and_intercept, cost = gradDescent(X_test, Y_test, theta, alpha, iters)
  File "C:\Users\YungL\Desktop\linearRegression.py", line 26, in gradDescent
    theta = theta -(alpha/len(X)) * np.sum((X @ theta.T - y) * X, axis=0)
ValueError: shapes (20,1) and (2,1) not aligned: 1 (dim 1) != 2 (dim 0)

Printing X[i], y[i], and theta when the exception is thrown gives me this respectively:
[[ 0.07786339]    [[233.]    [[1. 1.]]

Column 1 being X, column 2 being y, and column 3 being theta. Referencing the matrices, these are the 1st values in each matrix. Although for theta, that is the only value.
Here is the complete matrix of X and y at the time of the exception:
[[ 0.07786339]    [[233.]
 [-0.03961813]    [ 91.]
 [ 0.01103904]    [111.]
 [-0.04069594]    [152.]
 [-0.03422907]    [120.]
 [ 0.00564998]    [ 67.]
 [ 0.08864151]    [310.]
 [-0.03315126]    [ 94.]
 [-0.05686312]    [183.]
 [-0.03099563]    [ 66.]
 [ 0.05522933]    [173.]
 [-0.06009656]    [ 72.]
 [ 0.00133873]    [ 49.]
 [-0.02345095]    [ 64.]
 [-0.07410811]    [ 48.]
 [ 0.01966154]    [178.]
 [-0.01590626]    [104.]
 [-0.01590626]    [132.]
 [ 0.03906215]    [220.]
 [-0.0730303 ]]   [ 57.]]

A: For matrix multiplication (which is what the @ operator does), you need the inner dimensions of the matrices in question to match. That is, you can multiply a 20 x 1 matrix by a 1 x 2 matrix, but not by a 2 x 1 matrix. This is not a numpy specific thing, it's just a basic fact of matrix arithmetic.
The issue you have is that X @ theta.T in your code is resulting in mismatched dimensions. I don't know what those variables represent (and you've edited the question to take out where they come from), but given the error, you probably want X @ theta instead. That will do the 20 x 1 and 1 x 2 multiplication, rather than the 2 x 1 multiplication that doesn't work mathematically.


text:
Q: how to capture the java version on linux machine how to capture the java version on linux redhat machine
we tried that:
java -version | head -1 | awk '{print $NF}' | sed 's/"//g'

but we get
openjdk version "1.8.0_65"
OpenJDK Runtime Environment (build 1.8.0_65-b17)
OpenJDK 64-Bit Server VM (build 25.65-b01, mixed mode)

while expected output should be
1.8.0_65

A: java -version outputs to its standard error, so you need to redirect that:
java -version 2>&1 | head -1 | awk '{print $NF}' | sed 's/"//g'

You can do this with a single AWK invocation:
java -version 2>&1 | awk 'NR==1 {gsub("\"", "", $NF); print $NF}'


text:
Q: Third party WPF controls: Devexpress vs Telerik I would like to hear your opinion about the two control providers.
To put it in a nutshell: I am building a classic LOB desktop application. The app will be created entirely in WPF. PRISM 4.0 will be used heavily. Whenever possible, I will try to follow MVVM pattern(it would be nice if the selected controls were designed to adopt it easily).
Mainly I am interested in:

*

*Good data grid, which supports sorting, filtering,  grouping,
exporting, printing and works fine
with a big amount of bound
records(10k+)
Combobox that supports filtering and auto-complete.
Navigation bar
Layout manager that is similar to the one that is used VS 2010
In a long term, I would also like to use their:

*

*Report tools
"Data mining" controls
Localization support in order to localize data grid actions for instance,..
I have been using Winforms Devxpress for a while and I was quite satisfied. Their support team is great. Still, I want to check if there is any better option on the market. In other words, I would like to know if Telerik's controls have any additional value?

A: I evaluated several WPF control packages,  Telerik, devExpress,  Xceed, SyncFusion, etc.  We were primarily interested in a grid control that could handle a large amount of data and have good performance.   In a simple test, we loaded 120,000 items into the grid and did a group on the fields.
DevExpress was the fasting loading compared to the others.  It took 15 secs to load, while the others where all about 45 seconds.  DV would group in 7 seconds, while the others took nearly 45 seconds.  A couple of the other controls packages locked up!  (fyi, the data was being loaded from Mongo).
When bringing up the filter dialog for a column on Telerik, it would extend beyond the bottom of the screen without any scrollbar. Also, cicking on a filter item in the dropdown combo would immediately do the filter then rather than waiting for me to select the others.  Therefore, if selecting 5 items, it would take 5 times as long.
I wish DevExpress would have a checkbox dropdown filter option (like Excel).  You can only select a single value, but it does have a very nice filter dialog that allows you to do more complex filters.  Still, would like to be able to easily check a few values and move on quickly.
Telerik integrated nicely with Sql Server using Entity Framework. It's paging, sorting, filtering, etc. integrated directly with EF and had Sql Server do these operations at the database.  Very nice! I monitored the sql commands as doing operations.  It you are viewing large amounts of data on sql server, this may be the one control that really does this well.  (Except for the dropdown filter combo that does not handle large data very well).  We are using Mongo for our large data, so this did not apply to us.  We did have a few exceptions with Telerik when testing data. DevExpress does not have a paging option unless you it yourself.
In the end we chose DV due to performance reasons with large data and stability.

A: I would definitely go for DevExpress, their components are in my opinion nicer and with better APIs than Telerik ones, then let's don't forget you already know their object model, naming conventions and APIs from the windows forms world, this is not a minor thing because you will most likely reuse your know-how and this is far more important and valuable.

A: The Telerik RadDataGrid supports MVVM and the command pattern properly straight out of the box.  The DevExpress one requires a lot of extra code before you can use MVVM with it properly.

A: DevExpress WPF is slow and not optimized performance wise. I've tried rich text edit control of both DevExpress and Telerik. Telerik control outperforms DevExpress in terms of performance.

A: I am using Telerik and DEVExpress both. Based on my experience, DevExpress is better in win form controls. But, Telerik is more better than in Asp.NET controls.
DevExpress rendering result on the server controls are very messy in client site. They create button control using the table tag.

A: I was exactly in the same position few months ago when evaluating WPF controls for a new WPF project. I'm not sure if you have made any decision, but I can offer my experiences with Telerik and hope it helps.
In my project, one particular need was to use TreeListView and there were limited reputed vendors provided this control. I spent some time doing researches and found Telerik which offered for what I needed. I downloaded the trial and used it for 2 months, contacted their support, checked their forums. I can tell you that they have excellent supports! Usually the supports provided solution with sample codes. Like all developers, we would encounter roadblock, we studied the API, documentations, and examples. For me, support is important as it saves development time! My feedback is Telerik provides great UI controls with vast collection and customization choices, and great technical supports. However, their documentation isn't so good. Also, watch out performance in WPF controls, my experience is it has some performance hit if you have large data source. Be sure to do some prototypes in critical architectural areas if performance is the key requirements.
Just give it a try and see if it meets your needs or not.
BTW, I'm also ComponentOne customer. Just get the controls for what you need if it can save you time. The important thing is which helps ship your product on time! Hope this helps.

A: I'd take telerik hands down...#1 reason being support, #2 reason is that if the control can't do what you need you just need to put in a ticket or post to the support forums and you can DRIVE their feature development.
...pretty cool :)

A: We had to make a quite similiar decision a few months ago. We were using WinForms, the Microsoft Composite UI Application Block and DevExpress WinForms. For our new application, created new from scratch, we decided to use WPF (without PRISM) and we were especially in need of some grids, so we used DevExpress WPF Controls.
This was imho a good and a bad decision.
The good part:

*

*You can use the controls in a very similiar way you are used to. There are some differences, but you get used to them quickly. This is a huge plus, because it took us quite some time to get used to them while using the WinForm controls.

*The controls, especially the grids, are useable as the WinForms controls. If your users are used to them, the transition is very smooth.

*Applying one of the provided themes is very simple and you get a good looking solution without much annoyance. They apply to pure WPF controls, too, so the whole application looks consistent. We are still using mostly Windows XP, the themes apply to this as well, which is exceptional useful for us.
The bad part:

*

*We expected the DevExpress WPF controls to provide the same control coverage as the WinForm controls did. The DevExpress WPF controls at that time had version number 10.1, and we were disappointed that some controls were missing completely (for example TreeList, Schedulers, Passwordbox or the very useful LookUpEdit). While the later three are available with version 10.2, TreeLists still aren't there. If you are looking for additional controls from the WinForms package than the ones listed, it is a good idea to check if they exist for the DX WPF controls first.

*Some parts made the impression that they were done quickly. There were some quickfixes neccessary to get the controls running the way we intended to use them. The good thing is that most of these problems are solved with 10.2.

*The documentation and the support center for the WPF controls feels less complete than the WinForms documentation. While this is probably just my personal impression, I was almost always able to find an answer to a certain problem I had with the WinForms controls on the DX website, I'm not that succesful with the WPF controls. The support team is as helpful as always, though.
This list is not intended to be exhaustive, those were the things that immediately came to my mind.
So, what would I do if I had to do the same decision again? I would very likely use DevExpress again. Most negative things that bugged me were fixed with version 10.2, so the controls are quite usable now. I especially like that you can use your former experience with the WinForm controls (with limitations, of course). The later was also the primary reason for buying the DX components. Unfortunately, I don't know the Telerik controls enough to say anything about them, so if someone has experience with both, especially with switching from DX to Telerik that would surely be a very interesting information.
We're not using the MVVM pattern with our grids, as the "traditional" way of loading and displying data is sufficient enough for us. Some of our grids contain 100k+ values, the performance of the grid is imho always ok. The controls disn't look like they had a build in support for MVVM, if you're trying to use it it looks like you have to do everything manually. Maybe 10.2 changed things here, I haven't checked, but I don't think so.
We used our own implementation for localisation, so I don't know about the DX localization support.

A: I believe devexpress is realy beter in WinFormApp. I'm using it for several years it's really nice.
On the other hand recently I'h tried its WPF controls, It's terrible and full of bag I don't have time to switch to telerik for this project.
Another problem that I had with devex is RTL. If You want to have a multi language app It can be important.
Telerik can support RTL But Devex don't Support it in WinApp and in WPF in Devex don't supported it completely.
AS I said devex is better in WinApp without RTL.

A: From my point of view DevExpress provides some what  light weight controlls compare to Telerik. Reporting using DevExpress is more flexible. But at the same time Telerik having a better look and feel comapre to another tools.

A: I have a friend that uses Telerik controls and he absolutely swears by them.  He specifically mentioned how their data grid control is the greatest thing since sliced bread and uses all the time (which might help you out based on your first bullet point).
Again, not firsthand experience, but I trust his opinions on these kind of things.

A: have not tried DevExpress, but I use Telerik for WPF it has some good components the Gridview for example. but other components are full of bugs example a simple dockcontrol to this day they have not managed to get it to work properly.

A: I used both telerik wpf radcontrols and the devexpress ! From my experience i was satisfied with telerik controls as my main objective was to be more productive and deliver a desktop application with a good UX in a short time ! Telerik make heavy use of the mvvm pattern and recommend using it as most of their demos are based on it ! As for documentation looking at the demos source code was enough for me to have a quick start ! On the other hand devexpress is more mature. in other words, telerik contains bugs but The support will always find a workaround for you  if you ask.


text:
Q: Dart, Only static members can be accessed in initializers in simple class example In this code below,
class SimpleClass {
  final String ID;

  BusInformationScreen({this.ID});

  var output = ID;
}

I got an error
Only static members can be accessed in initializers.
so i adjusted code like this below.
class SimpleClass {
  static final String ID;

  var output = ID;
}

I thought if i declare ID as a static, It doesn't have to initialize it but i got an error like this.
The final variable 'ID' must be initialized.

What is the reason that i couldn't declare variable output?

class SimpleClass {
  final String ID;
  final String output;
  SimpleClass_2 simpleclass_2 = SimpleClass_2(parameter: ID), SimpleClass_2 simpleclass_2 = SimpleClass_2(parameter: ID);

  SimpleClass({this.ID}): output = ID;
}

class SimpleClass_2 {
  final parameter;

  SimpleClass_2({
    this.parameter
  });
}

A: (I'm gonna assume BusInformationScreen is supposed to be the constructor for SimpleClass )
The problem is
var output = ID;

You're trying to set the value for output before the class has been constructed. You can set it in the initializer list instead :
  SimpleClass({this.ID}):
        output= ID;


text:
Q: 2 Listagg the same query and repeated value   SELECT DISTINCT
         ROW_NUMBER () OVER (ORDER BY A.f_NAME ASC) AS r,
         A.ID,
         A.F_NAME,
         A.L_NAME,
         A.FATHER_NAME,
         A.DOB,
         A.DEAD_DATE,
         A.GENDER,
         A.NATIONALITY,
         A.AUTHOR_INFO,
         A.REWARD,
         LISTAGG (TO_CHAR (S.SUBJECT_NAME), ', ')
            WITHIN GROUP (ORDER BY TO_CHAR (S.SUBJECT_NAME))
            AS SUBJECT_NAME,
         LISTAGG (TO_CHAR (B.TITLE), ', ')
            WITHIN GROUP (ORDER BY TO_CHAR (b.title))
            AS book
    FROM book_author ba
         RIGHT JOIN author a
            ON A.ID = BA.AUTHOR_ID
         LEFT JOIN book b
            ON B.ID = BA.BOOK_ID
         LEFT JOIN author_subject ass
            ON a.ID = ass.author_id
         LEFT JOIN subjects s
            ON s.id = ass.subject_id
   WHERE A.ACTIVE = 1
GROUP BY A.ID,
         A.F_NAME,
         A.L_NAME,
         A.FATHER_NAME,
         A.DOB,
         A.DEAD_DATE,
         A.GENDER,
         A.NATIONALITY,
         A.AUTHOR_INFO,
         A.REWARD;

If  1 subject 2 books,  then the  subject repeated 2 time . I know this question repeated, but do not write correctly.
Please help me. Thanks. 18c and earlier Oracle

A: One method is to use row_number() to do what you want.  Your query is quite complicated, but here is the idea:
with x as (
      <whatever>
     )
select <grouping columns>, -- grouping columns
       list_agg(case when seqnum_subject_name = 1 then subject_name end, ', ') within group (order by subject_name),
       list_agg(case when seqnum_title = 1 then title end, ', ') within group (order by title)
from (select x.*,
             row_number() over (partition by <grouping columns>, subject_name order by subject_name) as seqnum_subject_name,
             row_number() over (partition by <grouping columns>, title order by title) as seqnum_title
      from x
     ) x
group by <grouping columns>;

I am not sure why you are converting subject_name to a string.  I don't see why that would be needed so I removed that logic.


text:
Q: The function of a capacitor with the fluorescent lamp What is the function of the capacitor across the supply to the fluorescent lamp when it is used?

A:
Figure 1. A typical fluorescent lamp circuit with capacitor on mains input. Source: Illumination - types of lamps.
Fluorescent lamps form an inductive load on the AC mains supply. As a result large installations of such lamps suffer a poor power factor and resultant voltage drop. Adding a capacitor to each lamp corrects the power factor bringing it back close to unity (1.0). This solves the problem of associated voltage drop and also, for large energy users, eliminates power factor surcharge on the bills - for that part of the load at least.
It is possible to omit the capacitor on the individual lamps and to centralise them in the switch room and automatically switch in as many as required to keep the power factor within acceptable limits.

A: Fluorescent lamps, like spark gaps, have negative resistance.   This makes the lamp very likely to build up an oscillation, causing radio interference.   The capacitor, in addition to the internal RF
resistance in the ballast choke, damps such oscillation.
There's
a capacitor across the points of a classical auto distributor's points
(which are a spark gap), for similar reasons.   With other components,
Marconi made early practical radio transmitters powered by ... a spark gap.

A: Not any of it exactly correct I'm afraid. If you take the breaker points in the car, the release of current to the coil primary when the switch opens causes the immediate field collapse that will generate the HV spark. If you draw out the circuit (remember it's an auto transformer without isolation between primary & secondary), you will see that without the capacitor there is no direct earth connection. That's what the "condenser" provides. This is ringing ac at HF. It also stops the propensity therefore to arc across the points as they are by-passed by it. Low reactance to ac.
The fluorescent is a different issue. For PF correction yes but not required for operation. The lamp must record correctly the power it is taking from the mains. The inductor (choke) spoils that for inductive motorised recorders (The company meter). You want to pay don't you? !!


text:
Q: Will memcache help with expensive MySQL queries? (Drupal site) this is a simple question. There are some queries on our site that take too many seconds to complete (like 15 seconds!). For anonymous traffic they get a cached .html file, but for logged in users it's too slow.
The query looks like this:

SELECT node.nid, votingapi_cache_vote_percent_average.value AS votingapi_cache_vote_percent_average_value, votingapi_cache_vote_percent_count.value AS votingapi_cache_vote_percent_count_value, node.type AS node_type, users.name AS users_name, users.uid AS users_uid, node_data_field_species.field_species_nid AS node_data_field_species_field_species_nid, node.title AS node_title, node.changed AS node_changed, node.created AS node_created, node_data_field_picture.field_picture_fid AS node_data_field_picture_field_picture_fid, node_data_field_picture.field_picture_title AS node_data_field_picture_field_picture_title, node_data_field_picture.field_picture_alt AS node_data_field_picture_field_picture_alt, node_data_field_recorded.field_recorded_value AS node_data_field_recorded_field_recorded_value, node_data_field_static_location.field_static_location_value AS node_data_field_static_location_field_static_location_value, field_video_op_videos.video_id AS field_video_op_videos_preview_image_link FROM node node LEFT JOIN votingapi_cache votingapi_cache_vote_percent_average ON node.nid = votingapi_cache_vote_percent_average.content_id AND votingapi_cache_vote_percent_average.content_type = 'node' AND votingapi_cache_vote_percent_average.value_type = 'percent' AND votingapi_cache_vote_percent_average.tag = 'vote' AND votingapi_cache_vote_percent_average.function = 'average' LEFT JOIN votingapi_cache votingapi_cache_vote_percent_count ON node.nid = votingapi_cache_vote_percent_count.content_id AND votingapi_cache_vote_percent_count.content_type = 'node' AND votingapi_cache_vote_percent_count.value_type = 'percent' AND votingapi_cache_vote_percent_count.tag = 'vote' AND votingapi_cache_vote_percent_count.function = 'count' INNER JOIN users users ON node.uid = users.uid LEFT JOIN content_field_species node_data_field_species ON node.vid = node_data_field_species.vid LEFT JOIN content_type_picture node_data_field_picture ON node.vid = node_data_field_picture.vid LEFT JOIN content_field_recorded node_data_field_recorded ON node.vid = node_data_field_recorded.vid LEFT JOIN content_field_static_location node_data_field_static_location ON node.vid = node_data_field_static_location.vid LEFT JOIN content_type_video node_data_field_video ON node.vid = node_data_field_video.vid LEFT JOIN op_videos field_video_op_videos ON node_data_field_video.field_video_video_id = field_video_op_videos.video_id WHERE (node.type IN ('audio','picture','video')) AND (node.status = '1') ORDER BY votingapi_cache_vote_percent_average_value DESC, votingapi_cache_vote_percent_count_value DESC LIMIT 0, 30

Will memcache help to serve that page faster? Or, at least, second-time access to it...
Thanks

A: Expensive queries should be chached one way or another. The query you posted didn't depend on the user being logged in so should be cached.
Have you tried turning on agressive caching in admin, this may help (but could hurt you elsewhere).
If the query is being run from a block make sure block caching is on and appropriate for the query (this would be BLOCK_CACHE_GLOBAL).
Worst case you should look at building your own caching for the pinch points. Only as a last resourt.
update: I am guessing that you are using views to generate the page. I have looked here and it looks like the latest views2 and views3 has some caching built in, if you upgrade you may be able to use it.

A: Using memcached to cache the output of this query, or the generated HTML resulting from it, will indeed speed up your page load after the initial result has been cached.
Before doing that though, you should look at the cache settings on the view itself.  In my experience, these settings override the site-wide cache settings in Settings -> Performance.  Assuming you are using Drupal 6 and Views 2, you can set the cache lifetime of a view by editing the view, and then clicking Basic Settings -> Cache.

A: memcached is just a caching mechanism. Your query will still take just as long to perform.
If you want to use it to make things smoother, continually query the database and update the result in memcached in the background and serve up the information from the cache. That way the information is no more that 15 or so seconds old, but is retrieved very quickly.
You might also want to just increase the cache of the MySQL server. memcached is not usually used for caching a single query result...


text:
Q: Проблема с импортом модуля PIL Рабочие среды не видят PIL, Image.
No module named PIL(Image)

На компьютере стоит последний пакет Anaconda.
Пробовал как устанавливать Pillow, так и обновлять. Все равно не хочет работать.
С VS Code то же самое.


text:
Q: Blob storage, IIS smooth streaming or Adaptive streaming I m confused I would like to have smooth streaming capability on the cloud but I m a bit confused.
I have seen by searching the web that sooth streaming with azure blob will be supported by april we are in juin and I have seen no updates no where. Is it stile ongoing? should we wait? any news?
http://blogs.msdn.com/b/hanuk/archive/2011/04/12/windows-azure-cdn-for-iis-smooth-streaming.aspx
I have seen this method for doing soomth streaming
http://blog.smarx.com/posts/smooth-streaming-with-windows-azure-blobs-and-cdn
He is parsing the files and recreating manifests it seems to have some limitations and potential issues with future releases and it's called Adaptive streaming instead of smooth. Is it the way to go?
I wonder also if we have to use a silverlight player or if it can be done also in HTML5?

A: Native support in the Windows Azure CDN for Smooth Streaming is indeed still coming. It's not available yet.
The reason my solution is called "Adaptive Streaming" instead of "Smooth Streaming" is because "Smooth Streaming" refers specifically to using IIS to serve the content (so my solution, while compatible, isn't technically Smooth Streaming).
Smooth Streaming doesn't strictly require Silverlight, but that's the most common player. No browser I'm aware of natively supports the Smooth Streaming protocol.


text:
Q: Karma/Jasmine unit test for D3 svg element I am working on an Angular app and I am using Jasmine to write the unit tests and Karma as test runner.
We are using D3 for visualization.
My actual code is something like this.
createPlot(ds, "#firstDiv", "constant1", "constant2", "constant3", 1300, 500);

where ds is my data and "#firstDiv" is the id of the DIV where I need SVG.
Inside createPlot, I have something like
var svg = d3.select(divId).append("svg")
        .attr("width", someValue)
        .attr("height", someValue);

I need to call createPlot function with various div ids on my page.
This code actually works and creates SVGs as needed.
My question is:
I would like to write jasmine unit test for this using Karma test runner.
How can test that after calling "createPlot" "svg" has been created?
Any example or help is greatly appreciated.
Update:  (tried Dayan's suggestion with below code, but it didn't work)
describe('D3 Page', function () {
    var ctrl, scope, element, compile;
    var html ='<div id="first"> </div>';
    beforeEach(module('app'));
    beforeEach(inject(function ($controller, $rootScope, $injector, $compile) {
        scope = $rootScope.$new();
        ctrl = $controller('D3PageCtrl', {
            $scope: scope
        });
        compile = $compile;
        element = compile(angular.element(html))(scope);
    }));
    afterEach(function() {
    });
    it('should create svg', function(){
        createPlot(ds, "#first",  "constant1", "constant1", "operatorsNOp", 1300, 500);
        console.log(element.html()); // prints ' '
        element = compile( angular.element(html) )( scope );
        element.scope().$digest();
        console.log(element.html()); // prints ' '
        console.log(element.find('svg').length); // prints 0
        expect(element.find('svg').length).toBe(1);  // fails
    });
});

A: Something like this should serve as a guide:
describe('sample tests', function () {
    var container;
    beforeEach(function () {
       container = document.createElement('div');
       createPlot(container, "#firstDiv", "constant1", "constant2", "constant3", 1300, 500);
    })

    afterEach(function () {
       container=null;
    })

    it('should have svg', function () {
         var svg = container.getElementsByTagName('svg');
         expect(svg).not.toBe(null);
    })
})


text:
Q: How does GL_PIXEL_PACK_BUFFER asynchronicity work? If I understand correctly, when I use glGetTextureSubImage() OpenGL has to synchronize, before this function can return.
But if I bind a buffer to GL_PIXEL_PACK_BUFFER that function call is asynchronous.
Does OpenGL synchronize it as soon as I try to access the data? Are there other rules?

A:
Does OpenGL synchronize it as soon as I try to access the data?

Yes; that's the whole point. When reading into your storage, the OpenGL implementation must assume that you will immediately access the read pixel data. It has to assume that because it cannot detect when you're about to read that storage. After all, OpenGL doesn't own that storage.
A buffer object is storage that OpenGL owns. If you call glGetBufferSubData or glMapBufferRange or whatever, OpenGL sees that call. Therefore, the OpenGL implementation can synchronize with the reading operation at that point, rather than at the time you issued the read.
Of course, with persistent mapping, OpenGL doesn't have the ability to tell when you're reading the data. But if you're using persistent mapping, you're telling OpenGL that you will perform the necessary synchronization, so it won't try to do so.


text:
Q: Mozilla Firefox not getting value innerText This is my JavaScript code:
function selectRow(objTR) {
    for (i = 0; i < ddlModalityList.options.length; i++) {
        if (ddlModalityList.options[i].text == objTR.cells[1].innerText.trim()) break;
    }

    ddlModalityList.options[i].selected = true;
    txtSSAETitle.value = objTR.cells[2].innerText.trim();
    txtSSName.value = objTR.cells[3].innerText.trim();
}

This is repeater code. On row click I am passing id of tr and displaying respective td value in respective dropdownlist and textboxes. This code works fine in IE but fails in Mozilla Firefox.

        <%#Eval("Acq_Modality_ID")%>

        <asp:Label ID="lblModality" runat="server" Text='<%#Eval("Modality")%>'></asp:Label>

        <asp:Label ID="lblSchdledStAETitle" runat="server" Text='<%#Eval("Scheduled_Station_AE_Title")%>'></asp:Label>

        <asp:Label ID="lblSchdleStationAEName" runat="server" Text='<%#Eval("SCHEDULED_STATION_NAME")%>'></asp:Label>

A: Firefox does not support innerText. You can use textContent instead. However, older IE does not support textContent, so you'll need to use one and fall back to the other.
function getInnerText(el) {
    return el.textContent || el.innerText;
}

Note that they're not identical, but for your purposes it will be fine.

A: Use innerHTML instead of innerText. InnerText will not work in FF. innerHTML will work on both of them.
http://forums.asp.net/p/1228392/2210082.aspx

A: Firefox does not support innerText.. you should use jquery so that you dont need to care about the difference in browers implementation
so using jquery your code would be
function selectRow(objTR) {
    for (i = 0; i < ddlModalityList.options.length; i++) {
        if (ddlModalityList.options[i].text == $(objTR).children('td').eq(1).html().trim()) break;
    }

    ddlModalityList.options[i].selected = true;
    txtSSAETitle.value = $(objTR).children('td label').eq(2).html().trim();
    txtSSName.value = $(objTR).children('td label').eq(3).html().trim();
}

im leaving the ddlModalityList as it is because i dont know what it is.

A: function selectRow(objTR) {
    for (i = 0; i < ddlModalityList.options.length; i++) {
        if (ddlModalityList.options[i].text == $(objTR).children('td').eq(1).html().trim()) break;
    }

    ddlModalityList.options[i].selected = true;
    txtSSAETitle.value = $(objTR).children('td label').eq(2).html().trim();
    txtSSName.value = $(objTR).children('td label').eq(3).html().trim();
}

A: document.getElementById('InputText').innerHTML.replace(/<.+?>/gim,''));


text:
Q: Can't get mutual friend with images of all the users from facebook at same time I am trying to get users mutual friend with image
1) Name
2) Total mutual friend count
3) User_Image
I am using this Facebook api
https://graph.facebook.com/v2.8/{facebook_uid}?fields=context.fields(mutual_friends)&access_token={access_Token}

And I am getting this result
{
   "context": {
      "mutual_friends": {
         "data": [
            {
               "name": "Gaurav Varshney",
               "id": "1919297771636793"
            }
         ],
         "paging": {
            "cursors": {
               "before": "MTkxOTI5Nzc3MTYzNjc5MwZDZD",
               "after": "MTkxOTI5Nzc3MTYzNjc5MwZDZD"
            }
         },
         "summary": {
            "total_count": 1
         }
      },
      "id": "dXNlcl9jb250ZAXh0OgGQMVZBxLkIzIAZCrsH18MkJldpVQt5FdVkJzXiEz7ulaHNGnyCX0gDZCghaZBZAZB0JQd2wTbPd1SnEfWZC394zYYWfOCmnFHga6LbbnYcHhHPA6F3o4ZD"
   },
   "id": "1744744292507346"
}

But I am getting no image of the user
I have look an alternative
https://graph.facebook.com/v2.8/facebook_uid/picture?type=large

Then I get an images but I don't find it suitable because suppose if i get 100 mutual friends so for every friend I need to hit this api for getting image .Can anyone give me a proper solution in which I need to hit one api and I get all the three things name,image,total_mutual_friend count

A: You can use Field Expansion to make nested requests.
1234567890?fields=context.fields(mutual_friends{name,picture})

But I don't think you can get the count of mutual friends for those mutual friends that same way. For that, you'll likely have to query the API for the individual mutual friend again.
Edit: To get larger versions of the profile pictures than the default 50*50px ones, you can use the type modifier here as well:
1234567890?fields=context.fields(mutual_friends{name,picture.type(large)})


text:
Q: How does allocation strategy usePowerOf2Sizes work? It seems that the allocation strategy usePowerOf2Sizes has no effect on the padding factor of the collection. Is there something I am missing or is this a bug? Is there an example that demonstrates the effect of usePowerOf2Sizes on the padding factor?
I have tried the following experiment:

*

*Insert several documents to mongodb.

*Randomly pick several documents, change their size, and save them.

*Check the padding factor of the collection.

*Repeat the steps 2 and 3 several times, observing the padding factor.

I expected that the resulting padding factor of this collection would be smaller for the exact fit allocation strategy than for the power of 2 sizes allocation strategy.
What I really observed, however, was the same padding factor regardless of the used allocation strategy.
This is the code I used (for mongo version 2.6.4):

function randomChoice(arr) {
    return arr[getRandomInt(0, arr.length)]
}

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function prepare(count, usePowerOf2Sizes) {
    db.aaa.drop();
    db.aaa.createIndex({"i": 1})

    for (var i=0; i<count; i++) {
        db.aaa.insert({"i": i});
    }
    db.runCommand({"collMod": "aaa", "usePowerOf2Sizes" : usePowerOf2Sizes })
}

function changeSizes(actionCount) {
    vals = [100, 150, 225, 340, 500, 760, 1200].map(function (n) {return Array(n + 1).join("a")})

    count = db.aaa.count()

    for (var i=0; i<actionCount; i++) {
        d = db.aaa.find({"i": getRandomInt(0, count)})[0];
        d["a"] = randomChoice(vals);
        db.aaa.save(d);
    }
}

function runPaddingTest(documentCount, usePowerOf2Sizes, actionCount, iterations) {
    prepare(documentCount, usePowerOf2Sizes);
    print("Use padding:", db.aaa.stats().userFlags)
    print("Padding:", db.aaa.stats().paddingFactor)
    d1 = new Date().getTime();
    for(var i=0; i<iterations; i++) {
        changeSizes(actionCount);
        print("Padding:", db.aaa.stats().paddingFactor)
    }
    d2 = new Date().getTime();
    print("Millis:", d2-d1)
}

Example outputs:
// 100 documents, power of 2 sizes allocation strategy, 7*300 document changes
> runPaddingTest(100, true, 300, 7);
Use padding: 1
Padding: 1
Padding: 1.1840000000000002
Padding: 1.1800000000000068
Padding: 1.1360000000000148
Padding: 1.0660000000000238
Padding: 1.0050000000000323
Padding: 1
Padding: 1
Millis: 2661

// 100 documents, exact allocation strategy, 7*300 document changes
> runPaddingTest(100, false, 300, 7);
Use padding: 0
Padding: 1
Padding: 1.2129999999999992
Padding: 1.224000000000005
Padding: 1.1750000000000131
Padding: 1.1150000000000215
Padding: 1.0430000000000303
Padding: 1
Padding: 1
Millis: 2641

// 1000 documents, power of 2 sizes allocation strategy, 7*300 document changes
> runPaddingTest(1000, true, 300, 7);
Use padding: 1
Padding: 1
Padding: 1.451999999999991
Padding: 1.8189999999999849
Padding: 1.999
Padding: 1.9980000000000002
Padding: 2
Padding: 1.999
Padding: 1.9980000000000002
Millis: 2730

// 1000 documents, exact allocation strategy, 7*300 document changes
> runPaddingTest(1000, false, 300, 7);
Use padding: 0
Padding: 1
Padding: 1.447999999999991
Padding: 1.784999999999986
Padding: 1.9980000000000002
Padding: 1.999
Padding: 2
Padding: 1.999
Padding: 1.999
Millis: 2728

A: I don't think padding factor is relevant for usePowerOf2Sizes. For power of 2 sizes, the space allocated  in bytes for a new spot for a record (for an insert or an update requiring a document move) is something like
2^ceiling(log_2(bsonsize(record))

i.e. the smallest power of two larger than the document size. For the exact fit allocation strategy, the space is
padding factor * bsonsize(document)

The padding factor is some number between 1 and 2 that MongoDB adjusts automatically based on how it sees documents in the collection grow. Note that it's not an empirical measure of how much padding, just some guess at how much padding should be used in the near future, and it's not relevant for power of 2 sizes. I don't know exactly how it is calculated - you'll have to read the code for that - but the fact that different allocation strategies lead to different record sizes lead to different patterns of documents on disk and patterns of document moves on update means it's not surprising the padding factor differs when doing the same operations on the same collection created with different allocation strategies.

A: I know this is an old question, but I had the same thought today. I was able to confirm by using the special "$showDiskLoc" property to prove that it is rounding to the next power of 2^N.
With the example I tested on a new collection, the delta between offsets confirms to me that it is properly rounding the bsonsize to the next power of 2^N. This will also tell you which preallocated datafile the document was assigned to which is useful when you have actual fragmentation.

db.test.drop();

for (var i = 0; i < 10; i++) {
    var doc = {"stuff": "7K92NoukQhTzWJWQmTIFmmzwhk4UCtscgCq4eFAp5gRrmUKrLz8J0GueE84IvQ2ySJIMpx82IXSYqa2DxRPj087iN8UclTF9NRYMWDejIFENOGWP1R8JoCLsq5MEEDtiBoMYP5epowHz3UFyilrMRsAf0qSbQXsnNUKrg0PaDRi67tLAbim1rn3nOW2nxPFKV5XNmfPm8Cm3ONfIR7qpmjV98rucFpeguL6FrNQgcSUUTjCXvZ48cPDKITWrSl5OLLzxVAXjhm2LSKFLxC9VDykBuwrVX0sOT8Px0H5LEgVpzLU3BqU8tNUPz39SMGC98gpmMg6aJNSLFc91xuC6sSJFa8X1COMcBsXOpnLvuL6garJYisImzhpWvrVtGsLORLIskm6nD5PWrGkAnEvCNP9aZVvbsovhR89AeWMCMoftYirf57hmOPa2BMf3Y5Cs9bp5PCs4SpsvcP7q1Q7tKJvlSISUUs6to3u59UXoLn3JT5baM6kUSROls9CnU1O5"};

    // 529 -> should get rounded to 1024
    print(Object.bsonsize(doc));
    db.test.insert(doc);

    doc = {"stuff": "77K92NoukQhTzWJWQmTIFmmzwhk4UCtscgCq4eFAp5gRrmUKrLz8J0GueE84IvQ2ySJIMpx82IXSYqa2DxRPK92NoukQhTzWJWQmTIFmmzwhk4UCtscgCq4eFAp5gRrmUKrLz8J0GueE84IvQ2ySJIMpx82IXSYqa2DxRP"};
    // 183 -> should get rounded to 256
    print(Object.bsonsize(doc));
    db.test.insert(doc);
}

db.test.find({}, {"_id": 1})._addSpecial("$showDiskLoc", true);

// Offset diff should alternate between 1024 and 256
{ "_id" : ObjectId("5a20f806c5587820fa66fc49"), "$diskLoc" : { "file" : 0, "offset" : 336048 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc4a"), "$diskLoc" : { "file" : 0, "offset" : 337072 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc4b"), "$diskLoc" : { "file" : 0, "offset" : 337328 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc4c"), "$diskLoc" : { "file" : 0, "offset" : 338352 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc4d"), "$diskLoc" : { "file" : 0, "offset" : 338608 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc4e"), "$diskLoc" : { "file" : 0, "offset" : 339632 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc4f"), "$diskLoc" : { "file" : 0, "offset" : 339888 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc50"), "$diskLoc" : { "file" : 0, "offset" : 340912 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc51"), "$diskLoc" : { "file" : 0, "offset" : 341168 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc52"), "$diskLoc" : { "file" : 0, "offset" : 342192 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc53"), "$diskLoc" : { "file" : 0, "offset" : 342448 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc54"), "$diskLoc" : { "file" : 0, "offset" : 343472 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc56"), "$diskLoc" : { "file" : 0, "offset" : 343728 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc55"), "$diskLoc" : { "file" : 0, "offset" : 475312 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc57"), "$diskLoc" : { "file" : 0, "offset" : 476336 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc58"), "$diskLoc" : { "file" : 0, "offset" : 477360 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc59"), "$diskLoc" : { "file" : 0, "offset" : 477616 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc5a"), "$diskLoc" : { "file" : 0, "offset" : 478640 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc5b"), "$diskLoc" : { "file" : 0, "offset" : 478896 } }
{ "_id" : ObjectId("5a20f806c5587820fa66fc5c"), "$diskLoc" : { "file" : 0, "offset" : 479920 } }


text:
Q: Keyboard shortcut for code refactor (var rename) in Visual Studio When renaming a variable in Visual Studio (I use 2010), it shows a little mark that when clicked, leads to a drop-down that offers to rename all the dependant references.

What I want to do, is spare getting the mouse and click it in order to show the drop-down.
I was wondering if there is a way to access it via the keyboard.

A: If you wish to assign your own shortcut, go to Tools | Options | Environment | Keyboard, then in the "Show commands containing" field, enter the text View.ShowSmartTag

A: I believe that shortcut is Ctrl + . [dot] :)


text:
Q: Heroku Application Error failing to deploy I am trying to deploy my site on Heroku.
I've used the following command "heroku logs --tail" in my cmd and it returns with the following code:
2019-07-31T23:55:23.815010+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=kobadatech.herokuapp.com request_id=2a5d4d0d-3ebb-47eb-8361-d8b870dd64be fwd="46.69.72.14" dyno= connect= service= status=503 bytes= protocol=https
 !    Logs eventsource failed with: 401 Unauthorized

This is the link to my Heroku page: https://kobadatech.herokuapp.com/.


text:
Q: rotate node in 3D I am trying to draw this 3D shape

I draw the 4 arrows and the cylinder, but can't rotate the arrows in 3D to put them on the top.
\documentclass{standalone}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\usetikzlibrary{shapes.arrows}

\begin{document}
%,rotate around={30:(0,1,1)}

\begin{tikzpicture}
        \node[cylinder, draw=white,fill=blue, shape aspect=0.7,rotate=90,minimum height=0.7cm, minimum width=2cm] {hh};
        \node [fill=red,single arrow, draw=none, rotate=90,minimum height=1cm,minimum width=0.7cm]at(0,0) {};
        \node [fill=blue,single arrow, draw=none, rotate=-90,minimum height=1cm,minimum width=0.7cm] at (0,1.5) {};
        \node [fill=red,single arrow, draw=none, rotate=-180,minimum height=1cm,minimum width=0.7cm]at(-0.75,0.7) {};
        \node [fill=blue,single arrow, draw=none, rotate=-360,minimum height=1cm,minimum width=0.7cm] at (0.75,0.7) {};
    \end{tikzpicture}
\end{document}

A: Here's another version with uses the 3D library and paints a custom arrow.
The code between \makeatletter and \makeatother is used to correct an error in the implementation of canvas is xy plane at z=. As far as I know it was first fixed by Jake in TikZ: How to draw an isometric drawing.
Code
\documentclass[tikz, border=2mm]{standalone}
\usetikzlibrary{calc, 3d}

\makeatletter
    \tikzoption{canvas is xy plane at z}[]%
    {   \def\tikz@plane@origin{\pgfpointxyz{0}{0}{#1}}%
        \def\tikz@plane@x{\pgfpointxyz{1}{0}{#1}}%
        \def\tikz@plane@y{\pgfpointxyz{0}{1}{#1}}%
        \tikz@canvas@is@plane
    }
\makeatother

\newcommand{\Arrow}[4]%
% start, direction, length, width
{   \fill[white] (#1) -- ++ (#2+90:#4/2) -- ++ (#2:#3-#4) -- ++ (#2+90:#4/2) -- ++ (#2-45:1.414214*#4) -- ++ (#2-135:1.414214*#4) -- ++ (#2+90:#4/2) -- ++ (#2-180:#3-#4) -- cycle;
}

\begin{document}
\begin{tikzpicture}
[   xy/.style={canvas is xy plane at z=#1},
    x={(-20:1cm)},
    y={(20:1cm)},
    z={(90:1cm)},
]
    \fill[cyan!50!gray, draw=white] (-135:4) arc (-135:45:4) -- ++ (0,0,2) arc(45:-135:4) -- cycle;
    \fill[cyan!50!gray, draw=white] ($(225:4)+(0,0,2)$) arc (-135:225:4)
        coordinate[pos=0.20] (n1)
        coordinate[pos=0.55] (n2)
        coordinate[pos=0.70] (n3)
        coordinate[pos=0.95] (n4)
     -- cycle;
    \begin{scope}[xy=2]
        \foreach \A in {1,...,4}
        { \Arrow{{\A*90-60-180*mod(\A,2)}:{3.6-3.2*mod(\A,2)}}{\A*90-60+180}{3.2}{0.5}
        }
    \end{scope}
\end{tikzpicture}

\end{document}

Output

A: A solution with arrows.meta library
\documentclass[border =3mm]{standalone}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\usetikzlibrary{arrows.meta,calc}

\begin{document}
%,rotate around={30:(0,1,1)}
\tikzset{Ultra thick/.style={line width=2.5pt}}
\begin{tikzpicture}
        \node[cylinder, draw=white,fill=blue, shape aspect=0.7,rotate=90,minimum height=0.7cm, minimum width=2cm,aspect=1.5](c) {hh};
   \begin{scope}[white,-{Triangle[angle=45:1pt 2]},inner sep=0.5pt]
        \node(topt) at (c.-5){};
        \node(topl) at (c.50){};
        \node(topc) at ($(c.before top)!0.5!(c.after top)$){};
        \node(topb) at ($(topc)!-1!(topt)$){};
        \node(topr) at ($(topc)!-1!(topl)$){};
        % draw arrows
        \draw[Ultra thick](topc)--(topt);
        \draw[Ultra thick](topc)--(topb);
        \draw[Ultra thick](topr)--(topc);
        \draw[Ultra thick](topl)--(topc);
  \end{scope}
\end{tikzpicture}

\end{document}

Output [added by cfr]:


text:
Q: R - Apply operation to each column dataframe X referencing entries of dataframe Y I have two dataframes in R, one of which contains model outputs and the other contains model thresholds. That is, the outputs dataframe (call it df1) looks something like this:
model1      model2       model3
0.086       0.2645728    0.0001668753
0.024       0.2109496    0.0001905100
0.052       0.2484194    0.0038053175
0.274       0.3650003    0.0002842775
0.260       0.4055953    0.0280523161

And the threshold dataframe (call it df2) looks something like:
model   threshold
model1  0.5520000
model2  0.7924895
model3  0.7537394

I want to apply the >= operation to each entry in df1 where the column name is equal to the model name in df2, and store these binaries in a new dataframe (call it df3), which would be the same size as df1. That is, df3 is the predicted label for each entry in df1, given the corresponding model-based threshold in df2. It's clear that I could do this in a brute force for-loop fashion like:
df3 = df1
for (mdl in df2$model) {
   df3[, mdl] = df1[, mdl] >= df2$threshold[df2$model==mdl]
}

I don't like this solution, and I'm hoping there is a more R-based way to perform this operation.
Reproducible Sample Data
df1 <- read.table(header = TRUE, text = "
                  model1      model2       model3
0.086       0.2645728    0.0001668753
0.024       0.2109496    0.0001905100
0.052       0.2484194    0.0038053175
0.274       0.3650003    0.0002842775
0.260       0.4055953    0.0280523161")

df2 <- read.table(header = TRUE, text = "
                  model   threshold
model1  0.5520000
model2  0.7924895
model3  0.7537394")

A: You can use map2 function from purrr package and also mapply from base R since we are iterating over two variables at the same time:
library(purrr)

df1 %>%
  map2_dfc(., df2$threshold, ~ .x >= .y)

# A tibble: 5 x 3
  model1 model2 model3
  <lgl>  <lgl>  <lgl>
1 FALSE  FALSE  FALSE
2 FALSE  FALSE  FALSE
3 FALSE  FALSE  FALSE
4 FALSE  FALSE  FALSE
5 FALSE  FALSE  FALSE

Or using mapply of apply family of functions:
mapply(function(x, y) x >= y, df1, df2$threshold)

     model1 model2 model3
[1,]  FALSE  FALSE  FALSE
[2,]  FALSE  FALSE  FALSE
[3,]  FALSE  FALSE  FALSE
[4,]  FALSE  FALSE  FALSE
[5,]  FALSE  FALSE  FALSE

A: An alternative stupid method:
transform df2 to a data frame with the same size as df1
df <- data.frame(
    model1 = rep(df2[which(df2$model == "model1"), "threshold"],nrow(df1)),
    model2 = rep(df2[which(df2$model == "model2"), "threshold"],nrow(df1)),
    model3 = rep(df2[which(df2$model == "model3"), "threshold"],nrow(df1))
)

df3 <- df1 >= df


text: Q: Autosomal Inbreeding Probability Matrix We are mating two people with Aa genotypes.  So the punnet square tells us their offspring will be AA, Aa, or aa with probabilities .25, .5, or .25, respectively.  We are interested in breeding these offspring (we are assuming there are many offspring) together and need to find the probability we pair together (AA,AA), (AA,Aa), (AA, aa), (Aa,Aa), (Aa,aa), (aa,aa).  My attempt was to multiply the P(AA)*P(AA) and so on down the list but the six probabilities did not add up to 1, as it should.  any help is appreciated.  this is for a film project for my linear algebra II class.  thanks.


text:
Q: How to overwrite (NOT append) a text file in ASP.NET using C# I have included a text file in my website with multiple lines.
I have put a textbox (Multimode=true) and a button in the page.
On Page_Load the content from the textFile should be displayed in the textbox.
Then the user can edit the textbox. On button click the current content of TextBox should be overwritten in that text file (it should not be appended).
I'm successfully displaying the text file data in a textbox. But while overwriting, it appends in the text file rather than overwriting.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
    if (File.Exists(Server.MapPath("newtxt.txt")))
    {
        StreamReader re = new StreamReader(Server.MapPath("newtxt.txt"));
        while ((input = re.ReadLine()) != null)
        {
           TextBox1.Text += "\r\n";
           TextBox1.Text += input;
        }
        re.Close();
    }

    else
    {
        Response.Write("<script>alert('File does not exists')</script>");
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    StreamWriter wr = new StreamWriter(Server.MapPath("newtxt.txt"));
    wr.Write("");
    wr.WriteLine(TextBox1.Text);
    wr.Close();
    StreamReader re = new StreamReader(Server.MapPath("newtxt.txt"));
    string input = null;
    while ((input = re.ReadLine()) != null)
    {
        TextBox1.Text += "\r\n";
        TextBox1.Text += input;
    }
    re.Close();
}

How can I overwrite the text file and then display it in my TextBox on the same button click?

A: StreamWriter constructor has several overloads, including one to specify whether to append or overwrite.
StreamWriter wr = new StreamWriter(Server.MapPath("newtxt.txt"), false);

From MSDN, the second parameter:

Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.

A: Server.MapPath returns a string with the path to the file.  You might try opening the file by hand before passing it to the stream writer.  Note the FileMode of Create, and the FileAccess of Write.
var path = Server.MapPath("newtxt.txt");
using (var fileStream = File.Open(path, FileMode.Create, FileAccess.Write))
{
    using (var writer = new StreamWriter(fileStream))
    {
        // the rest of your code
    }
}

A: Check out the System.IO.File.WriteAllText method, it'll overwrite the file if it exists and it's all done in just a single line of code. Likewise, you can use the System.IO.File.ReadAllText method to easily get the contents of a file.
protected void Page_Load(object sender, EventArgs e)
{
    if (File.Exists(Server.MapPath("newtxt.txt")))
    {
        TextBox1.Text = System.IO.File.ReadAllText("newtxt.txt");
    }
    else
    {
        Response.Write("<script>alert('File does not exists')</script>");
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    System.IO.File.WriteAllText("newtxt.txt", TextBox1.Text);
}

A: You appear to be overwriting the file in your Button Click handler, then appending it's contents to the TextBox.  In this way, it appears to the client that you've appended to the file.
Try the following in the Button Click handler, after writing the file and before reading it back:
TextBox1.Text = "";

Or just don't bother reading it back - there's not much point because the text you've written to the file is still in the TextBox.


text:
Q: Fork Join pool hangs The case is that an application hangs infinitely from time to time.
Seems that the bug sits in the following snippet:
ForkJoinPool pool = new ForkJoinPool(1); // parallelism = 1

List<String> entries = ...;

pool.submit(() -> {

    entries.stream().parallel().forEach(entry -> {
        // An I/O op.
        ...
    });

}).get();

Thread pool-4-thread-1 that executes the code freezes on get():
"pool-4-thread-1" #35 prio=5 os_prio=0 tid=0x00002b42e4013800 nid=0xb7d1 in Object.wait() [0x00002b427b72f000]
       java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        at java.util.concurrent.ForkJoinTask.externalInterruptibleAwaitDone(ForkJoinTask.java:367)
        - locked <0x00000000e08b68b8> (a java.util.concurrent.ForkJoinTask$AdaptedRunnableAction)
        at java.util.concurrent.ForkJoinTask.get(ForkJoinTask.java:1001)
...other app methods

One can assume that the task passed to submit() executes too long.
But surprisingly there is no ForkJoinPool-N-worker-N occurrences in the thread dump, so looks like the pool doesn't perform any computations!
How is that possible? If no tasks are executed by the pool, why pool-4-thread-1 thread waits inside get()?
P.S. I know that it's not recommended to execute I/O-related tasks in ForkJoinPool, but still interested in the root of the problem.
Update. When parallelism is set to value greater than 1, no problems are detected.

A: Set parallelism = N where N > 1 solved the problem.
Strange thing but seems that there is some bug in ForkJoinPool similar to what is stated here.


text:
Q: Angular2 countdown display onClick Event for a second for another function needs time to process its code I have my original code in angular1 in which there are two functions: start() and startFilling(). start() is called a button click. startFiling() needs 10 seconds to process once the user clicks Start button that fires start(). A counter (which I have bound to template)  which goes in desc mode from 10 till 0 so that user gets feedback of how much time is left to process his request.
Template:

Countdown  {{counter}}

<button class="button button-dark start-button" ng-click="start()" ng-disabled="disableStart">Start</button>

Controller:
counter=10;
$scope.start = function(){
  ...
  ...

  $timeout($scope.startFilling, 10000) <= call startFilling() after 10 seconds
  $scope.onTimeout = function(){
    $scope.counter--;
    mytimeout = $timeout($scope.onTimeout,1000);

    if($scope.counter==0){
     $timeout.cancel(mytimeout);
     $scope.counter=0
    }
  }

  var mytimeout = $timeout($scope.onTimeout,1000); <= calling onTimeout() at each second to decrease the counter
}

$scope.startFilling = function(){
  console.log("startFilling()")
}

How can I achieve this in Angular2?
So far I have like this:
counter=10
timeoutId: any;

start(){
 ...
 ...

    this.timeoutId = setTimeout(()=>{
                    this.startFilling()
                }, 10000)

    var onTimeout: ()=> {

    }

    var newTimeoutId= setTimeout(()=>{onTimeout()},1000);

}

startFilling(){

   console.log("startFilling()")
}

A: Angular 2 has rxjs Support.
You use Observable.timer for it.
import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Component({
    selector: 'my-app',
    template: 'Ticks (every second) : {{ticks}}'
})
export class AppComponent {
  ticks =0;
  ngOnInit(){
    let timer = Observable.timer(2000,1000);
    timer.subscribe(t=>this.ticks = t);
  }
}

Working plunkr

A: Start is called a button click
public counter: number;
public timer: any;

constructor() {}

start() {
    this.counter = 10;
     window.clearInterval(this.timer);
     this.timer = setInterval(() => {
       this.counter--;
       if(this.counter === 0) {
            window.clearInterval(this.timer);

            /*After counter value is 0 means 10000 is completed */
            this.startFilling();
          }
     }, 1000);
}

startFilling() {
   console.log(true);
}


text:
Q: Can I delete the system-reserved partition on my RAID (non-system-drive) I have reinstalled my system as follows:
1 x 400 GB HDD -> system drive
4 x 1000 GB HDD -> RAID 10
After the installtion of Windows 7 Enterprise x64 is finished, I have a 100 MB NTFS system-reserved partition on each of the 2 disks (the 400 GB HDD and the RAID disk).
I would like to delete the system-reserved partition on my RAID disk.
Can I delete that partition without screwing up my new installation?
Edit1: Okay, I found out that this partition contains files for system-recovery and bitlocker.
But I thought that it'll be created only once.
The actual system-drive was my drive for movies, music and so on. I didn't format or partition it before I reinstalled win 7 (because my important files will be moved to the raid-disk). Could it be, that the system-reserved drive on my actual system-drive is from an earlier installation? (The actual system-drive containted the bootmgr from my previous win 7 installation)

A: I solved it myself as follows:
First I downloaded EasyBCD to find out, which of the two system-reserved partitions is used to boot.
Then I moved it to my system-disk (it was on the raid-disk).
After that, I had to change boot-priority of sata-disks in BIOS to my system-disk as first drive.
After that, I deleted that partition on my raid-disk.
That's all.