text:
Q: Is this a data race? OPENMP I am a bit confused if there is a data race for variable k. To my understanding, only one thread will execute the single construct but since no wait is asserted, threads will start executing the for construct immediately. Is atomic here enough to prevent any potential data race?
#include <stdio.h>
#include <omp.h>
#define Nthreads 8

void main()
{

int n =9, l,k =n,i,j;
k += n+1;

omp_set_num_threads(Nthreads);

  #pragma omp parallel default(none) shared(n, k) private(j)
  {
   #pragma omp single nowait
    {
    k = k+5;
    }
   #pragma omp for nowait
     for( i =0; i< n; i++)
     {
      #pragma omp atomic
       k +=n+i+1;
     }
  }
}

A: Assuming the rest of the code expresses your intended algorithm correctly, it almost is. As you were probably suspecting yourself, you need to protect k' s update in the single region as well.
j is an unused variable, I do not know if you simply forgot to delete it or you were trying to implement sth else.
I would have used a reduction clause for k in the for loop instead of using a synchronization construct. I do not know if it would have been better or faster though.


text:
Q: Rails 5.1.7 Server Hangs On First Request We are trying to update a Rails Server to release 5.1.
Server starts fine; but on the first request, goes completely dead; and has to be killed with signal 9.
Doesn't matter if its Puma or Webrick.
Doesn't matter if its 5.1.0 or 5.1.7
Doesn't matter if its development or production mode.
Eventually I saw the process size was 90GB and growing!
I've tried rbtrace, but struggled to get anything meaningful out of it.
I'm on osx, so strace isn't available, and I've struggled to get dtrace or dtruss to work, or produce anything meaningful.
So looking for a way to get this rails server to tell me what it's problem is....
Let me know what additional information is salient.

A: After quite a long process, I found a solution that didn't so much find the source of the issue, but provided a process to work around it.
First off, I used
rails app:update

And accepted all of the overwrites.   Then using git, I walked through all of the removed code from my config file and returned just the required sections [like config/routes.rb, and ActionMailer config, for example].
Application then started right up, no issue.
This also led me to
http://railsdiff.org/5.0.7.2/5.1.0
Which is pretty critical for Rails upgrading.   This is well worth consuming:
https://github.com/rails/rails/issues/31377#issuecomment-350422347

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can you get a ComboBox child of a DataGridView to process all keys, including "."? I have the same problem as described in the posts listed below.   That is, certain keys don't work at all when I type them into my combobox until I first hit the spacebar.  One of the keys is ".", but another is the letter "Q", and there are others: "$", "%".
http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=659716&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2909173&SiteID=1&pageid=0
http://bytes.com/forum/thread548399.html
I've tried a lot of things so far.  My latest failure was based on the theory that maybe the DataGridView was using WIN32 API wndproc subclassing to intercept messages, so I wrote logic to save the old wndproc and restore it after adding it to the DataGridView's control collection.   That didn't work.
Messina - thanks for reminding me about Spy++.     For the letter "A", the edit window sends an EN_UPDATE to its combobox parent.   But, not for the "Q".   That's so strange.
I have convinced myself that the DataGridView is not subclassing the combo and the edit, because I check the address of the wndprocs just after creation and before adding them to the grid's collection, and then later when I paint.    Unless the grid installs some sort of global hooks..
I'm thinkin, maybe I can subclass the edit control, and then send the notification to the combobox the way I see the edit control doing here?
EDIT:  More info here.   Windows messages from grid, combobox, and edit control, from Spy++:
HWNDs:
122064e < grid
010d0674 < combobox
01360696 < combox's edit control
<01402> 01360696 P WM_KEYDOWN nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01403> 010D0674 S WM_GETDLGCODE
<01404> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01405> 010D0674 S WM_GETDLGCODE
<01406> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01407> 010D0674 S WM_GETDLGCODE
<01408> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01409> 010D0674 S WM_GETDLGCODE
<01410> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01411> 01360696 P WM_CHAR chCharCode:'0061' (97) cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01412> 010D0674 S WM_GETDLGCODE
<01413> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01414> 010D0674 S WM_GETDLGCODE
<01415> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS

<01416> 010D0674 S WM_COMMAND wNotifyCode:EN_UPDATE wID:1001 hwndCtl:01360696  <<< edit control sends to combobox

<01417> 010D0674 S message:0x2111 [User-defined:WM_USER+7441] wParam:00060674 lParam:010D0674    What do these do?
<01418> 010D0674 R message:0x2111 [User-defined:WM_USER+7441] lResult:00000000

<01419> 010D0674 R WM_COMMAND
<01420> 010D0674 S WM_CTLCOLOREDIT hdcEdit:C7011AA6 hwndEdit:01360696
<01421> 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0

<01422> 010D0674 S WM_COMMAND wNotifyCode:EN_CHANGE wID:1001 hwndCtl:01360696  << edit control sends to combobox

<01423> 010D0674 S message:0x2111 [User-defined:WM_USER+7441] wParam:00050674 lParam:010D0674

<01424> 0122064E S WM_PAINT hdc:00000000   <<< grid is told to paint
<01425> 0122064E S WM_ERASEBKGND hdc:94011D4E
<01426> 0122064E R WM_ERASEBKGND fErased:True
<01427> 0122064E S WM_GETTEXTLENGTH
<01428> 0122064E R WM_GETTEXTLENGTH cch:0
<01429> 0122064E S WM_GETTEXT cchTextMax:2 lpszText:0012D0C0
<01430> 0122064E R WM_GETTEXT cchCopied:0 lpszText:0012D0C0 ("")
<01431> 0122064E S WM_GETTEXTLENGTH
<01432> 0122064E R WM_GETTEXTLENGTH cch:0
<01433> 0122064E S WM_GETTEXT cchTextMax:2 lpszText:0012D0C0
<01434> 0122064E R WM_GETTEXT cchCopied:0 lpszText:0012D0C0 ("")
<01435> 010D0674 S WM_WINDOWPOSCHANGING lpwp:0012D4B0
<01436> 010D0674 R WM_WINDOWPOSCHANGING
<01437> 010D0674 S CB_GETCURSEL
<01438> 010D0674 R CB_GETCURSEL index:CB_ERR
<01439> 010D0674 S WM_GETTEXTLENGTH
<01440> 01360696 S WM_GETTEXTLENGTH
<01441> 01360696 R WM_GETTEXTLENGTH cch:2
<01442> 010D0674 R WM_GETTEXTLENGTH cch:2
<01443> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012CC44
<01444> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012BE64
<01445> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012BE64 ("a")
<01446> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012CC44 ("a")
<01447> 010D0674 S CB_GETCURSEL
<01448> 010D0674 R CB_GETCURSEL index:CB_ERR
<01449> 010D0674 S WM_GETTEXTLENGTH
<01450> 01360696 S WM_GETTEXTLENGTH
<01451> 01360696 R WM_GETTEXTLENGTH cch:2
<01452> 010D0674 R WM_GETTEXTLENGTH cch:2
<01453> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012CC44
<01454> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012BE64
<01455> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012BE64 ("a")
<01456> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012CC44 ("a")
<01457> 010D0674 S CB_GETCURSEL
<01458> 010D0674 R CB_GETCURSEL index:CB_ERR
<01531> 0122064E R WM_PAINT
<01532> 010D0674 S WM_PAINT hdc:00000000
<01533> 010D0674 S WM_NCPAINT hrgn:00000001
<01534> 010D0674 R WM_NCPAINT
<01535> 010D0674 S WM_ERASEBKGND hdc:0F0141ED
<01536> 010D0674 R WM_ERASEBKGND fErased:True
<01537> 0122064E S WM_CTLCOLOREDIT hdcEdit:840137F1 hwndEdit:010D0674
<01538> 0122064E R WM_CTLCOLOREDIT hBrush:F0103EB0
<01539> 010D0674 R WM_PAINT
<01540> 01360696 S WM_PAINT hdc:00000000
<01541> 01360696 S WM_NCPAINT hrgn:00000001
<01542> 01360696 R WM_NCPAINT
<01543> 01360696 S WM_ERASEBKGND hdc:C7011AA6
<01544> 01360696 R WM_ERASEBKGND fErased:True
<01545> 010D0674 S WM_CTLCOLOREDIT hdcEdit:870137F1 hwndEdit:01360696
<01546> 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0
<01547> 010D0674 S WM_CTLCOLOREDIT hdcEdit:870137F1 hwndEdit:01360696
<01548> 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0
<01549> 01360696 R WM_PAINT
<01555> 0122064E S WM_CTLCOLOREDIT hdcEdit:8A0137F1 hwndEdit:010306AC
<01556> 0122064E R WM_CTLCOLOREDIT hBrush:78103C5B
<01568> 010D0674 S CB_GETCURSEL
<01569> 010D0674 R CB_GETCURSEL index:CB_ERR
<01570> 010D0674 S WM_GETTEXTLENGTH
<01571> 01360696 S WM_GETTEXTLENGTH
<01572> 01360696 R WM_GETTEXTLENGTH cch:2
<01573> 010D0674 R WM_GETTEXTLENGTH cch:2
<01574> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D7A4
<01575> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C9C4
<01576> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C9C4 ("a")
<01577> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D7A4 ("a")
<01578> 010D0674 S CB_GETCURSEL
<01579> 010D0674 R CB_GETCURSEL index:CB_ERR
<01580> 010D0674 S WM_GETTEXTLENGTH
<01581> 01360696 S WM_GETTEXTLENGTH
<01582> 01360696 R WM_GETTEXTLENGTH cch:2
<01583> 010D0674 R WM_GETTEXTLENGTH cch:2
<01584> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D6E0
<01585> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C900
<01586> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C900 ("a")
<01587> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D6E0 ("a")
<01588> 010D0674 S CB_GETCURSEL
<01589> 010D0674 R CB_GETCURSEL index:CB_ERR
<01590> 010D0674 S WM_GETTEXTLENGTH
<01591> 01360696 S WM_GETTEXTLENGTH
<01592> 01360696 R WM_GETTEXTLENGTH cch:2
<01593> 010D0674 R WM_GETTEXTLENGTH cch:2
<01594> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D6E0
<01595> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C900
<01596> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C900 ("a")
<01597> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D6E0 ("a")
<01598> 010D0674 R message:0x2111 [User-defined:WM_USER+7441] lResult:00000000
<01599> 01360696 S WM_GETTEXTLENGTH
<01600> 01360696 R WM_GETTEXTLENGTH cch:2
<01601> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012DF8C
<01602> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012DF8C ("a")
<01603> 010D0674 R WM_COMMAND
<01604> 01360696 P WM_KEYUP nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:1

Letter q
<01625> 01360696 P WM_KEYDOWN nVirtKey:'Q' cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01626> 010D0674 S WM_GETDLGCODE
<01627> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01628> 010D0674 S WM_GETDLGCODE
<01629> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01630> 010D0674 S WM_GETDLGCODE
<01631> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01632> 010D0674 S WM_GETDLGCODE
<01633> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01634> 01360696 P WM_CHAR chCharCode:'0071' (113) cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01635> 010D0674 S WM_GETDLGCODE
<01636> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01637> 010D0674 S WM_GETDLGCODE
<01638> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01640> 01360696 P WM_KEYUP nVirtKey:'Q' cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:1 fUp:1

A: By any chance, have you already solved your problem?
I have the same problem as yours, my custom control for DataGridView cannot receive letter Q, period, dollar, single quote, percent, etc.
I was able to solve the problem by changing the "switch .. default: return false" to "switch .. default: return !dataGridViewWantsInputKey"
I guess the pattern code from Microsoft for making your own usercontrol for datagridview is not optimal.  This is the pattern code from Microsoft:
http://msdn.microsoft.com/en-au/library/7tas5c80(vs.80).aspx
public bool EditingControlWantsInputKey(
    Keys key, bool dataGridViewWantsInputKey)
{
    // Let the DateTimePicker handle the keys listed.
    switch (key & Keys.KeyCode)
    {
        case Keys.Left:
        case Keys.Up:
        case Keys.Down:
        case Keys.Right:
        case Keys.Home:
        case Keys.End:
        case Keys.PageDown:
        case Keys.PageUp:
            return true;
        default:
            return false; // I changed this to: return !dataGridViewWantsInputKey.  My usercontrol can now receive Q, period, dollar, etc.
    }
}

A: Partial answer to my question.   In the Combobox I handle the KeyDown, TextChanged, and KeyUp events, which fire in that order.  If I go from KeyDown to KeyUp with TextChanged skipped, I check whether the character was a Keys.Q or Keys.OemPeriod.  (I'm not sure it's safe to others, like shift/D1, shift/D2, etc...).    If it's one of those keys, I change the combobox text myself.
But that's not enough, because merely changing the text sets the cursor in the edit control (that belongs to the combobox) to the start of the text.   So, to fix that,  I use FindWindowEx to get the handle of the edit control, then send it a EM_SETSEL to reset the cursor to the end of the word.


text:
Q: ASP.NET FormView DetailsView and polymorphism I'm writing an ASP.NET Master Page that does the common grunt work for master/detail editing (ValidationSummary, error handling, popup of detail view using jQuery-ui dialog).  It has two ContentPlaceHolder controls for the master and detail views, the master placeholder is expected to contain a GridView, and the detail placeholder either a DetailsView or a FormView.
The master page just needs to access a few basic members of the DetailsView or FormView:

*

*ChangeMode method

*DataBind method

*CurrentMode property

*InsertItem method

*UpdateItem method

I was surprised to see that, while both DetailsView and FormView have these same members, they are not (except DataBind) inherited from a common base class or interface.  There are even two equivalent enums FormViewMode and DetailsViewMode, so that the ChangeMode and CurrentMode members don't even have the same signature.
I am intending to get round this by creating a wrapper class, but can anyone explain why they are implemented like this?  Am I storing up trouble by attempting to use them polymorphically?
I find it hard to believe that this was not deliberate on the part of Microsoft's engineers, so I can only conclude that they intended to discourage polymorphic use.

A:
while both DetailsView and FormView have these same members, they are
  not inherited from a common base class or interface.

Yes they are:
DetailsView : CompositeDataBoundControl, IDataItemContainer, INamingContainer, ICallbackContainer, ICallbackEventHandler, IPostBackEventHandler, IPostBackContainer, IDataBoundItemControl, IDataBoundControl, IFieldControl
FormView : CompositeDataBoundControl, IDataItemContainer, INamingContainer, IPostBackEventHandler, IPostBackContainer, IDataBoundItemControl, IDataBoundControl, IRenderOuterTableControl


text:
Q: How to get markers inside an area selected by mouse drag? In Brief
I want to find all the markers which lie within a rectangular area created by dragging the mouse over the map. Is this feature supported by any jQuery plugins or something else? If not, I would like to implement this in my project. I think it would be cool.
Details
I am using Google Maps v2 because I want to support IE 6 in my project.
I am a beginner in Maps and went through the Developer's guide section and some basic demos and other SO questions.
Here is my idea so far -

*

*User clicks on a "Select an area" button in the controls section of the map. This calls disableDragging() and user is ready to do a selection. (May be http://code.google.com/apis/maps/documentation/javascript/v2/controls.html#Custom_Controls gives some idea how to do this)

*Then user does an area selection. The selection start and selection end points are noted and assuming these as the two opposite corners of the rectangle, the markers within  it are found. But, so far I did not see any working code to get the coordinates of the clicked point. I guess it is better to go with latitude/longitude as the coordinates instead of the actual x-y coordinates. This question Google Maps API using jQuery Plugin: How to get a marker's latitude and longitude on click? discusses getting the latitude/longitudes of a marker on clicking it, but I have not successfully tried it yet.
Summary
Here are my questions again -

*

*How do I display a rectangular selection area over the map ? (generally slight grey and transparent in appearance)

*How to get the lat/lang(latitude/longitude) of the clicked point and then extend it to get those of the selection start and end points.
I am experienced with jQuery and if there are some nice solutions with jQuery plugins them please let me know. I saw this list of 10 jQuery Plugins for Easier Google Map Installation but not sure if any of those would help me meet my requirement.
When I have the list of markers, I would like to populate some related info inside a separate display section, so that every time the user selects some markers, corresponding information is displayed in the display section. That part should easier.
Thanks

A: You can check KeyDragZoom  example under Google Maps API Demo Gallery to achieve rectangular selection feature. You can find the documentation here.
For the second problem you can use GLatLngBounds class and its containsLatLng(latlng:GLatLng) function. By setting your GLatLngBounds object to the bounds of your rectangle you can test your markers against it with containsLatLng function.
If you decide to use KeyDragZoom, adding a dragend listener to the getDragZoomObject will give you a GLatLngBounds object which you can use to test your markers against with the containsLatLng function.
map.enableKeyDragZoom();
var dz = map.getDragZoomObject();
GEvent.addListener(dz, 'dragend', function (bnds) {
  // test your markers against bnds here
});


text:
Q: GitHub Pages (jekyll blog) showed 404 I tried to build up a Jekyll blog website using GitHub pages. I could check the homepage, but the subpages (about & blogposts) showed 404.
To find out where the problem is, I opened a new repo. And I set up the basic things of a Jekyll site using jekyll new . locally and uploaded them to the Github repo. I did not change anything after this step.
And then, I used jekyll serve to run the local test, and everything went well. The layout looked nice and I could check the first blog "Welcome to Jekyll!"(built by default).
However, when I used the link of GitHub Pages to check, the layout of the homepage looked quite different, and I could not check the default blogpost "Welcome to Jekyll!", which showed me 404.
How can I fix it?
This is my repo: https://github.com/jl-xie-kcl/blog20211122
(you can check the screenshots in issue 2 https://github.com/jl-xie-kcl/blog20211122/issues/2)

A: Those pages do work, your links are just incorrect because your blog is not at the root of your domain — and this goes the same for the style and images not working, by the way:

*

*The link to your about page: https://jl-xie-kcl.github.io/blog20211122/about

*The link to your blog post: https://jl-xie-kcl.github.io/blog20211122/jekyll/update/2021/11/22/welcome-to-jekyll.html

In order to fix this, you will have to change the baseurl value in your _config.yml to:
baseurl: "/blog20211122"

As stated by the comment on this configuration line:
baseurl: "" # the subpath of your site, e.g. /blog


text:
Q: Прокси в браузере Ребят, появился вопрос, не по программированию, правда. Может, кто знает и поможет мне.
Задача: Присвоить каждой вкладе в браузере проксю или же открыть N браузеров, независимых друг от друга (чтобы можно было в них указать проксю).
Как пробовал:

*

*Через portable-версию мозиллы - не получается, при открытии второй копии portable-версии мозилла выдает ошибку (что копия уже запущена).

*Попробовал запустить эту portable версию через SandBoxie - результат одинаковый.

*Пробовал через браузер k-meleon, к сожалению, там присваивается прокся ко всему браузеру, а не ко вкладкам.

*Пробовал различные профили в браузерах - тоже не дало результата.

Надеюсь на вашу помощь, спасибо!
A: Вариант 1:
В Firefox создаём профили (запуск менеджера профилей с ключем firefox.exe -p). Затем после создания профилей создаём ярлыки на запуск с каждым профилем: "C:\Program Files\Mozilla Firefox\firefox.exe" -p prof1 -no-remote.
ВАЖНО использовать ключ *-no-remote*, он позволяет запускать множество копий Огнелиса. Устанавливаем на каждый профиль дополнение "FoxyProxy" (как-то так называлось) - и вуаля! Еще можно "CookieManager", если хотите тыщу вконтактов открыть. :)
Вариант 2:
Можно запускать приватные окна, в них будут доступны дополнения профиля, из которого были окна запущены, но сами по себе они будут независимы. Минус - после закрытия все данные пропадают (заполненные формы, история адресов).


text:
Q: Create Object and its Properties at Run-time from List I need to create dynamic object and its properties at run-time then create instance of this object to store values.
why I want above logic!
I am reading excel file in C# and first line of code is header which is actually  properties and followed by each rows are record which is instance of dynamic object.
 List<string> ExcelDataHeader = new List<string>();
         for (int y = 2; y <= colCount; y++)
           {
             ExcelDataHeader.Add(xlRange.Cells[headerRow, y].Value2.ToString());
           }

  dynamic MyDynamic = new System.Dynamic.ExpandoObject();
    ??????????

I need to return excel read data in object

A: You could use ExpandoObject here - it'll work, but you need to use the dictionary API:
IDictionary<string, object> obj = new ExpandoObject();
obj["id"] = 123;
obj["name"] = "Fred";

// this is the "dynamic" bit:
dynamic dyn = obj;
int id = dyn.id; // 123
string name = dyn.name; // "Fred"

However, I fail to see the point. Since you won't be referring to the object in C# code by things like obj.PropertyName, dynamic has very little purpose. You might as well just store each record in a Dictionary<string,object> or similar. Given what you describe, there are no places where you would actually use MyDynamic as a dynamic object.


text:
Q: passing value to a jsp page from a java class using DAO I wanted to pass the value retrieved on a java class to a  page.I am using DAO classes.
I have retrieved the values from the database and stored them on String variables.Now I want to set them to the text boxes in my view.jsp page.I am new to this area,can anyone help me out??
View.jsp is as
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>

    <form action="process.jsp">
    Enter Name

 <input type="text" name="uname"  onclick="this.value=''"/>

    <input type="submit" value="view details"/>

    Email id:
 <input type="text"  name="email"  id="email" >

    password:
 <input type="text"  name="passw"  id="passw">

    </form>

and My Activity ViewDAO.java is as
 public static void  view(user u) {
    Connection con=ConnectionProvider.getCon();
    String uname=u.getUname();
    try {
        PreparedStatement ps=con.prepareStatement("select email,pass from  S1.USER432 where name='"+uname+"'");
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {

            String email = rs.getString("EMAIL");
            String pass = rs.getString("PASS");

            }

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }
}

Thanks...

A: If you are using a front controller[spring mvc] then you can pass the data by doing,
model.addAttribute("variable_name ", data);
and in the jsp you can access it by doing this ${variable_name};

A: if you are using simple jsp and servelt, then make one ViewController.java.
You can two methods one for handling GET and other for POST
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String email = request.getParameter("email");
            String password = request.getParameter("password");

    request.setAttribute("email", email);
            request.setAttribute("password", password);
                        request.getRequestDispatcher("view.jsp").forward(request, response);
         }
        catch(Exception e){

        }

View.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>

    <form action="process.jsp">
    Enter Name

 <input type="text" name="uname"  onclick="this.value=''"/>

    <input type="submit" value="view details"/>

    Email id:
 <input type="text"  name="email"  id="email" value="<%=email%>" >

    password:
 <input type="text"  name="passw"  id="passw" value="<%=password%>">

    </form>

A: The Servlet decides which page must be loaded. So whatever you get from the DAO must go to the Servlet and through that, to the jsp. You can use a bean class to send values from DAO to Servlet.
Like this,
public class Details{
  private String email;
  private String password;

  public void setEmail(String email){
    this.email = email;

  }
  public void setPassword(String password){
    this.password= password;

  }
  public String getEmail(){
     return this.email;
  }
  public String getPassword(){
     return this.password;
  }

}

And you can make the following changes in DAO after getting the query results in the String. Add these
Details d = new Details();
d.setEmail(email);
d.setPassword(pass);
return d;

You can pass this object d to the servlet and retrieve the values using the getter methods of the bean. Also, the DAO must be called from the Servlet.
And now on the Servlet side.
On the Servlet you can put your code in the get or post method depending on your need. It may be like
public class ExampleServlet extends HttpServlet{

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

String email = request.getParameter("email"); //got from the jsp where "email" is the name attribute of the input field
Details d = new Details();
d = ViewDao.view(user_object); //the bean sent by DAO. "user_object" is parameter that your DAO method is taking in your code

if(d.getEmail()!=null){ //just an example

 // your code that redirects desired page
}

}
}

Based on d returned by the DAO you may redirect to any page you want.

A: You need to call the DAO method from your servlet like below:
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      // call DAO method to get the email and password
    HashMap<String,String> map=ViewDAO.getDetails();

    //from the map you will get the  email and password.then you need to set them in the attributes and get them in your jsp

     request.setAttribute("email", map.get("email"));
      request.setAttribute("password", map.get("password"));

}

your DAO method should be like the below:
public static HashMap<String,String>  getDetails(user u) {
    Connection con=ConnectionProvider.getCon();
    String uname=u.getUname();
    Map<String,String> map=new HashMap<>();
    try {
        PreparedStatement ps=con.prepareStatement("select email,pass from  S1.USER432 where name='"+uname+"'");
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {

            String email = rs.getString("EMAIL");
            String pass = rs.getString("PASS");

            }
       map.put("email",email);
       map.put("password",pass);

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return map;
    }
}

Hope this will help you.

A: Something like that
Observe this import
dao.UserDao,bean.*,

*

*dao is the package

*UserDao is the class

*bean is the method you want or is could an attribute from dao

remember that
jsp

<%@page import="dao.UserDao,bean.*,java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Users List

<%
List<User> list=UserDao.getAllRecords();
request.setAttribute("list",list);
%>

    <thread class="bg-info">
        Id	Name	Password	Edit	Delete
    </thread>
        <c:forEach items="${list}" var="u">

        ${u.getId()}	${u.getUsername()}	${u.getPassword()}
        Edit
        Delete

        </c:forEach>

Add New User

 <form action="index.jsp">
         <button type="submit">IndexUsers</button>
  </form>

Bean or model
package bean;
// classe para as tables
public class User {

    private int id;
    private String username,password;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}

dao
public class UserDao {
    public static Connection getConnection(){
        Connection con=null;
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql_database","root","14570");
        }catch(Exception e){System.out.println(e);}
        return con;
    }
    public static int save(User u){
        int status=0;
        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement(
    "insert into login(username,password) values(?,?)");
            ps.setString(1,u.getUsername());
            ps.setString(2,u.getPassword());

            status=ps.executeUpdate();
        }catch(Exception e){System.out.println(e);}
        return status;
    }
    public static int update(User u){
        int status=0;
        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement(
    "update login set username=?,password=? where id=?");
            ps.setString(1,u.getUsername());
            ps.setString(2,u.getPassword());

            ps.setInt(3,u.getId());
            status=ps.executeUpdate();
        }catch(Exception e){System.out.println(e);}
        return status;
    }
    public static int delete(User u){
        int status=0;
        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement("delete from login where id=?");
            ps.setInt(1,u.getId());
            status=ps.executeUpdate();
        }catch(Exception e){System.out.println(e);}

        return status;
    }
    public static List<User> getAllRecords(){
        List<User> list=new ArrayList<User>();

        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement("select * from login");
            ResultSet rs=ps.executeQuery();
            while(rs.next()){
                User u=new User();
                u.setId(rs.getInt("id"));
                u.setUsername(rs.getString("username"));
                u.setPassword(rs.getString("password"));

                list.add(u);
            }
        }catch(Exception e){System.out.println(e);}
        return list;
    }
    public static User getRecordById(int id){
        User u=null;
        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement("select * from login where id=?");
            ps.setInt(1,id);
            ResultSet rs=ps.executeQuery();
            while(rs.next()){
                u=new User();
                u.setId(rs.getInt("id"));
                u.setUsername(rs.getString("username"));
                u.setPassword(rs.getString("password"));

            }
        }catch(Exception e){System.out.println(e);}
        return u;
    }

}

A: Another Example this import import="dao.*"% makes available any methods from package dao, Bellow you see how to get the result of the method countid() in the dao.
<%@page import="dao.*"%>

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% int id = 0; %>
<%
DaoEvento daoEvento = new DaoEvento();
id = daoEvento.countId();
%>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

        <form action="add_event_servletnew" method="POST">

                    <%= request.getParameter("message") %>

                    view

                        id
                        <input type="text" name="id" value="<%= id%>" readonly="readonly" class="form-control"/>

                        Title
                        <input type="text" name="title" value="" class="form-control" />

                        Start
                        <input type="date" name="start" value="" class="form-control"/>

                        End
                        <input type="date" name="end" value="" class="form-control" />

                        <input type="submit" value="submit" class="btn btn-success btn-block"/>

        </form>


text:
Q: swift: Crash on physicsBody from texture I made a node called bone which is made from a bone image. This node works perfectly. After I render it, I try to create a SKPhysicsBody for it, but that line causes a crash. I can't figure out whats the problem.
Here, I declare the SKSpriteNode on top of the class
let bone = SKSpriteNode(imageNamed: "bone")
Here, I set it up. The last line is the one that causes the crash.
bone.anchorPoint = CGPointMake(0.5, 0.5)
bone.position.x = CGFloat(arc4random() % (UInt32(self.view.frame.size.width)) + 1)
bone.position.y = CGRectGetMaxY(self.frame) + bone.size.height/2

self.addChild(bone)

let boneBody = SKPhysicsBody(texture: self.view.textureFromNode(bone), size: bone.size)

Thanks in advance.


text:
Q: Can not build ios app into device because "embedded framework 'SharedCode.framework' was built for iOS Simulator." I use Kotlin Native (multiplatform) and I have create a TestKotinNative app, but only work when run on simulator.
When I run on my device (iphone 7, 13.4.1), xcode show error "TestKotlinNative.xcodeproj Building for iOS, but the linked and embedded framework 'SharedCode.framework' was built for iOS Simulator."
My Xcode version: 11.4.1
Please help me! Thank
This is my build.gradle.kts (same with https://play.kotlinlang.org/hands-on/Targeting%20iOS%20and%20Android%20with%20Kotlin%20Multiplatform/06_SettingUpKotlinFramework)
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget

plugins {
    kotlin("multiplatform")
}

kotlin {
    //select iOS target platform depending on the Xcode environment variables
    val iOSTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget =
        if (System.getenv("SDK_NAME")?.startsWith("iphoneos") == true)
            ::iosArm64
        else
            ::iosX64

    iOSTarget("ios") {
        binaries {
            framework {
                baseName = "SharedCode"
            }
        }
    }

    jvm("android")

    sourceSets["commonMain"].dependencies {
        implementation("org.jetbrains.kotlin:kotlin-stdlib-common")
    }

    sourceSets["androidMain"].dependencies {
        implementation("org.jetbrains.kotlin:kotlin-stdlib")
    }

}

val packForXcode by tasks.creating(Sync::class) {
    val targetDir = File(buildDir, "xcode-frameworks")

    /// selecting the right configuration for the iOS
    /// framework depending on the environment
    /// variables set by Xcode build
    val mode = System.getenv("CONFIGURATION") ?: "DEBUG"
    val framework = kotlin.targets
        .getByName<KotlinNativeTarget>("ios")
        .binaries.getFramework(mode)
    inputs.property("mode", mode)
    dependsOn(framework.linkTask)

    from({ framework.outputDirectory })
    into(targetDir)

    /// generate a helpful ./gradlew wrapper with embedded Java path
    doLast {
        val gradlew = File(targetDir, "gradlew")
        gradlew.writeText("#!/bin/bash\n"
                + "export 'JAVA_HOME=${System.getProperty("java.home")}'\n"
                + "cd '${rootProject.rootDir}'\n"
                + "./gradlew \$@\n")
        gradlew.setExecutable(true)
    }
}

tasks.getByName("build").dependsOn(packForXcode)

enter image description here

A: A dirty way to keep using the new versions of xCode with Kotlin multiplatform framework is...
Before change the platform (simulator and iphone) to run your project just go in frameworks location and delete the framework file. XCode will re-built your framework and app will deploy on your choosen platform

A: In your script, you declare the iOSTarget variable to be always set for iosX64 target, which is a simulator. In the hands-on example, the idea was to choose targets depending on the Xcode build settings. but in your code, this part is commented leaving the only simulator set by default. Try fixing it to be exactly as in the hands-on final version(see it here)


text:
Q: 'sudo apt autoremove python3' removed a lot of packages here is a list of packages that were to be removed and I hastily pressed yes and deleted a lot of packages
aisleriot apparmor apport apport-gtk aptdaemon apturl apturl-common blender blender-data caribou chrome-gnome-shell
  command-not-found dh-python fastjar firefox flashplugin-installer fonts-dejavu fonts-lato foomatic-db-compressed-ppds gconf2 gdebi
  gdebi-core gdm3 gedit geoclue-ubuntu-geoip gimp-help-common gimp-help-en gir1.2-ibus-1.0 gksu gnome-menus gnome-music gnome-orca
  gnome-power-manager gnome-screensaver gnome-shell gnome-shell-extensions gnome-software gnome-terminal google-chrome-stable
  gsettings-ubuntu-schemas hplip hplip-data ibus ibus-pinyin ibus-table indicator-applet indicator-bluetooth indicator-datetime
  indicator-keyboard indicator-messages indicator-power indicator-session indicator-sound jarwrapper language-selector-common
  libaccount-plugin-1.0-0 libaccount-plugin-generic-oauth libaccount-plugin-google libaio1 libappindicator1 libatk-wrapper-java
  libatk-wrapper-java-jni libavdevice-ffmpeg56 libbonobo2-0 libbonobo2-common libbonoboui2-0 libbonoboui2-common
  libboost-locale1.58.0 libboost-regex1.58.0 libboost-thread1.58.0 libcolorpicker-java libevent-core-2.0-5 libfcitx-config4
  libfcitx-gclient0 libfcitx-utils0 libfontchooser-java libgeonames0 libgksu2-0 libglade2-0 libgnome-2-0 libgnome2-0 libgnome2-bin
  libgnome2-common libgnomecanvas2-0 libgnomecanvas2-common libgnomeui-0 libgnomeui-common libgnomevfs2-0 libgnomevfs2-common
  libindicator7 libjemalloc1 liblightdm-gobject-1-0 libopencolorio1v5 libopenimageio1.6 liborbit-2-0 libpanel-applet0 libpurple-bin
  libruby2.3 libsnapd-glib1 libspnav0 libtimezonemap-data libtimezonemap1 libtinyxml2.6.2v5 libunity-settings-daemon1
  liburl-dispatcher1 libyaml-cpp0.3v5 lightdm linux-headers-4.10.0-32 linux-headers-4.10.0-32-generic linux-headers-4.10.0-33
  linux-headers-4.10.0-33-generic linux-headers-4.4.0-93 linux-headers-4.4.0-93-generic linux-headers-4.4.0-96
  linux-headers-4.4.0-96-generic linux-image-4.10.0-32-generic linux-image-4.10.0-33-generic linux-image-4.4.0-93-generic
  linux-image-4.4.0-96-generic linux-image-extra-4.10.0-32-generic linux-image-extra-4.10.0-33-generic
  linux-image-extra-4.4.0-93-generic linux-image-extra-4.4.0-96-generic linux-signed-image-4.10.0-32-generic
  linux-signed-image-4.10.0-33-generic lsb-release mysql-client-5.7 mysql-client-core-5.7 mysql-server mysql-server-5.7
  mysql-server-core-5.7 nautilus-share openprinting-ppds plymouth-theme-ubuntu-gnome-text plymouth-theme-ubuntu-text
  printer-driver-foo2zjs printer-driver-foo2zjs-common printer-driver-postscript-hp printer-driver-ptouch printer-driver-pxljr
  python-pyatspi python3 python3-apport python3-apt python3-aptdaemon python3-aptdaemon.gtk3widgets python3-aptdaemon.pkcompat
  python3-brlapi python3-bs4 python3-cairo python3-chardet python3-commandnotfound python3-cups python3-cupshelpers python3-dbus
  python3-debian python3-defer python3-distupgrade python3-gdbm python3-gi python3-gi-cairo python3-html5lib python3-louis
  python3-lxml python3-mako python3-markupsafe python3-pexpect python3-pil python3-pkg-resources python3-problem-report
  python3-ptyprocess python3-pyatspi python3-pycurl python3-renderpm python3-reportlab python3-reportlab-accel python3-requests
  python3-six python3-software-properties python3-speechd python3-systemd python3-uno python3-update-manager python3-urllib3
  python3-xdg python3-xkit rake rhythmbox rhythmbox-plugin-magnatune rhythmbox-plugin-zeitgeist rhythmbox-plugins ruby
  ruby-did-you-mean ruby-minitest ruby-net-telnet ruby-power-assert ruby-test-unit ruby2.3 rubygems-integration sessioninstaller
  signon-keyring-extension signon-plugin-oauth2 snapd snapd-login-service software-properties-common software-properties-gtk
  system-config-printer-common system-config-printer-gnome system-config-printer-udev totem-plugins ubuntu-core-launcher
  ubuntu-drivers-common ubuntu-gnome-desktop ubuntu-minimal ubuntu-release-upgrader-core ubuntu-release-upgrader-gtk ubuntu-standard
  ubuntu-system-service ubuntu-touch-sounds ufw unattended-upgrades unity-control-center unity-control-center-signon unity-greeter
  unity-settings-daemon unoconv update-manager update-manager-core update-notifier update-notifier-common usb-creator-common
  usb-creator-gtk vim-gnome vim-gui-common vim-runtime xdiagnose

visually speaking everythings looks and works the same, some software like chrome, firefox, gedit, vim, mysql, and even the gnome-terminal were gone but I got those back.
I'm thinking of doing a clean install, but since I don't see much difference then should I just manually reinstall stuff that I use and lost?
How do go about getting these packages back?
running
sudo apt install x y z

kind of command gives error and I can't install all packages this way like xdiagnos.
I have done a backup of just my data and not the whole system so I can't just go back to a earlier state.


text:
Q: Share Email Folder Using mdapi I am using financialforcedev's mdapi to create folder sharing in my Salesforce org - https://github.com/financialforcedev/apex-mdapi
I am using the following code for Sharing DashboardFolder which works absolutely fine.
 @future(callout=true)
public static void shareDashboardFolder(String brandAPIName, String brandManagerRoleAPIName, String brandAgentAPIName)
{
    // Retrieve Folder
    MetadataService.MetadataPort service = createService();
    MetadataService.DashboardFolder folder = (MetadataService.DashboardFolder) service.readMetadata('DashboardFolder',
                                                                        new String[] { brandAPIName }).getRecords()[0];
    MetadataService.FolderShare folderShareServiceManager = new MetadataService.FolderShare();
    MetadataService.FolderShare folderShareService = new MetadataService.FolderShare();
    folderShareService.accessLevel = 'View';
    folderShareService.sharedTo = brandAPIName;
    folderShareService.sharedToType = 'Role';
    System.debug('Dashboard Folder :::::: '+folder);
    folder.folderShares.add(folderShareService);
    service.updateMetadata( new MetadataService.Metadata[] { folder });
}

However, when I try doing the same using EmailFolder, I get a null pointer exception on line - folder.folderShares.add(folderShareService);
      @future(callout=true)
public static void shareDashboardFolder(String brandAPIName, String brandManagerRoleAPIName, String brandAgentAPIName)
{
    // Retrieve Folder
    MetadataService.MetadataPort service = createService();
    MetadataService.EmailFolder folder = (MetadataService.EmailFolder) service.readMetadata('EmailFolder',
                                                                        new String[] { brandAPIName }).getRecords()[0];
    MetadataService.FolderShare folderShareServiceManager = new MetadataService.FolderShare();
    MetadataService.FolderShare folderShareService = new MetadataService.FolderShare();
    folderShareService.accessLevel = 'View';
    folderShareService.sharedTo = brandAPIName;
    folderShareService.sharedToType = 'Role';
    System.debug('Email Folder :::::: '+folder);
    folder.folderShares.add(folderShareService);
    service.updateMetadata( new MetadataService.Metadata[] { folder });

I tried comparing the two debug logs statements and it shows that folder.folderShares is coming up as empty for the Email Folder and not for the Dashboard Folder and I am not sure why that it.
Debug log statements as printed
 DashboardFolder:[Folder.accessType=null, Folder.folderShares=null, Folder.name=null, Folder.publicFolderAccess=null, Folder.sharedTo=null, Metadata.fullName=null, accessType=null, accessType_type_info=(accessType, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false), apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false), field_order_type_info=(fullName, accessType, folderShares, name, publicFolderAccess, sharedTo), folderShares=(FolderShare:[accessLevel=Manage, accessLevel_type_info=(accessLevel, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false), apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false), field_order_type_info=(accessLevel, sharedTo, sharedToType), sharedTo=madhurima.bhowmick@qunomedical.com, sharedToType=User, sharedToType_type_info=(sharedToType, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false), sharedTo_type_info=(sharedTo, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false)]), folderShares_type_info=(folderShares, http://soap.sforce.com/2006/04/metadata, null, 0, -1, false), fullName=Thirty_Two_Account, fullName_type_info=(fullName, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false), name=Thirty Two Account, name_type_info=(name, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false), publicFolderAccess=null, publicFolderAccess_type_info=(publicFolderAccess, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false), sharedTo=null, sharedTo_type_info=(sharedTo, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false), type=DashboardFolder, type_att_info=(xsi:type)]

 EmailFolder:[Folder.accessType=null, Folder.folderShares=null, Folder.name=null, Folder.publicFolderAccess=null, Folder.sharedTo=null, Metadata.fullName=null, accessType=null, accessType_type_info=(accessType, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false), apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false), field_order_type_info=(fullName, accessType, folderShares, name, publicFolderAccess, sharedTo), folderShares=null, folderShares_type_info=(folderShares, http://soap.sforce.com/2006/04/metadata, null, 0, -1, false), fullName=null, fullName_type_info=(fullName, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false), name=null, name_type_info=(name, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false), publicFolderAccess=null, publicFolderAccess_type_info=(publicFolderAccess, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false), sharedTo=null, sharedTo_type_info=(sharedTo, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false), type=EmailFolder, type_att_info=(xsi:type)]


text:
Q: Feature Vector Builder - What design pattern can be useful? My problem looks very simply, but only at first sight (for me :P ).
I need to create a class which builds a feature vector. This feature vector represents a text. Features are like : Avarage word lenght, Number of sentences in hole text etc.
Some Features can be extracted during other features computation, thats why I've modified a Builder design pattern a little, and it looks like this:
I am creating a builder object:
FeatureVectorBuilder fvb = new FeatureVectorBuilder(String text/InputStream <- now it doesn't matter)

then I am specifing an order, its express which features I want to include
fvb.setLenghtWord(True) <- for fixed length features
fvb.setXXXFeature(32) <- for variable length features

next i am building this vector:
fvb.buildFeatureVector() <- this way computations are optimized;

and finally I have a FeatureVector to get.
fvb.getFeatureVector();

Everything looks ok, but... there is about 32 different features to set...
This way, pessimistic case need 32 functions invocations, also creating a function with 32 parameters looks stupid.
I am wondering if somebody was struggeling with such a problem and maybe there is better solution than "32 different methods" approach :)

A: One of the points of the builder pattern is to avoid methods with a large number of parameters by replacing them with several methods in the builder. If you have 32 possible features, it looks normal to me to have 32 methods in the builder.
Another possibility is to design each feature as a class, and to add instances of those classes in your builder:
builder.addFeature(new LengthWordFeature(true))
       .addFeature(new XxxFeature(32));

A: One possibility to encapsulate the features cleanly would be:
abstract class Feature
{
    String name;
    ...
}

class NumericFeature extends Feature
{
    int value;
}

class OtherFeatureType extends Feature
{
    ....
}

Feature[] features = new Feature[] {
    new NumericFeature("xxxFeature", 32),
    new OtherFeature("feature1", ...),
    ...
};

FeatureVectorBuilder fvb = new FeatureVectorBuilder(text, features);


text:
Q: Floating action button layout anchor not working I want a floating action button in between my two relative layouts.
For this I have taken parent layout as coordinator layout and specified the anchor and anchor gravity to fab button.
But its not getting set where I want it to be.
I want it to set at right corner of relative layout6 at the end and between relative layout6 and relative layout3 on right corner.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/bg"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@+id/relativeLayoutParent"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/imageView5"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginEnd="30dp"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginStart="30dp"
                android:layout_marginTop="30dp"
                android:background="@color/colorAccent">

                <RelativeLayout
                    android:id="@+id/relativeLayout6"
                    android:layout_width="match_parent"
                    android:layout_height="240dp"
                    android:layout_centerHorizontal="true">

                    <ImageView
                        android:id="@+id/imageView7"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:scaleType="fitXY"
                        app:srcCompat="@drawable/profile_img" />

                    </LinearLayout>

                </RelativeLayout>

                <RelativeLayout
                    android:id="@+id/relativeLayout3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentStart="true"
                    android:layout_below="@+id/relativeLayout6">

            </RelativeLayout>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_anchorGravity="center"
                app:layout_anchor = "@id/linearLayout"
                android:layout_margin="@dimen/fab_margin"
                app:srcCompat="@android:drawable/ic_dialog_email" />
        </LinearLayout>

    </ScrollView>

</android.support.design.widget.CoordinatorLayout>

Please help.. Thank you.

A: Put FloatingActionButton inside CoordinatorLayout. The anchor property only works inside the CoordinatorLayout.
One more thing: Your layout is messy. Please arrange it.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bg"
android:orientation="vertical">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/relativeLayoutParent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/imageView5"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginEnd="30dp"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:layout_marginStart="30dp"
            android:layout_marginTop="30dp"
            android:background="@color/colorAccent" />

        <RelativeLayout
            android:id="@+id/relativeLayout6"
            android:layout_width="match_parent"
            android:layout_height="240dp"
            android:layout_centerHorizontal="true" />

        <ImageView
            android:id="@+id/imageView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/profile_img" />

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/relativeLayout6" />
</ScrollView>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/fab_margin"
    app:layout_anchor="@id/linearLayout"
    app:layout_anchorGravity="center"
    app:srcCompat="@android:drawable/ic_dialog_email" />

A: Too many errors in open and closed tags.

*

*Just before the Imageview, there's a RelativeLayput but you closed it as Linear layout...fix this

*Fix that RelaLayout as RelativeLayout just after scrollview

*Errors in close tag of linear layout

*Open two Relative layouts, only one is closed.

Also, the key to remember Scrollview can host only one direct child.
I've removed all your errors but as Scrollview can only have one child, it's not working as you want it to be.Try to Fix this.
Try constraintLayout with guidelines. You'll find it a better way to anchor something.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/bg"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@+id/relativeLayoutParent"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/imageView5"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginEnd="30dp"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginStart="30dp"
                android:layout_marginTop="30dp"
                android:background="@color/colorAccent">

            <RelativeLayout
                android:id="@+id/relativeLayout6"
                android:layout_width="match_parent"
                android:layout_height="240dp"
                android:layout_centerHorizontal="true">

                  <ImageView
                android:id="@+id/imageView7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:scaleType="fitXY"
                      app:srcCompat="@drawable/profile_img"
                 />

             </RelativeLayout>

         </RelativeLayout>
        </RelativeLayout>

        <RelativeLayout
        android:id="@+id/relativeLayout3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/relativeLayout6">

    </RelativeLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_anchorGravity="center"
        app:layout_anchor = "@id/linearLayout"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

    </ScrollView>

    </android.support.design.widget.CoordinatorLayout>

A: Try this hope it works for you...
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey_200"
    android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <RelativeLayout
            android:id="@+id/relativeLayout6"
            android:layout_width="match_parent"
            android:layout_height="240dp"
            android:layout_centerHorizontal="true">

        <ImageView
            android:id="@+id/imageView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/image" />

            </RelativeLayout>

        </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="60dp"
            android:layout_height="60dp"
            app:layout_anchorGravity="bottom|right|end"
            app:layout_anchor="@+id/appbar"
            android:layout_margin="10dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            app:srcCompat="@android:drawable/ic_dialog_email" />

<android.support.v4.widget.NestedScrollView
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:background="@android:color/white"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <RelativeLayout
        android:id="@+id/relativeLayout3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello world"/>

    </RelativeLayout>
</android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>


text:
Q: Strange Date behavior in Chrome Why these nearly similar date objects give different results in Chrome 37?
var d2014 = new Date(2014, 0, 1);
alert(d2014.getFullYear()); // 2013

var d2015 = new Date(2015, 0, 1);
alert(d2015.getFullYear()); // 2015

In IE11 I get "2014" and "2015" as expected. Browser works in Russian locale. Conversion to strings gives the following results:
d2014.toString();    // Tue Dec 31 2013 23:00:00 GMT+0300 (RTZ 2 (зима))
d2015.toString();    // Thu Jan 01 2015 00:00:00 GMT+0300 (RTZ 2 (зима))

d2014.toUTCString(); // Tue, 31 Dec 2013 20:00:00 GMT
d2015.toUTCString(); // Wed, 31 Dec 2014 21:00:00 GMT

A: This is a chrome specific issue, you can view the discussion here https://code.google.com/p/v8/issues/detail?id=3116 and in https://code.google.com/p/chromium/issues/detail?id=417640 look for
 #31 ulan@chromium.org,
This issue is fixed in version 3.29.39


text:
Q: How to set %xmode Verbose on Jupyter notebook at launch? I want to set %xmode Verbose to get error messages in greater detail, but since I always need it, I rather want to set it at launch.
So I tried adding it on at the bottom of my jupyter_notebook_config.py, but then when I launch it again, it got the following error:

Exception while loading config file /Users/me/jupyter/jupyter_notebook_config.py
SyntaxError: invalid syntax

However, I also added import os, sys, random, asyncio, argparse at the bottom of the file, which did not lead to the error. So I feel the magic command does not work at the config file.
So is there any way to enable Verbose debug mode at default in Jupyter notebook?

Clarification
This question is about Jupyter notebook (open via jupyter notebook), not IPython (open via ipython). I found the %xmode command works in IPython config file (which I have actually used) and want to enable it on Jupyter notebook as well, which is my point.

A: *

*Go to ~/.ipython/profile_default/startup.

*Create a file named 00-set-traceback-mode.py.

*Add the following lines:
from IPython import get_ipython
ip = get_ipython()
ip.InteractiveTB.set_mode(mode="Verbose")

You have done.


text:
Q: What is the minimum distance for a planet to be able to form from a star? I've been playing Starchitect for a while, and I'm trying to create a terrestrial planet orbiting a F-type star with minimal distance. I have tried 0.005 and 0.01 AU, both of which failed. The upper bound is 0.1 0.03 AU, with a terrestrial planet orbiting there as well. So what is the lower bound?
Update: After some experimenting, the new upper bound is 0.03 AU.


text:
Q: can I make a ruby GUI in javascript/html/css? this is not a ruby on rails question
I just finished up a ruby basics course on teamtreehouse and I'm sitting
here thinking of what I want to make to demonstrate to myself that I
grasped what I learned.
I have a plan to write a program to automate setting up new hire files
and folders on a network directory at my work at the click of a button.
It might be nice to have a GUI for it instead of running it through the
command line.
First off, is this possible to run ruby with javascript and html without
running it through a server?
I'm trying to think of different ways I would get ruby to speak with
javascript. My first thought was to use a JSON file to produce url links
from in my webpage, but I have no idea how I would run the ruby program
from the web page.
probably a dumb question. Im trying to come up with a good project to
get some confidence in bare bones ruby before I pursue ruby on rails or
sinatra.

A: One easy way to run Ruby and many other languages in the browser would be to use a Ruby to JS compiler like http://opalrb.org/. Here's a huge list of more languages then you can shake a stick at: https://github.com/jashkenas/coffeescript/wiki/list-of-languages-that-compile-to-js#ruby.
The only trick is to make sure that the compiler can also be run in the browser not just the code it produces.
Hopefully that helps.
---- edit ----
I think I perhaps didn't read your question as much as I should have. As for comunication between the server and the client goes, I would say go with sinatra. It's really very simple, and you don't even have to use a database if it's just a project to learn with. Just modify files and save your data that way.
If you want a more dynamic front end making AJAX calls then you can just make a route in sinatra that would return back the information in an easy to parse form for JS such as JSON.


text:
Q: Erlang data types What is the benefit of having string as a list of integers rather than an independent data type in Erlang? Is this to make the string manipulation easier and more efficient? Are there any other reasons for this?

A: I believe (TM) that the only benefit was to allow them to implement wide character representations (unicode, utf-x, ...) in a robust way. On the down side, the performance is much less efficient than linear byte arrays. That said, Erlang was never really meant to be used for heavy string manipulations and so the performance of doing so shouldn't matter.


text:
Q: C# for-loop performance estimates: i++ vs. ++i implementation: which is faster? My question relates to performance comparison (numeric estimates) pertinent to the following sample cases implementing for-loop in C# 4.0 and/or C# 5.0 in 4 different manners:
for (int i=0; i<10000; i++;){string _s="a";}
for (int i=0; i<10000; ++i;){string _s="a";}
for (int i=10000; i>0; i--;){string _s="a";}
for (int i=10000; i>; --i;){string _s="a";}

Question: Which of the following implementations will provide better performance (execution time) in generic for-loop implemented in C# 4.0 or C# 5.0?
Note 1: string _s="a"; is just a sample operation, potentially could be omitted for testing purpose.
Note 2: so far, as per discussion on (Is there a performance difference between i++ and ++i in C?) it seems like ++i runs faster than I++ in C++.

A: The optimizer should know that the pre-incremented value of i is never used, and therefore they should be the same (simply increment i).
The only reason i++ may be slower than ++i is if the compiler has to save off the old, pre-incremented value before incrementing i. However, given low register pressure, this should be as trivial as one additional "move" instruction.
If you really care, I would suggest you benchmark your test cases.  Stopwatch provides enough functionality to get a pretty good estimation.
Also, looking at the generated IL will show you if there is any difference at all.


text:
Q: char \0 escape sequence - what does it mean? I'm reading this example
The real "Hello World!" for CUDA!
What does the \0 in
char str[16] = "Hello \0\0\0\0\0\0";

stand for?
I'm not sure why the 16 char str has "Hello " inside it and then all zeroes then (this isn't a global variable). How can I be sure that it just contains zeroes?"

A: \0 stands for NUL, Nul is used as a string termination character. Meaning it states the end of a string. The value of a NUL byte is 0x00

A: '\0' is the ASCII NUL null character (ASCII code zero).
There is no point in specifying all of the zero bytes in the array. The following are equivalent:
char str[16] = "Hello \0\0\0\0\0\0";
char str[16] = "Hello ";

If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. [IBM]

Since the length was given to be 16, the compiler will automatically ensure the rest of the array (after "Hello " is zeroed.) The author did this either to "be sure" the rest of the array was zero, or to serve as documentation for the reader.
Contrary to our initial analyses, the CUDA kernel is not "poking in bytes" to append World! to the existing string.  Hello is printed first. Then the kernel modifies the string to be World!, which is finally printed.
The only reason the string is specified to be 16 bytes, is because that is the block size the kernel is designed to work with, and they have to make sure that the kernel is not messing with memory it shouldn't be.
I've added some comments to the (partial) original code to make this all more clear:
__global__                              // The kernel which is run in parallel
void hello(char *a, int *b)
{
    a[threadIdx.x] += b[threadIdx.x];
}

int main()
{
    // The line in question. There's really no point in padding it with zeros.
    // The zeros are *not* replaced, and only 12+1 bytes are being specified.
    char a[N] = "Hello \0\0\0\0\0\0";

    // These values are added (by the CUDA kernel) to the array above. Again,
    // since partial arrays are zero-filled, there's no point in filling this in.
    int b[N] = {15, 10, 6,  0, -11,  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    // 'H' + 15 = 'W'
    // 'e' + 10 = 'o'
    // 'l' + 6  = 'r'
    // 'l' + 0  = 'l'
    // 'o' - 11 = 'd'
    // ' ' + 1  = '!'

    char *ad;
    int *bd;
    const int csize = N*sizeof(char);
    const int isize = N*sizeof(int);

    printf("%s", a);                  // Print "Hello "

    cudaMalloc( (void**)&ad, csize );
    cudaMalloc( (void**)&bd, isize );
    cudaMemcpy( ad, a, csize, cudaMemcpyHostToDevice );
    cudaMemcpy( bd, b, isize, cudaMemcpyHostToDevice );

    dim3 dimBlock( blocksize, 1 );
    dim3 dimGrid( 1, 1 );
    hello<<<dimGrid, dimBlock>>>(ad, bd);   // Add the values in b to a

    cudaMemcpy( a, ad, csize, cudaMemcpyDeviceToHost );
    cudaFree( ad );
    cudaFree( bd );

    printf("%s\n", a);               // print "World!"
    return EXIT_SUCCESS;
}

A: As stated it has little sense. \0 just places the character with code 0 there, but it happens anyway. The good use of this is where array bounds are not given, as the extra 0 will count in, or where you have more characters after the 0.
char foo_and_bar[] = "Foo\0Bar";

will separate the parts with 0.


text:
Q: Multiple threads can wait on a semaphore at same time Can multiple threads wait on a single semaphore ?
If yes, upon semaphore down which one will be resumed ?

A: As the document for sem_post suggests,

If the value of the semaphore resulting from this operation is zero, then one of
      the threads blocked waiting for the semaphore will be allowed to return
      successfully from its call to sem_wait(). If the symbol _POSIX_PRIORITY_SCHEDULING
      is defined, the thread to be unblocked will be chosen in a manner appropriate to
      the scheduling policies and parameters in effect for the blocked threads. In the case of
      the schedulers SCHED_FIFO and SCHED_RR, the highest priority waiting thread will be
      unblocked, and if there is more than one highest priority thread blocked waiting for
      the semaphore, then the highest priority thread that has been waiting the longest will
      be unblocked. If the symbol _POSIX_PRIORITY_SCHEDULING is not defined, the choice of a
      thread to unblock is unspecified.

Also , as sem_wait defines in Application Usage section, There can be cases of priority inversion involving threads with differemt priority levels

A: Can multiple threads wait on a single semaphore ?

Yes.
If yes, upon semaphore down which one will be resumed ?

Exactly one of them.  Which one depends on OS kernel implementation: the container type that is used to hold the waiting threads.  This is quite likely to be a FIFO queue and so the first thread to call semaphore.wait() will be released first, but you should not design your app in any way that relies on this behaviour.

A: That will be the thread scheduled to execute at that particular CPU cycle.


text:
Q: Why can't Wolfram calculate the Laplace transform of $\sinh(t)\sin(t)$ correctly? Question
Show that the Laplace transform of $\sinh(t)\sin(t) = \frac{2s}{s^4+4}$.
Wolfram can't calculate this as is, so I tried to simplify it a bit. I defined  $\sinh(t)$ as $e^t-e^{-t}$ and split up the operation. This is what Wolfram outputs (after I pair them up myself):
$$
\frac{1}{(s-1)^2+1}-\frac{1}{(s+1)^2+1}
$$
However, when you attempt to structure this to show that it answers the question, you get
$$
\frac{4s}{s^4+4}
$$
Why is it not calculating this correctly? How do you solve this problem then?

A: Note how you have defined $\sinh(t)$. A factor of $\frac{1}{2}$ is missing, which when you correct for should give you the answer you're looking for.


text:
Q: Populating listview with jQuery Mobile on a multi-page template I am trying to render a listview on a second page using jquery.mobile.
I am using a single HTML with multiple "pages".

    List

                First Page

            Load JSON data

                Second Page

            Back

Simple list

JS :
$(document).on('pagebeforeshow', '#index', function(){
    $('#populate-button').on('click',function(e,data){
        $.ajax({url: "http://api.themoviedb.org/2.1/Movie.search/en/json/23afca60ebf72f8d88cdcae2c4f31866/The Goonies",
            dataType: "jsonp",
            jsonpCallback: 'successCallback',
            async: true,
            beforeSend: function() {
                $.mobile.showPageLoadingMsg(true);
            },
            complete: function() {
                $.mobile.hidePageLoadingMsg();
            },
            success: function (result) {
                ajax.jsonResult = result;
                $.mobile.changePage("#second");
            },
            error: function (request,error) {
                alert('Network error has occurred please try again!');
            }
        });
    });
});

$(document).on('pagebeforeshow', '#second', function(){
    ajax.parseJSONP(ajax.jsonResult);
});

var ajax = {
    jsonResult : null,
    parseJSONP:function(result){
        $('#movie-data').empty();
        $('#movie-data').append('
Movie name: ' + result[0].original_name+ '
');
        $('#movie-data').append('
Popularity: ' + result[0].popularity + '
');
        $('#movie-data').append('
Rating: ' + result[0].rating+ '
');
        $('#movie-data').append('
Overview: ' + result[0].overview+ '
');
        $('#movie-data').append('
Released: ' + result[0].released+ '
');
        $('#movie-data').listview('refresh');
    }
}

A: You have id="loadList)", that is, with a closing parenthesis in
List

Maybe this is causing your problem?


text:
Q: MongoDB Atlass can't connect via Mongo Compass on Mac - Get Error queryTxt ESERVFAIL Wondered if anyone knows how to fix my connection to a mongo db database hosted on mongo atlas.
Trying to connect to it by mongo compass, followed instructions to connect to compass found within the cluster on Atlas but get this message in the yellow box when I try to connect:
queryTxt ESERVFAIL

Does anyone know what it means? How to fix?


text:
Q: Is Gmail removing "Received" in headers? I added my professional email to my gmail account as POP3 and set it as default for sending emails. Strangely, when sending emails to other emails like hotmail, or even by using tools like mail-tester or mailgenius, for each of them I see in headers something like that :
Gmail to Hotmail
Received: from server1 by server2 with esmtps
Received: from google-server by server2
Received: by google-server

But somehow, when I send an email to another gmail account, the first "Received" is different...
Gmail to Gmail
Received: from server2 by server2 with LMTP id wGSgNXg5bGIpwQEAIcWi0g
Received: from google-server by server2
Received: by google-server

Notice esmtps was replaced by LMTP with some ID, and server1 is not there anymore.
How is this possible and how can I fix this? I need that server1 for SPF check.
More detailed - Gmail to Hotmail
Received: from nwpro1.fcomet.com ([172.104.22.223])
    by mx36.antispamcloud.com with esmtps (TLSv1.3:TLS_AES_256_GCM_SHA384:256)
    (Exim 4.92)
    (envelope-from <professional@domain.com>)
    id 1nk4co-0007F6-CK
    for private@hotmail.com; Thu, 28 Apr 2022 15:56:08 +0200
Received: from mail-vs1-f52.google.com ([209.85.217.52]:42929)
    by nwpro1.fcomet.com with esmtpsa  (TLS1.3) tls TLS_AES_128_GCM_SHA256
    (Exim 4.94.2)
    (envelope-from <professional@domain.com>)
    id 1nk4c9-00BNxm-QH
    for private@hotmail.com; Thu, 28 Apr 2022 09:55:23 -0400
Received: by mail-vs1-f52.google.com with SMTP id i186so4660856vsc.9
    for <private@hotmail.com>; Thu, 28 Apr 2022 06:55:23 -0700 (PDT)

More detailed - Gmail to Gmail
Received: from nwpro1.fcomet.com
    by nwpro1.fcomet.com with LMTP id wGSgNXg5bGIpwQEAIcWi0g
    (envelope-from <professional_first@domain.com>)
    for <professional_second@domain.com>; Fri, 29 Apr 2022 15:16:08 -0400
Received: from mail-ed1-f52.google.com ([209.85.208.52]:37606)
    by nwpro1.fcomet.com with esmtpsa (TLS1.3) tls TLS_AES_128_GCM_SHA256
    (Exim 4.94.2)
    (envelope-from <professional_first@domain.com>) id 1nkW67-000XKe-6M
    for professional_second@domain.com; Fri, 29 Apr 2022 15:16:08 -0400
Received: by mail-ed1-f52.google.com with SMTP id k27so10117156edk.4
    for <professional_second@domain.com>; Fri, 29 Apr 2022 12:16:08 -0700 (PDT)

A: The esmtps is a secure version of the extended smtp protocol, the LMTP protocol you're seeing in the second request is because that request is more local (e.g., from the same server).
You probably wouldn't ever see that esmtps if its not even leaving the host.
Some more information about the situation may help, ie, sending from hotmail to gmail got this or from gmail to gmail got this.
:)
I appreciate the edit to the question, but I am not sure if that helps.
The sources haven't really changed, and I am not sure that this is the true header.
All the headers I found are like this:
Received: by filterdrecv-75d94df84d-wmwh2 with SMTP id filterdrecv-75d94df84d-wmwh2-1-626C6700-1A
        2022-04-29 22:30:24.062932892 +0000 UTC m=+1989919.691835974
Received: from MjIyOTcyNTI (unknown)

Sources:
ESMTP (minus s, as that is ssl)
https://help.returnpath.com/hc/en-us/articles/220564347-What-is-Extended-Simple-Mail-Transfer-Protocol-ESMTP-
SMTP
https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol
LMTP
https://en.wikipedia.org/wiki/Local_Mail_Transfer_Protocol


text:
Q: Uniform upper bound related to unidimensional symmetric random walk Consider the following basic random walk : $S_n=\sum_{k=1}^n X_k$ where the $(X_k)$
are i.i.d. with $P(X_k=(-1))=P(X_k=1)=\frac{1}{2}$. Let $M_n=\max(0,S_1,S_2, \ldots ,S_n)$ and $\mu(n,t)=P(M_n \leq t)$.
Using the reflection principle , (as explained here), and putting
$q=\lfloor \frac{n-1}{2} \rfloor$ one can see that
$$
\mu(n,t)=P\bigg( -2\lfloor \frac{t}{2} \rfloor-1\leq S_{2q+1} \leq 2\lceil \frac{t}{2} \rceil-1\bigg)=\frac{1}{2^{2q+1}} \sum_{j=-\lfloor \frac{t}{2} \rfloor}^{\lceil \frac{t}{2} \rceil} \binom{2q+1}{q+j} \tag{1}
$$
The Stirling formula yields $\binom{2q+1}{q+j} \sim_{q \to \infty} \frac{2^{2q+1}}{\sqrt{\pi q}}$ for any $j$, and hence for a fixed $t$,
$$
\mu(n,t) \sim_{n\to \infty} (t+1) \sqrt{\frac{2}{\pi n}} \tag{2}
$$
I ask if this limit is also an uniform upper bound, in the sense that
$$
\mu(n,t) \leq (t+1) \sqrt{\frac{2}{\pi n}} \text{ whenever }
\ \mu(n,t) \ \text{is not trivial (i.e. equal to } 0 \ \text{ or } \ 1).
\tag{3}
$$
 UPDATE 02/14/2013  I've just realized that the two-variables inequality
(3) follows from the much simpler one-variable inequality
$$
\frac{\binom{2q+1}{q}}{2^{2q+1}} \leq \sqrt{\frac{1}{\pi (q+1)}} \tag{4}
$$
Indeed, the numerator in the RHS of (1) is a sum of $t+1$ binomials, and the largest such binomial is $\binom{2q+1}{q}$. So (1) implies that
$$
\mu(n,t) \leq (t+1) \frac{\binom{2q+1}{q}}{2^{2q+1}} \tag{5}
$$
Inequality (4) looks much easier to prove.

A: The answer is YES, and indeed inequality (4) is true. To see this, put
$$
u_q=\frac{\binom{2q+1}{q}}{2^{2q+1}}\sqrt{q+1} \tag{5}
$$
Then the usual Stirling formula stuff shows that $u_q \to \frac{1}{\sqrt{\pi}}$. To show
(4), it will therefore suffice to show that $(u_q)$ is increasing. So let us
compute $\frac{u_{q+1}}{u_q}$. Using
$$
\binom{2q+3}{2q+1}=\frac{2(2q+3)}{q+2} \binom{2q+1}{q},
$$
we obtain
$$
\frac{u_{q+1}}{u_q} =\frac{q+\frac{3}{2}}{\sqrt{(q+1)(q+2)}},
$$
and this is $\gt 1$ by the AM-GM inequality, qed.


text:
Q: SQL conditional statements? I'm trying to write a query for a table in SQLCE and compact-framework but the query needs to read every row with two conditions.
Column 'location' in any given row may or may not be null, if it's not null it needs to be checked for its value, if it's null the row should be selected, i.e:
if( location!= null )
{
    if( d == "location" )
         SELECT;
}
else
    SELECT;

Anyone know how I can go about doing this?

A: Use OR to test if either condition is true.
SELECT col1, col2, ..., coln
FROM yourtable
WHERE location IS NULL OR location = 'location'


text:
Q: Should Spring SseEmitter.complete() trigger an EventSource reconnect - how to close connection server-side I'm trying to set up a Spring SseEmitter to send a sequence of updates of the status of a running job. It seems to be working but:
Whenever I call emitter.complete() in in my Java server code, the javascript EventSource client calls the registered onerror function and then calls my Java endpoint again with a new connection. This happens in both Firefox and Chrome.
I can probably send an explicit "end-of-data" message from Java and then detect that and call eventSource.close() on the client, but is there a better way?
What is the purpose of emitter.complete() in that case?
Also, if I always have to terminate the connection on the client end, then I guess every connection on the server side will be terminated by either a timeout or a write error, in which case I probably want to manually send back a heartbeat of some kind every few seconds?
It feels like I'm missing something if I'm having to do all this.

A: I have added the following to my Spring boot application to trigger the SSE connection close()
Server Side:

*

*Create a simple controller which returns SseEmitter.

*Wrap the backend logic in a single thread executor service.

*Send your events to the SseEmitter.

*On complete send an event of type complete via the SseEmitter.
@RestController
public class SearchController {

@Autowired
private SearchDelegate searchDelegate;

@GetMapping(value = "/{customerId}/search")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "Search Sources", notes = "Search Sources")
@ApiResponses(value = {
        @ApiResponse(code = 201, message = "OK"),
        @ApiResponse(code = 401, message = "Unauthorized")
})
@ResponseBody
public SseEmitter search(@ApiParam(name = "searchCriteria", value = "searchCriteria", required = true) @ModelAttribute @Valid final SearchCriteriaDto searchCriteriaDto) throws Exception {
    return searchDelegate.route(searchCriteriaDto);
  }
}

@Service
public class SearchDelegate {
public static final String SEARCH_EVENT_NAME = "SEARCH";
public static final String COMPLETE_EVENT_NAME = "COMPLETE";
public static final String COMPLETE_EVENT_DATA = "{\"name\": \"COMPLETED_STREAM\"}";

@Autowired
private SearchService searchService;

private ExecutorService executor = Executors.newCachedThreadPool();

public SseEmitter route(SearchCriteriaDto searchCriteriaDto) throws Exception {
    SseEmitter emitter = new SseEmitter();
    executor.execute(() -> {
        try {
            if(!searchCriteriaDto.getCustomerSources().isEmpty()) {
                searchCriteriaDto.getCustomerSources().forEach(customerSource -> {
                    try {
                        SearchResponse searchResponse = searchService.search(searchCriteriaDto);
                        emitter.send(SseEmitter.event()
                                .id(customerSource.getSourceId())
                                .name(SEARCH_EVENT_NAME)
                                .data(searchResponse));
                    } catch (Exception e) {
                        log.error("Error while executing query for customer {} with source {}, Caused by {}",
                                customerId, source.getType(), e.getMessage());
                    }
                });
            }else {
                log.debug("No available customerSources for the specified customer");
            }
            emitter.send(SseEmitter.event().
                    id(String.valueOf(System.currentTimeMillis()))
                    .name(COMPLETE_EVENT_NAME)
                    .data(COMPLETE_EVENT_DATA));
            emitter.complete();
        } catch (Exception ex) {
            emitter.completeWithError(ex);
        }
    });
    return emitter;
   }
}

Client Side:

*

*Since we specified the name of event on our SseEmitter, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use addEventListener() to listen for named events. (Notice: The onmessage handler is called if no event name is specified for a message)

*Call the EventSource on the COMPLETE event to release the client connection.

https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
var sse = new EventSource('http://localhost:8080/federation/api/customers/5d96348feb061d13f46aa6ce/search?nativeQuery=true&queryString=*&size=10&customerSources=1,2,3&start=0');

sse.addEventListener("SEARCH", function(evt) {
   var data = JSON.parse(evt.data);
   console.log(data);
});

sse.addEventListener("COMPLETE", function(evt) {
   console.log(evt);
   sse.close();
});

A: According to the HTML standard for Server-sent events

Clients will reconnect if the connection is closed; a client can be told to stop reconnecting using the HTTP 204 No Content response code.

So Spring's SseEmitter behaves as expected and the purpose of complete() is to make sure all the events were sent and then to close the connection.
You need to either implement server-side logic that would return 204 http code on subsequent requests (e.g. by checking session id) or to send a special event and close the connection from client side after receiving it as suggested by Ashraf Sarhan


text:
Q: Spring MVC - redirect automatically append JsessionID This is my handler method , if the user attribute in session is not null (He already logged in) forward him to success page , if not, redirect him to login page.
@RequestMapping(value = "/")
public String showHome(HttpSession session) {
    User user = (User) session.getAttribute("user");
    if (user != null) {
        return "success";
    }
    return "redirect:/login";
}

The problem is , the first time I access my page, it redirect to login page but it automatically append jssessionId at the end of URL like this : "/login;jsessionid=FC75BC999410329E65785274BF0EB623". There is no problem when changing it to return "login".

A: In tomcat 7, make this change in your tomcat_home/web.xml
<session-config>
    <tracking-mode>COOKIE</tracking-mode>
</session-config>

A: I got around this by overriding the strictHttpFirewall, allowing semi-colons.
It's not an ideal solution, but I couldn't find a way to prevent Spring (or is it tomcat?) from appending the jsessionid to the redirect url
 @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

         .......

        @Bean
        public HttpFirewall allowSemicolonHttpFirewall() {
            StrictHttpFirewall firewall = new StrictHttpFirewall();
            firewall.setAllowSemicolon(true);
            return firewall;
        }

A: If you are getting this error in your spring-boot project then add the below property in your application.yml
server:
  servlet:
    session:
      tracking-modes: cookie

As spring eventually calls response.sendRedirect(response.encodeRedirectURL(url));
When it tries to redirect the request and http servlet response's method sendRedirect encodes the target URL and adds the JSESSIONID to it.
To avoid this we can configure tracking-mode and set it to cookie and this should solve the issue.