text:
Q: no window appears in Visual C++ program I am developing an Win32 application where user logins when the application starts in a login window and then the main window opens
But when I run the program nothing appears.
Here's the code
HINSTANCE   ghInstance;
HWND hWnd;

HWND hWndPopUp;

LRESULT WINAPI PopUpWndProc( HWND hWnd2, UINT msg, WPARAM wParam, LPARAM lParam );
LRESULT WINAPI  MainWndProc( HWND hWnd , UINT msg , WPARAM wParam , LPARAM lParam );

int WINAPI WinMain(HINSTANCE hInstance , HINSTANCE hPrevInstance , LPSTR lpszCmdLine , int nCmdShow){

WNDCLASS wc;
WNDCLASS wcPopUp;
MSG msg;
//HWND hWnd;
BOOL bRet;

if( !hPrevInstance )
{

    wc.lpszClassName    =   L"MainAppClass" ;

    wc.lpfnWndProc      =   MainWndProc ;

    wc.style            =   CS_OWNDC    |   CS_VREDRAW  |   CS_HREDRAW ;

    wc.hInstance        =   hInstance ;

    wc.hIcon            =   LoadIcon( NULL, IDI_APPLICATION ) ;

    wc.hCursor          =   LoadCursor( NULL, IDC_ARROW ) ;

    wc.hbrBackground    =   (HBRUSH)( COLOR_WINDOW+1 ) ;

    wc.lpszMenuName     =   NULL ;

    wc.cbClsExtra       =   0 ;

    wc.cbWndExtra       =   0 ;

    RegisterClass( &wc ) ;

    wcPopUp.lpszClassName   =   L"PopUpAppClass" ;

    wcPopUp.lpfnWndProc     =   PopUpWndProc ;

    wcPopUp.style           =   CS_OWNDC    |   CS_VREDRAW  |   CS_HREDRAW ;

    wcPopUp.hInstance       =   hInstance ;

    wcPopUp.hIcon           =   LoadIcon( NULL, IDI_APPLICATION ) ;

    wcPopUp.hCursor         =   LoadCursor( NULL, IDC_ARROW ) ;

    wcPopUp.hbrBackground   =   (HBRUSH)( COLOR_WINDOW+1 ) ;

    wcPopUp.lpszMenuName        =   NULL ;

    wcPopUp.cbClsExtra      =   0 ;

    wcPopUp.cbWndExtra      =   0 ;

    RegisterClass( &wcPopUp );

}

ghInstance = hInstance;

hWndPopUp = CreateWindowEx(WS_EX_CONTEXTHELP,
                        wcPopUp.lpszClassName,
                        L"Stock Ticker Login",
                        WS_OVERLAPPEDWINDOW,
                        0,
                        0,
                        CW_USEDEFAULT,
                        CW_USEDEFAULT,
                        NULL,
                        NULL,
                        hInstance,
                        NULL
                    );

bool show = ShowWindow( hWndPopUp, SW_MAXIMIZE  ) ;

UpdateWindow(hWndPopUp);

hPE = NULL;

/** While there is no WM_QUIT message in the Message Queue
    Fetch Message from the queue and Dispatch it to WindowProc()
**/
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0 )
{
    if (bRet == -1)
    {
        // handle the error and possibly exit

        int nerror = GetLastError();

        MessageBox(hWnd,L"Window Error",L"Window error", MB_ICONERROR);

        exit(1);
    }

    else {

        TranslateMessage( &msg );
        DispatchMessage( &msg );
    }
}

return (int)msg.wParam;

}

LRESULT WINAPI PopUpWndProc( HWND hWnd2, UINT msg, WPARAM wParam, LPARAM lParam ){

HDC hdc;
PAINTSTRUCT ps;

RECT rc;
GetClientRect(hWnd, &rc);

int height  = rc.bottom - rc.top;
int width = rc.right -rc.left;

switch( msg )
{

    case WM_CREATE:

        hWndStaticUsername = CreateWindowEx(    0
                                            , L"static"
                                            , L"Username"
                                            , WS_CHILD | WS_VISIBLE
                                            , rc.left + width/8
                                            , rc.top + height/4
                                            , 100
                                            , 30
                                            , hWnd2
                                            , 0
                                            , ghInstance
                                            , 0
                                    );

        hWndEditUsername = CreateWindowEx(  WS_EX_CLIENTEDGE
                                        , L"edit"
                                        , L""
                                        , WS_CHILD | WS_VISIBLE
                                        , rc.left + width/8 + 150
                                        , rc.top + height/4
                                        , 150
                                        , 30
                                        , hWnd2
                                        , 0
                                        , ghInstance
                                        , 0
                                );
        hWndBtnLogin = CreateWindowEx(  0
                                    , L"button"
                                    , L"Login"
                                    , WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON
                                    , rc.left + width/8
                                    , rc.top + height/4 + 80
                                    , 50
                                    , 30
                                    , hWnd2
                                    , 0
                                    , ghInstance
                                    , 0
                            );

        break;

    case WM_COMMAND:

        if(HIWORD(wParam)== BN_CLICKED  && lParam==(LPARAM)hWndBtnLogin )
        {
            TCHAR* uname =new TCHAR;
            Edit_GetText(hWndEditUsername, uname, 20);

            if(wcscmp(uname,L"")==0)

                return 0;

            else
            {
                StartTicker(uname);
                DestroyWindow(hWnd);
            }

        }

        break;

    case WM_DESTROY:

        hWnd = CreateWindowEx(WS_EX_CONTEXTHELP,
                        L"MainAppClass",
                        L"Assignment 2",
                        WS_OVERLAPPEDWINDOW,
                        0,
                        0,
                        CW_USEDEFAULT,
                        CW_USEDEFAULT,
                        NULL,
                        NULL,
                        ghInstance,
                        NULL
                    );

        ShowWindow( hWnd, SW_MAXIMIZE ) ;

        UpdateWindow(hWnd);

        break;

    default:

        return DefWindowProc(hWnd, msg, wParam, lParam );
}

return 0;

}

Please help me find the solution.

A:     return DefWindowProc(hWnd, msg, wParam, lParam );

Wrong window handle, it should be hWnd2.
To uplift this post beyond a 'debug my code for me' answer, there are two fundamental things you do wrong, they are going to get you into a lot more trouble:

*

*too sloppy on picking good variable names.  You should never have a global variable named "hWnd".  That should of course be hWndMain, you'd have never made that mistake.

*no error check whatsoever.  If you had any, you would have quickly discovered that CreateWindowEx() returned NULL and GetLastError() returned 1400.  Without error checking, you can only watch it misbehave but never diagnose it.

Using the raw winapi requires meticulous attention to such small details.  Consider using a class library instead.

A: how come you are calling:
ShowWindow( hWnd, SW_MAXIMIZE ) ;
UpdateWindow(hWnd);

only after and in the scope of: case WM_DESTROY:
I would imagine you call ShowWindow in normal execution and not in the distruction :)


text:
Q: .htaccess Serve everything from the root directory I have a need where I need to take incoming urls and serve them from root without changing the url.
So if someone types in:
http://example.com/randomdirectory/page.html
it would get serve up
http://example.com/page.html but the url wouldn't change.
I feel like I'm close with the following, but it fails when the url ends in a trailing slash; which I would want to serve the index.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\/([^.]+.html) /$2 [L]

Essentially, I just want to serve the same files (at root) no matter what the user types in.

A: You can use this rule instead:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)/(.*)$ /$2 [L]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set Visibility of Panel Inside Update Panel From Code behind From An Update Panel I have simplified and probably made a typo or two below, but I am trying to show and hide the visibility of pnl2, this code however doesn't work.  I thought as long as the panel was in another update panel I can control visibility.
Oddly enough if I debug this in Visual studio, and F10 all the way through it, it shows the visibility correctly, but when I hit my Last F10 and the page loads, it's always incorrect.
<asp:UpdatePanel runat="server" UpdateMode="Always" ID="updPanel1">
<ContentTemplate>
<asp:Panel runat="Server" ID="pnl1"/>
<asp:Button runat="Server" ID="hidePanel2" OnClick="HidePanel2"/>
</ContentTemplate>
</UpdatePanel>

<asp:UpdatePanel runat="server" UpdateMode="Always" ID="updPanel2">
<ContentTemplate>
<asp:Panel runat="Server" ID="pnl2"/>
</ContentTemplate>
</UpdatePanel>

protected void hidePanel2(object sender, EventArgs e)
{
if (pnl2.Visible == true)
{
    pnl2.Visible = false;
}else
{
    pnl2.Visible = true;)
}

A: The problem is that you are trying to update the visibility of "pnl2" from a button that is in the UpdatePanel named "updPanel1".  The postback for the button "hidePanel2" only causes the content of update panel "updPanel1" to change.  The rest of the form, including update panel "updPanel2", does not change.
The most direct solution, if the two panels are next to each other, is to put them both in one update panel.  If you have some other layout then you will need to explain what it is before we can help.


text:
Q: Symfony config: Doctrine InvalidConfigurationException: Unrecognized option "options" under "doctrine.dbal" I am using Symfony 2 and want to import a local CSV file with Doctrine:
$connection = $this->entityManager->getConnection();

        $output->writeln('Importing Articles');

        $path = $this->importHelperService->getCSVBasePath() . 'PromotionArtikel.csv';

        $query =
            <<<EOF
                LOAD DATA LOCAL INFILE '$path' INTO TABLE ProductCSV
                FIELDS TERMINATED BY ','
                ENCLOSED BY '"'
                LINES TERMINATED BY '\r\n'
                IGNORE 1 LINES;
EOF;

        $statement = $connection->prepare($query);
        $statement->execute();

But I got

[Symfony\Component\Debug\Exception\ContextErrorException]
  Warning: PDOStatement::execute(): LOAD DATA LOCAL INFILE forbidden

So I search how can I fix this problem and found this:
Symfony2 Doctrine PDO MySQL Connection with LOAD DATA LOCAL INFILE
But when I try to put the options into my config.yml
doctrine:
    dbal:
        options:
            1001: true

I got an InvalidConfigurationException:

InvalidConfigurationException: Unrecognized option "options" under
  "doctrine.dbal"

In my composer.lock I search for doctrine/dbal and I can see that version 2.5.12 is installed.

"name": "doctrine/dbal",
              "version": "v2.5.12",

Anyone an idea how can I solve this problem?
EDIT: Found by myself:

In my config there are different connections. So in this case the
  "options" have to be configured in the default connection:

doctrine:
    dbal:
        connections:
            default:
                options:
                    1001: true

A: The connection options should be defined at dbal.connections.<connection-name>.options according to the DoctrineBundle 2.5 configuration docs:
doctrine:
    dbal:
        connections:
            default:
                options:
                    # an array of options
                    key:                  []


text:
Q: Read url encoded data in spring boot I have a source which calls a post api and the request is url encoded. How can I retrieve the request data that is url encoded using spring boot.
Update
In my controller I have below method,
@PostMapping(value = "/res", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Map<String, Object> postResponse(@RequestBody Map<String, Object> url) {...}

It returns error

"error": "Unsupported Media Type",
      "message": "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported"

How can I get form-urlencoded data in controller

A: I got the answer finally.
url encoded values can be read as String
@PostMapping(value = "/res", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Map<String, Object> postResponse(@RequestBody String request) {...}


text:
Q: How to create folder with intermediary folder with Applescript? I think the question pretty explains what I'm intending to do.
I have seen some folder creation scripts on the Internet like this:
tell application "Finder"

    if not (exists folder new_foldername of this_folder) then
        make new folder at this_folder with properties {name:new_foldername}
    end if

end tell

But this script just create one new folder havving its parent folder. I would like something like this Cocoa NSFileManager method
- (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error

in which I pass a path as parameter and the folder is created within the intermediary directories.
thanks for your attention.

A: The simplest solution is probably to resort to the mkdir shell command, i.e.:
do shell script "mkdir -p '/path/to/folder/to/create'"


text:
Q: PostgreSQL: How does the implicit index work when using "COPY" for loading bulk rows into a newly created table? What I know for fast loading bulk rows into a new table is:

*

*Create the table(without creating the index)

*Use "COPY" to load data from a file into the table

*Create the index

What if I added a primary key when creating the table, according to PostgreSQL: "Adding a primary key will automatically create a unique btree index on the column or group of columns used in the primary key.", will the rows be indexed during "COPY" since the table has an implicit index? if the answer is yes, the "COPY" will slow down?

A:
will the rows be indexed during "COPY" since the table has an implicit index?

Yes.

if the answer is yes, the "COPY" will slow down?

Yes.
You can LOCK TABLE ... IN ACCESS EXCLUSIVE MODE then drop the PRIMARY KEY constraint for the duration if you need to.
PostgreSQL doesn't have a way to mark indexes as invalid then revalidate them for use without dropping and recreating them (yet).


text:
Q: How to add data to the properties created locally under test case in Soapui Pro? I have TestCase under a TestSuite step in the project. Inside test case, there are Properties test step and Groovy script test step.
Properties step, I added a property like Pro_Response and default value as Nothing
Similarly, I used the following groovy script for assigning a string value to the property and then it shows the string in the log.
String testString = "TestString"
testRunner.testCase.setPropertyValue( "Pro_Response", testString )
def getLocalPropValue = testRunner.testCase.getPropertyValue("Pro_Response")
log.info(getLocalPropValue)

Question: Why the string value is not updating in the property step which I added under the test case even the same property name (i.e. Pro_Response) is used in the script  for assigning?
Please refer the screenshot for your reference:

Thanks,
Karunagara Pandi

A: You have added a "Properties" Test Step, but your script is updating a property in the Test Case. Update your script to:
testRunner.testCase.testSteps["Properties"].setPropertyValue( "Pro_Response", testString )


text:
Q: Android: Creating bullet point list in an Edit Text I am using an EditText as the main notepad typing area and I want the user to be able to simply click a button and have their note turn into a bullet point list (add the bullet points and a few spaces before the text of each line).
I have figured out something that works, but my main problem is that if the user has a double-newline (a blank line in the note) it adds a bullet point to the empty line.
I tried using Matcher and Pattern with regular expressions, but don't cannot figure out how to avoid adding bullet points to a blank line in an already created set of text.
Here is the code that adds the bullet point to every line except the note title.
//Place text into an array containing the lines.
String[] lines = noteText.split("\n");

for (int i = 0; i < lines.length; i++) {
    //The note title. Don't add a bullet point
    if(i == 0) {
        pad.setText(lines[i]);
    } else {
        pad.append("\n" + "\u2022" + "  " + lines[i]);
    }
}

A: Why not check each line and see if it is empty or white text only?
String[] lines = noteText.split("\n");

for (int i = 0; i < lines.length; i++) {
 //The note title. Don't add a bullet point
 if(i == 0) {
    pad.setText(lines[i]);
 } else if (TextUtils.isEmpty(lines[i].trim()) {
    pad.setText(lines[i]);
 } else {
    pad.append("\n" + "\u2022" + "  " + lines[i]);
 }
}

Also, it will be better to simply handle i=0 case outside the loop and not inside. Otherwise you performing the zero check for every iteration which is unnecessary.

A: If you want something this complicated you may be better off not using an EditText, but writing your own custom view.
Ignoring that, here's a hack that will probably work
str = str.replaceAll("\n*","\n");

That will replace all double, triple, or more than that newlines with a single newline.  If you need the newlines, try
str = str.replaceAll("\n{1}", "\n\u2022");

That will look for single newlines and replace them with a newline followed by your bullet point.


text:
Q: Conflicts with routing when using default {controller}/{id} route and {controller}/{action}/{id} route I have the following routes setup;
RouteTable.Routes.MapHttpRoute(
   name: "ActionApi",
   routeTemplate: "api/{controller}/{action}/{id}",
   defaults: new { id = RouteParameter.Optional });

RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = System.Web.Http.RouteParameter.Optional },
    constraints: null,
    handler: new WebApiMessageHandler(GlobalConfiguration.Configuration));

and the following controller setup;
public class GetFileController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get(string id)
    {
        return Request.CreateResponse(HttpStatusCode.OK);
    }
}

The issue I have here is that this url
/api/GetFile/id_is_a_string

returns this error;
<Error>
    <Message>
        No HTTP resource was found that matches the request URI /api/GetFile/id_is_a_string.
    </Message>
    <MessageDetail>
        No action was found on the controller 'GetFile' that matches the name 'id_is_a_string'.
    </MessageDetail>
</Error>

Is there any way to get around having it not think the string parameter is actually the action name?
I know I could change my request URL to be;
/api/GetFile?id=id_is_a_string

but this routing change affects a lot of other controllers I already have set and don't really wish to go through everything to switch it up to send the request this way.
If I re-order the routes, it seems to work as it did but for my new controller which I would've ideally liked to have multiple endpoints within, I get this error;
ExceptionMessage=Multiple actions were found that match the request:

New Controller
public class GettingThingsController : ApiController
    {

        [HttpPost]
        public IHttpActionResult GetPeople()
        {
             return Ok();
        }

        [HttpPost]
        public IHttpActionResult GetProducts()
        {
            return Ok();
        }
    }

Is there anyway of achieving what I need at all?!

A: You can try to specify parameters with Regex:
routeTemplate: "api/{controller}/{action:regex([a-z]{1}[a-z0-9_]+)}/{id:regex([0-9]+)}",

routeTemplate: "api/{controller}/{id:regex([0-9]+)}",

These regex works in Route attribute. You can test it in RouteTable mappings.


text:
Q: Why does Weierstrass theorem does not apply to lower semicontinuity functions? What is a counter example of a function that is lower semicontinuous on a bounded, closed interval $[a,b]$ but has no maximizer on this interval?

A: On $[a,b]=[0,1]$, consider $$f(x) = \begin{cases} x, & 0 \le x < 1/2 \\ 0, & x\ge 1/2. \end{cases}$$
The supremum is $1/2$ but is not attained.


text:
Q: Bootstrap Tabs with Numerous Rows of Tabs - How to Make them Stack Bottom Up Apparently the default behavior is for the Bootstrap tabs to stack like in the top image when there's more than 1 row of tabs. I'd like the "full" row of tabs to always be resting atop the content box (looks more natural) instead of the partially filled row. Anyone know how to achieve this? Note the tab order within the row should remain the same, just the row order is changed. Would greatly appreciate the help, thanks.

A: I've been playing around with this recently and came up with a potential (partial) fix using flexbox (note, BS4 already utilises flexbox for tabs, although it still exhibits the same wrapping issue shown above):

/* for demo purposes only */
.demo {
  margin: 2em;
  max-width: 300px;
}

.tab-content {
  margin-top: 1em;
}

/* tab reordering fix - older browsers may require other prefixed rules */
.nav.nav-tabs {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap-reverse;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Home

Profile

Messages

Settings

[HOME TAB CONTENT]

[PROFILE TAB CONTENT]

[MESSAGES TAB CONTENT]

[SETTINGS TAB CONTENT]

The one remaining issue I'm still looking into is how to automatically move a tab to the bottom row if it's selected (in the example given here, clicking "Settings" works, but now looks removed from the tab body).
I've found a slight workaround (basically, if the top position of the clicked tab is above the top position of the currently active tab, swap the flex-wrap to wrap instead of wrap-reverse), but it feels flaky as hell!  If I ever sort it, I'll try to remember to update this post :)


text:
Q: Is it possible to restore only permissions from a SharePoint 2010 backup? Is there a way to only restore permissions and not the content from a SharePoint 2010 back-up?
If yes, how?

A: Saumil,
that is not possible. What you coud do:
* restore the content database to another sitecollection
* synchronize the permissions between the two sitecollections with some custom written powershell. I don't think there's an easier way.

A: You can with some 3rd party tools like Quest Security Explorer.  Essentially you would take a backup of the security, and then when needed you could restore it.
http://www.quest.com/security-explorer/


text:
Q: modify dataframe taking index from first part of columns names I would need your help to modify the following dataframe
df = pd.DataFrame(data=[[1,1,2,3,4],[2,3,4,5,6],[3,4,5,6,7]],
                  columns=['day','Sub_1_var1','Sub_1_var2','Sub_2_var1','Sub_2_var2'])

df
Out[45]:
   day  Sub_1_var1  Sub_1_var2  Sub_2_var1  Sub_2_var2
0    1           1           2           3           4
1    2           3           4           5           6
2    3           4           5           6           7

into df2
df2 = pd.DataFrame(data=[[1,1,2],[2,3,4],[3,4,5],
                         [1,3,4],[2,5,6],[3,6,7]],
                        columns=['day','var1','var2'],
                        index=['Sub_1','Sub_1','Sub_1','Sub_2','Sub_2','Sub_2'])

df2
Out[46]:
       day  var1  var2
Sub_1    1     1     2
Sub_1    2     3     4
Sub_1    3     4     5
Sub_2    1     3     4
Sub_2    2     5     6
Sub_2    3     6     7

A: Use:

*

*set_index by column day

*split by last _ columns by rsplit and create Multiindex

*reshape by stack

*sort_index and last reset_index

df = df.set_index('day')
df.columns = df.columns.str.rsplit('_', n=1, expand=True)
df = df.stack(0).sort_index(level=[1,0]).reset_index(level=0)
print (df)
       day  var1  var2
Sub_1    1     1     2
Sub_1    2     3     4
Sub_1    3     4     5
Sub_2    1     3     4
Sub_2    2     5     6
Sub_2    3     6     7

df.index = df.index.str[4:]
print (df)
   day  var1  var2
1    1     1     2
1    2     3     4
1    3     4     5
2    1     3     4
2    2     5     6
2    3     6     7


text:
Q: Browserify: Can't seem to get reactify to work with coffeeify I can't seem to get reactify to work with coffeeify. I followed the Reactify's readme to no avail.
app.coffee
### @jsx React.DOM ###

console.log 'hi'

browser command:
browserify -t coffeeify -t [ reactify -x coffee] ./src/coffeescripts/app.coffee
/Users/mueller.128/repos/klc/react_colorpicker/src/coffeescripts/app.coffee:1
/** @jsx React.DOM */
^
ParseError: regular expressions cannot begin with `*`

my attempt at using the browserify api in a gulp task
var browserify = require('browserify');
var source     = require('vinyl-source-stream');
var watchify   = require('watchify');
var coffeeify  = require('coffeeify');
var reactify   = require('reactify');

gulp.task('browserify', function() {
  return browserify('./src/coffeescripts/app.coffee')
    .transform({ }, coffeeify)
    .transform({ extension: "coffee" }, reactify)
    .bundle({debug: true})
    .pipe(source('./src/bundle.js'))
    .pipe(gulp.dest('./build/javascripts/'));
});

Thanks for any help.

A: I ran into this same issue -- ParseError: regular expressions cannot begin with `*` -- when using coffee-reactify as duereg suggests. Following the recipe from the gulp recipe led me to this:
bundler = browserify 'test.cjsx', {
  transform : [ require 'coffee-reactify' ]
}

...which exhibited the issue. Some ad-hoc logging in browserify revealed it's some kind of subtle bug where the transforms get added twice when specified in this way, confirming Ben's suspicion that the compiler was running twice. Changing it to the following:
bundler = browserify 'test.cjsx'
bundler.transform require 'coffee-reactify'

...fixed the issue entirely.
A functioning example:
gulp       = require 'gulp'
gutil      = require 'gulp-util'
browserify = require 'browserify'
source     = require 'vinyl-source-stream'

bundler = browserify './test.cjsx'
bundler.transform require 'coffee-reactify'

bundle = ->
  return bundler.bundle()
    .on 'error', gutil.log.bind(gutil, 'Browserify Error')
    .pipe source 'all-scripts.js'
    .pipe gulp.dest './.dist'

gulp.task 'default', ->
  bundle()

Where test.cjsx is just:
# @cjsx React.DOM

Someone recently opened a ticket on browserify's github.

A: browserify -t coffeeify -t [ reactify -x] ./app.coffee

A: I've had luck with the following gulp task. Note that you'll have to install the coffee-reactify plugin for this to work.
var gulp = require('gulp');
var browserify = require('gulp-browserify');
var rename = require('gulp-rename');

gulp.task('browserify', function() {
  gulp.src('./src/coffeescripts/app.coffee', { read: false })
    .pipe(browserify({
      debug: true
      transform: ['coffee-reactify'],
      extensions: ['.coffee']
    }))
    .pipe(rename('./src/bundle.js'))
    .pipe(gulp.dest('./build/javascripts/'))
});


text:
Q: MCU + RFID tag that reads and writes RFID messages I would like your input on choosing a proper RFID tag simulator chip.
I'm looking for an MCU + RFID tag setup that will allow me to receive commands and answer them (specifically, mifare commands).
The typical use case is:
1. MCU receives command from antenna and I reach a handler in the code with the proper command received.
2. I command the MCU to transmit a speific answer. The answer sgould be exactly what I command, without any additional CRC or what not.
Also, it would be very, very helpful if the identification process will not be done automatically, but I get alerted on each command received and choose if and how to reply to it.
Can you recommend me a product that does this?
Thanks in advance!

A: the TI TRF7970 is a good decision for that. You can put this Reader chip into transparent mode which allows you full control of the sending and receiving of frames. If this is not necessary you can let also the Reader chip doing the frame handling and you are doing only the data interpretation of the MCU.
The MCU should be a fast cpu because the latency of processing commands should be very short. (depending on which layer you wanna work)
best regards


text:
Q: Updating database ids, what to do with form url Updating existing items in DB in my application is solved by this way:
I have url like this:
http://localhost/project/public//structure/edit/about-us

In router I have set
Route::get('/structure/edit/{url}', 'StructureController@update'); //for displaying the prefilled form
Route::post('/structure/edit/{url}', 'StructureController@update'); // for saving new values

So it means, I'm building update query where url = $url . This is the main part of my view file:
{!! Form::open(['url' => URL::current()]) !!}

I don't know where to point "form action". So I¨m using the same url as current url, so router recognizes, that this is post request and I can process the update inside the same controller and select new (updated) data to my update form.
The problem is, when I update the url via form, new value will set to database. So it means, from this moment old url doesn't exists, but and my form action point to url, which doesn't exists anymore.
What can I do with that? If you know, what I mean...

A: To update use patch method instead of post. Write this in web.php
Route::get('/structure/edit/{id}', 'StructureController@edit');
Route::patch('/structure/{id}/update', 'StructureController@update');

You can use either action or url as a form action. Pass the structure id in the second parameter of the action
{!! Form::model($structure,['action' => ['StructionController@update',$structure->id],'method'=>'patch']) !!}

A: If you do what @smartrahat suggests and still got the error you posted, then can you run php artisan route:list command and show us the structure of your routes?


text:
Q: History of Location Problem
I would like to know the places a device of mine has been in.
Question
Is there any way to get the history of locations with my iphone 5s?

A: Option 1:
You can use the Apple Find My iPhone service to track and find your missing Apple device.

Use Find My iPhone
When you sign in to iCloud.com or the Find My iPhone app, you can see your missing device on a map or play a sound. And you can use Lost Mode to lock, track, or remotely erase all of your personal information.
More information on apple.com

Option 2:
If the device is currently in your possession and location services are turned on:
Use Significant Locations settings' to check visited places. These are buried pretty deep. You'll find them in Settings > Privacy > Location Services > System Services > Significant Locations. You must authenticate yourself to see them, using your passcode, Touch ID or Face ID.


text:
Q: Moving one harddrive between laptops will windows 10 work? So I have a new laptop form work. But my older laptop has a better/bigger ssd. And has all my stuff nicely configured.
Hardware wise they are both Asus with a Intel processors and Nvidia Graphics cards.
If I just put the ssd in the new laptop will Windows 10 work?
Or will it start complaining about license stuff? I understand I probably need to update my drivers.
Edit
I've moved the harddrive and Windows did do a whole device reconfiguration. It downloaded a few driver updates on it's own. And everything works.
Windows isn't complaining.... Yet..... If it does start complaining I'll edit again.

A: It will work, just transplant the hard drive. However, if you have windows 10 on the new laptop's SSD and not on your old laptop's SSD, then you won't be able to achieve your goal.
It won't complain about licensing issues as long as the windows 10 on your old SSD is registered.


text:
Q: iText flattening issue with watermark text I am using iTextSharp to add watermarks to existing documents that are in PDF format. I read them in, create a PdfTemplate object, add the watermark text, color, transparency, etc... to this PdfTemplate, then add the template to a PdfContentByte that I get using PdfWriter.DirectContent.
This solution has been working for a while for all documents that I throw at it, but for some reason a few particular PDFs have been printing with an opaque rectangle around the watermark text.
I have tried a number of things already, including setting the PdfGState's OverPrintMode to 1, opening the generated file after it is created and then using PdfStamper's setFormFlattening and setFreeTextFlattening before saving a new copy... Nothing has worked so far.
The issue is that I don't care about flattening form fields or buttons, I just want to flatten all the layers of the document after I have generated the entire thing. Is this even possible with the iText API?

A: Alright, coming back to close this one out since I solved it a long time ago:
The issue was that the pdfs having the issue were very old (v1.3 of the PDF standard) and did not support the transparency that was a part of the watermark element.
I got around this by printing the old PDF via a virtual printer to a temporary file, then continuing to process that file, which was now a newer version of the PDF standard.


text:
Q: Express rewrite URL issue I am trying to rewrite any query parameter of '?locale=en' to '/' and i don't want to redirect
in app.js i wrote before the router and it didn't work, the browser still has the same link.
var locale = req.query.locale;
var old_url = req.url;

if(locale=='en'){
 req.url = req.protocol + '://' + req.get('host') + req.originalUrl.replace("/?locale=" +
 locale,"");
 }

console.log('foo: ' + old_url + ' -> ' + req.url);
next();

A: const express = require("express");
const app = express();

app.use((req, res, next) => {

    let locale = req.query.locale;
    let old_url = req.url;

    if (locale == 'en') {
        req.url = `${req.protocol}://${req.get("host")}${req.originalUrl.replace(`?locale=${locale}`, "")}`
    }

    console.log('foo: ' + old_url + ' -> ' + req.url);

    next();

});

app.use((req, res, next) => {
    res.end(req.url);
});

app.listen(8080);

Just remove the trailing/leading slash in the replace
foo: /my/path?locale=en -> http://127.0.0.1:8080/my/path

BUT: you are set with this code the req.url property to the whole path (incl. fqdn) and not only the url/path as its original purpose: https://nodejs.org/api/http.html#http_message_url


text:
Q: General equivalence between closed set and accumulation points Studying analysis we were given the definition of closed set and accumulation points.
We than proved that given a metric space $(X,d)$, given $A \subseteq X$, $A$ is closed iff $A' \subseteq A$. I was wondering how can $A'$ be a subset and not always equal to $A$, so I did some research and for $\mathbb{R}$ they are in fact equal. Does this extends to arbitrary sets and metrics? If not could you provide some examples where this fails?

A: In the usual topology on $\Bbb R$, $\{1\}'=\emptyset$ and $[0,1] \cup \{2\} = [0,1]$ so it can be a subset of $A$.


text:
Q: Swapi get and render films in peopels card i need to render movie title from swapi.co in each people card
import React, {useEffect} from 'react';
import './App.css';

const App = () => {
  const [person, setPerson] = React.useState([]);
  const [films, setFilms] = React.useState([]);

  useEffect(() =>{
    fetchData('https://swapi.co/api/')
      .then(res => {
        fetchData(res.people).then(people => setPerson(people.results));
        fetchData(res.films).then(films => setFilms(films.results));
      });
  }, [])

  async function fetchData(url) {
    const response = await fetch(url);
    return response.json();
};

  return(
    <>
      {person.map(item => (

{item.name}

            {item.films.map(el => (

                {el}

            ))}

      ))}

    </>
  )
}

export default App;

i don't have idea how i should to do it because in render method  "item.films" return as arr with links to get. How i can change links to movie title?

A: films.map() return all movie title in sequence.
I need to return only movie title when
the character is present
for example when we get https://swapi.co/api/people/1
response is
"name": "Luke Skywalker",
    "height": "172",
    "mass": "77",
    "hair_color": "blond",
    "skin_color": "fair",
    "eye_color": "blue",
    "birth_year": "19BBY",
    "gender": "male",
    "homeworld": "https://swapi.co/api/planets/1/",
    "films": [
        "https://swapi.co/api/films/2/",
        "https://swapi.co/api/films/6/",
        "https://swapi.co/api/films/3/",
        "https://swapi.co/api/films/1/",
        "https://swapi.co/api/films/7/"
    ],

i want to change films links to films titile for each character

A: I know its late reply, but maybe it helps someone.
After fetching your character data, you need to map on character's films, and because they are links, you have to fetch every api to get the films and then extract the data you want from it.
swapi-demo


text:
Q: How do I change the "Default" password here's my problem. When I log in I'm beeing asked for a password connecting to the internet which is strange because I'm the only user and the admin. I have auto log in and it never asks for passwords, (except when i do administrative tasks.)
I have looked in the menu (System --> preferences, but i can't find any topic that say's passwords or similar. the only place where I have found a way to change my password is my user ((System --> preferences --> user and groups).
I did try to take screenshots but nothing happened, which also is strange.
I'm running ubuntu 10.04 LTS Desktop on my Asus 1201n (12").

A:
Chrome asks for the password when your account is set for autologin.
Doing this makes it so that the keyring doesn't load when you
reset/reboot your system.
Chrome is asking for the password to the keyring so it can access
stored information in the keyring. You can view the keyring on your
system by running the command seahorse from a terminal window. You can
also just bypass the asking by closing the window and still get to
your sites without a problem. Some of the security may not load
properly.
However, you can use the following command from a terminal window to
bypass the keyring asking:
google-chrome-stable --password-store=basic

Hope this helps!

Copied entirely from @Terrance's answer here

A: It's also possible that since your using auto-login, you might be hitting another problem - sometimes network manager doesn't seem to save the WEP/WPA key properly.  You can usually get round this by opening the connection and changing it "available to all users".
So, right click on network manager, choose "Edit Connections".  Find your connection, and choose "Properties", then tick the "Available to all users" box at the bottom.

A: Sounds like your keychain is out of sync with your password.  Go to System/Preferences/Password and Encryption keys, then choose the "login" chain.

The only way that I know works is to set this to a blank password - you will be prompted on whether you are willing to trust this "unsafe storage" method, since your keyring will unlock automatically on login.
I think you can also match the password on the login keychain to match that of your login password.  But a) I haven't tested that and b) you have to remember to change your keychain password whenever you change your login password.
As the only person on my laptop, configured with encrypted home, I'm happy with unsafe storage, but your mileage may vary.

A: In order to change the root password, open a terminal
sudo passwd

When asked, provide your user password in order to perform sudo tasks, then enter the "new UNIX password" twice.
Now the root user has a new password.
You will see something like this:
geppettvs@HANNAH:~$ sudo passwd
[sudo] password for geppettvs:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
geppettvs@HANNAH:~$

Good luck!


text:
Q: NSString Comparison Where @"" == nil I want to compare two strings where I want nil to be equal to a blank string (@""). Right now I'm doing this, which works fine:
if ([self.firstName ? self.firstName : @"" isEqualToString:anotherContact.firstName ? anotherContact.firstName : @""]) {
    // They are equal.
}

But there seems like there might be something simpler that I'm missing.
I'm not looking for case sensitivity here. If case is different then the test should fail.

A: I'd suggest a function in this case:
NSString * emptyStringIfNil(NSString * s)
{
    if( !s ) return @"";
    else return s;
}

if ([emptyStringIfNil(self.firstName) isEqualToString:emptyStringIfNil(anotherContact.firstName)]) {
    // They are equal.
}

Much easier to read. You can do the internals of the function however you want; I'd say the ternary conditional would be reasonable there.

A: - (NSString*)firstName {
    return _firstName ? _firstName : @"";
}

One of the few important reasons for using property getter/setter methods is that it allows you to enforce certain conditions for a property, such as to never be nil.
You can easily ensure that properties such firstName are never nil by implementing a custom getter or setter method in a single place, and then you don't have to bother with the weird ternary operators whenever you access such properties.

A: Why not make it a macro? Seems like a perfect use case for it.
Alternatively, you could add a category on NSString: +string:isEqualToString:.

A: [string length]

works, but it will return zero if it is nil also. If that's acceptable to you, it's simpler.
btw nested ternary operators are OK in the privacy of your own home, but if you're writing code to share maybe it's better to spread it out a bit so it's obvious.
In response to comments, the way I would do it is like this:
    if((([a length] == 0) && ([b length] == 0)) ||
        ([a isEqualToString:b])) {
        // they are equal
    }

If either clause succeds then the strings are equal. The second catches any non-nil strings that are actually equal, including @"" == @"". The first catches a and b both nil, or one nil and one @"". I did write the first as ((a == nil) && (b == nil)) at first but you said @"" should equal nil.

A: you can use ?: operator. a ? a : b is same as a ?: b (with side effect of a performed once only)
if ([self.firstName ?: @"" isEqualToString:anotherContact.firstName ?: @""]) {
    // They are equal.
}


text:
Q: Stopping Account Sharing I am trying to figure out a way to stop account sharing on a site that requires a login. To solve this I would want to base it on an individuals machine or ip.  I know I could base this on a cookies, which could possible be deleted or an ip which could possibly be dynamic.  Is there something that I am not thinking of?  As of now I am thinking I would have to base it on a cookie that can only be rewritten so often with an ip.
Is this the only way to handle it or can someone point me in the right direction.

A: I would spend time looking into a system detecting account sharing instead of preventing. Not only do you not harm your average user logging in on a few locations, but it's also less time consuming and let's you be able to take more accurate action.
You can use your login / visit log for detection. More then one login in 5 minutes with distinct ip(s), the ip(s) used to login are from broad ISP's etc. etc.

A: Well, don't hobble your site without considering the consequences. The same person could be logging in from work, school, ips can change because of dynamic addressing, etc...
You could force each id to be logged in from a unique location (e.g. record each login in a table where certain fields comprise a unique key, and look for insertion exceptions).  A login from a new location while the old location has been recently active could be set either to (a) fail at the new location, or (b) cause a failure at the old location, (c) inform the alternate location, (d) log somewhere.  Also, providing a table of where you've logged in from, shown to the user in fine print, together with a blurb on the policy might aid in compliance among "honest" people.


text:
Q: how to load Register form lables caption from other language file? i have create a twig registration form. i want to make all labels caption variable to be changed as per user language. my language file is seperated in PHP file, please how to load all variables from language PHP file to the template .twig file ??
and here is a form :
{{ header }}

 {{text_heading}}

 {{text_register}}

 <form action="{{ action }}" method="post" enctype="multipart/form-data">

     {{entery_fullname}}
    <input type="text" name ="fullname" value="{{ username }}" placeholder ="{{place_fullname}}">

 </input>

     {{entery_email}}
    <input type="email" name ="email" placeholder ="{{place_email}}">

 </input>

     {{entery_phone}}
    <input type="phone" name ="phone" placeholder ="9xxxxxxxx">

 </input>

    {{ entry_password }}
    <input type="password" name="password" value="{{ password }}" placeholder="{{ place_password }}" />

    <input type="radio" name ="usertype" value = "customer" checked>
     {{Text_Customer}}

    <input type="radio" name ="usertype" value = "vendor">
     {{Text_Vendor}}

    <input type="radio" name ="usertype" value = "both" >
     {{Text_Both}}

    <button name ="register" type ="button"  method ="submit"> {{btn_register}} </button>

 {{text_forgotten}}

</form>
{{ footer }}

my language file is PHP, and here it is:
<?php
// Heading
$_['heading_title']  = 'Administration';

// Text
$_['text_heading']   = 'Administration';
$_['text_register']     = 'Please enter your details to register.';
$_['text_forgotten'] = 'Forgotten Password';
$_['Text_Customer'] = 'Im a Customer';
$_['Text_Vendor'] = 'Im a Vendor';
$_['Text_Both'] = 'Both Customer/Vendor';
// Entry
$_['entery_fullname'] = 'Your Full Name: ';
$_['entery_email'] = 'Email: ';
$_['entery_phone'] = 'Phone No: ';
$_['entry_password'] = 'Password: ';

// Button
$_['btn_register'] = 'Register';

// placeholders
$_['place_fullname'] = 'Your Real Full Name';
$_['place_email'] = 'Active Email';
$_['place_password'] = 'Strong password';
// Error
$_['error_register']    = 'Check your input carfully.';
$_['error_token']    = 'Invalid token session. Please register again.';
?>

A: You should use twig filters for this.
Register a filter trans and use it like:
{{"phrase"|trans}}

Then you would use own or third party implementation (like symfony/translations) to load and translate phrases.

A: i fix the proble:
first i convert twig file to php file
and i use (define) on language file like this:
define('entery_fullname', 'Your Full Name:');

but my question now, is this way is better or there is somthing else more faster and much better?


text:
Q: HTML connected graph drawing Exists an algorithm that calculate the position of nodes of a connected graph?
I like to draw the nodes of the graph as HTML DIV and have an algorithm that allows to positionate the nodes on the html page (using absolute position) according to the connections , like a mind map.

A: Generate SVG from dot, and write an XSLT that translates the SVG xml into the required HTML (on the server side).
Or, if you don't care about IE versions less than 9, just serve the SVG


text:
Q: function calling by rigid python keyword why list object is not callable inside a function ??
CODE:
def unique_list(list1):

    sets=set(list1)

    u_list=(list(sets))

    print("old list",list1)
    print('unique list',u_list)

list1=[1,1,2,3,4,4,5]
unique_list(list1)

when i did this.. I got the exact output [1,2,3,4,5]... BUT
if i use list in lieu of list1 or any other name  like the following code:
def unique_list(list):
     sets=set(list)
    u_list=(list(sets))
    print("old list",list)``
    print('unique list',u_list)

list=[1,1,2,3,4,4,5]
unique_list(list)

python throws error:
TypeError: 'list' object is not callable

is it for this reason that rigid keywords must not be used as variable name ?? or for other reasons ??

A: Heres working code for what you want to do
def unique_list(list1):
    print("old list",list1)
    print('unique list',(list(set(list1))))

list1=[1,1,2,3,4,4,5]
unique_list(list1)

here's why your code wasn't working
lets take a look at the code that defines your function
def unique_list(list):
    #code

list is a class name and list() is a function that is native to python; by making it a parameter and or variable, you are overriding it!
So, when you call list(set(list)) its basically saying: parameter(set(parameter))
Obviously the parameter cant be a function and a list at the same time; so there isn't any scenario where this could work.
I recommend using convention names like so if you arent sure what to call a list:
lst = []
x = []
l = []

The only time you should ever put any of these names alone into the definition of a function is through type-hinting
def foo(s: str, l: list) -> list:
    #do code
    return l + list(s)

In conclusion... it's a horrible practice to use any built-in function/class names in python as variable/functions unless you are actually trying to override them.


text:
Q: dataframe object is not callable in pyspark temp = Window.partitionBy("id").orderBy("time").rowsBetween(-5, 5)
spark_df.withColumn("movingAvg",fn.avgspark_df("average")).over(temp)).show()

I'm getting this error in the last line .

dataframe object is not callable

A: You are missing a bracket, but it also seems some of the syntax is wrong. I assume this is what your code was before the bracket got missing:
fn.avgspark_df("average")

Which is why you get the error; you are trying to call the DataFrame as a function. I believe you can achieve what you want with:
import pyspark.sql.functions as fn
from pyspark.sql import Window

df = pd.DataFrame({'id': [0,0,0,0,0,1,1,1,1,1],
                   'time': [1,2,3,4,5,1,2,3,4,5],
                   'average':[0,1,2,3,4,5,6,7,8,9] })
df = sqlContext.createDataFrame(df)

temp = Window.partitionBy("id").orderBy("time").rowsBetween(-1, 1)
df.withColumn("movingAvg",fn.avg("average").over(temp)).show()

A:  from pyspark.sql import SparkSession
 from pyspark.sql import Window
 from pyspark.sql.functions import max,min,avg
 spark = SparkSession.builder.appName("Data Frame Example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()

 l=[("Alice", "2016-05-01", 50.00),
                                ("Alice", "2016-05-03", 45.00),
                                ("Alice", "2016-05-04", 55.00),
                                ("Bob", "2016-05-01", 25.00),
                                ("Bob", "2016-05-04", 29.00),
                                ("Bob", "2016-05-06", 27.00)]

customers = spark.sparkContext.parallelize(l).toDF(["name", "date", "amountSpent"])

temp = Window.partitionBy("name").orderBy("date")

customers.withColumn( "movingAvg",avg("amountSpent").over(temp)).show()


text:
Q: Code splitting `import` breaks Jest tests I'm using the code splitting feature of webpack, but it seems that jest doesn't recognize the import() function:
        import('myModule').then(function (myModule) {
        ^^^^^^
SyntaxError: Unexpected token import

I don't have any special setup. My npm test script is simply run jest "test": "jest"
How can I make it work?
I'm using the latest version of jest 20.0.4 and babel-jest 20.0.3

A: Oh I just found the answer.
Simply install this plugin: https://github.com/airbnb/babel-plugin-dynamic-import-node and add it to the .babelrc file:
{
  ...
  "env": {
    "test": {
      "plugins": ["dynamic-import-node"]
    }
  }
}


text:
Q: making cascading dropdownlist I am  trying to make cascading dropdown list in ASP.NET MVC4, both values for my dropdown list's comes from methods, so am in trouble how to pass value form one dropdown list to another.
Here's how I get values for the  first dropdown list:
var CampaignInfo1 = CampaignManagementService.GetAdvertisers((string)Session["ticket"]);
List<CampaignList1> items1 = new List<CampaignList1>();
foreach (var element in CampaignInfo1)
{
    items1.Add(new CampaignList1() { ID1 = element.Key, Name1 = element.Value });
}
var listOfCamp1 = new SelectList(items1, "ID1", "Name1", 1);
ViewData["list1"] = listOfCamp1;

And dropdown list in view:
@Html.DropDownList("list1", ViewData["list1"] as SelectList, "-- Select Client -1-")

The second dropdown list value am getting almost  same method:
var CampaignInf = CampaignManagementService.GetCampaigns((string)Session["ticket"], IDFromfirstDDL);
List<AlreadyCreatedCampaignList> itemas = new List<AlreadyCreatedCampaignList>();
foreach (var element in CampaignInf)
{
    itemas.Add(new AlreadyCreatedCampaignList() { campID = element.Key, campName = element.Value });
}
var listOfCam = new SelectList(itemas, "campID", "campName", 1);
ViewData["clist"] = listOfCam;

But there  is a problem that in method GetCampaigns I have to pass the id(IDFromfirstDDL) which I get from first DDL, and only then method return values which are  for that id.
The problem is that I don't know how to pass that selected value from first DDL to second, without any form submit, because I need that second DDL changes his values immediately after first DDL changes.

A: i made it combining http://kruisit.nl/articles/asp.net-mvc-linked-dropdown/  and  http://www.appelsiini.net/projects/chained jquery chained selector this article
currently using in my site
public static class LinkedDropdownHelper
        {
            #region Methods

            public static MvcHtmlString LinkedDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string parent, IEnumerable<LinkedSelectListItem> selectList ,bool removedefault=false)
            {
                ModelMetadata metadata = ModelMetadata.FromLambdaExpression( expression,htmlHelper.ViewData );
                var selectedvalue = metadata.Model;
                string propertyName = metadata.PropertyName;
                TagBuilder select = new TagBuilder("select");
                select.Attributes.Add("id", propertyName);
                select.Attributes.Add("name", propertyName);
                //select.Attributes.Add("class", "linked-dropdown");
                select.Attributes.Add("class", parent);

                foreach (var item in selectList)
                {
                    if (removedefault && item.Value == "-1")
                    {
                        //skip default
                    }
                    else
                    {
                        TagBuilder option = new TagBuilder("option");
                        option.InnerHtml = item.Text;
                        option.Attributes.Add("value", item.Value);
                        option.Attributes.Add("class", item.LinkValue);

                        if (item.Selected)
                        {
                            option.Attributes.Add("selected", "selected");
                        }
                        select.InnerHtml += option.ToString(TagRenderMode.Normal);
                    }
                }
                //below code was changed by abdurrauf to support jquery chains
                string script = @"<script type='text/javascript'>$(document).bind('ready',  function(){
            $('#" + propertyName + "').chained('#" + parent + "');"+
                   @"$('select[name=""" + propertyName + @"""]').val("""+selectedvalue+@""");" +
                  "});</script>";

                return MvcHtmlString.Create(script + select.ToString(TagRenderMode.Normal));
            }

            #endregion Methods
        }

        public class LinkedSelectList : IEnumerable<LinkedSelectListItem>
        {
            #region Constructors

            public LinkedSelectList(IEnumerable items, string dataValueField, string dataTextField, string dataLinkedValueField, IEnumerable selectedValues)
            {
                if (items == null)
                {
                    throw new ArgumentNullException("items");
                }

                Items = items;
                DataValueField = dataValueField;
                DataTextField = dataTextField;
                DataLinkedValueField = dataLinkedValueField;
                SelectedValues = selectedValues;
            }

            #endregion Constructors

            #region Properties

            public string DataLinkedValueField
            {
                get; private set;
            }

            public string DataTextField
            {
                get; private set;
            }

            public string DataValueField
            {
                get; private set;
            }

            public IEnumerable Items
            {
                get; private set;
            }

            public IEnumerable SelectedValues
            {
                get; private set;
            }

            #endregion Properties

            #region Methods

            public virtual IEnumerator<LinkedSelectListItem> GetEnumerator()
            {
                return GetListItems().GetEnumerator();
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }

            internal IList<LinkedSelectListItem> GetListItems()
            {
                return GetListItemsWithValueField();
            }

            private static string Eval(object container, string expression)
            {
                object value = container;
                if (!String.IsNullOrEmpty(expression))
                {
                    value = DataBinder.Eval(container, expression);
                }
                return Convert.ToString(value, CultureInfo.CurrentCulture);
            }

            private IList<LinkedSelectListItem> GetListItemsWithValueField()
            {
                HashSet<string> selectedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                if (SelectedValues != null)
                {
                    selectedValues.UnionWith(from object value in SelectedValues select Convert.ToString(value, CultureInfo.CurrentCulture));
                }

                var listItems = from object item in Items
                                let value = Eval(item, DataValueField)
                                select new LinkedSelectListItem
                                {
                                    Value = value,
                                    Text = Eval(item, DataTextField),
                                    LinkValue = Eval(item, DataLinkedValueField),
                                    Selected = selectedValues.Contains(value)
                                };
                return listItems.ToList();
            }

            #endregion Methods
        }

        public class LinkedSelectListItem
        {
            #region Properties

            public string LinkValue
            {
                get; set;
            }

            public bool Selected
            {
                get; set;
            }

            public string Text
            {
                get; set;
            }

            public string Value
            {
                get; set;
            }

            #endregion Properties
        }


text:
Q: SPFx solution deployment failure I'm trying to Deploy my SPFX Solution using CI/CD Pipeline.
While running the pipeline it is throwing me this error with react-select File. The error message is the below:

Error - tsc node_modules/react-select/dist/declarations/src/accessibility/index.d.ts(1,13): error TS1005: '=' expected

Can someone help me with this?  Thanks in Advance.


text:
Q: Administer a Domain with only one IP in AWS Networking Noob here in some dire need for help!
Say I have only one public IP (let's say 54.0.0.1) I want to use and several servers in a domain locally.
I have created and registered a domain example.com.
Now I would like to have one server with the public IP 54.0.0.1 that administers the traffic coming in from people entering example.com into their browser, and redirects the traffic to different servers in the local network, depending what subdomain they entered.
E.g. if someone types shop.example.com the DNS recognizes example.com, resolves the request to 54.0.0.1 at which point the server redirects the traffic to the shop server with the address 172.0.0.3 in the same network as the Public Server but with no direct internet access.
And then if someone enters contact.example.com they get redirected to a 3rd server with the local address 172.0.0.4 etc.
Is this scenario even possible with only one Public IP? And if yes, any tips on how to accomplish this in Amazon Webservice would be appreciated.
I have informed myself about NAT-Gateways, Proxys and DNS but I can't seem to put it all together.

A: I would stop trying to use a specific IP address all together. Just create an AWS Application Load Balancer and place it in front of all the different EC2 servers serving all of your domains. An ALB can handle directing the request to the appropriate server, as well as serving the appropriate SSL certificate for each server. Also, you can use Amazon's free SSL certificates from the ACM service with an ALB.

A: Yes it can be possible. Create one application load balancer. Then create the web servers as you described which hosts multiple subdomains.
Then create a target group per subdomain and forward the traffic from application load balancer. In application load balancer you have to define the rule(host-based routing) where, if the request comes for shop.example.com then forward it to that particular target group.  You can also create(in ACM) and attach a wildcard SSL certificate for your domain on ALB.
Also, you don't need to use public IP/Elastic IP in this case as making ALB interfacing will do the trick.
Please refer:
https://awstutorialseries.com/blog/post/host-based-routing-application-load-balancers
http://docs.aws.amazon.com/elasticloadbalancing/latest/application/application-load-balancer-getting-started.html


text:
Q: Sprite Kit iOS 7 - how to add a shadow to a SKSpriteNode? I have a SKSpriteNode containing other SKSpriteNodes. How can I create a copy of this SKSpriteNode where all the pixels are black?
Once I have this shadow SKSpriteNode I will then flip it upside down and use it as a shadow.
Thanks

A: You can create a shadow using the same image like this :
SKSpriteNode *shadow = [SKSpriteNode spriteNodeWithImageNamed:@"YourImageName"];

shadow.blendMode = SKBlendModeAlpha;
shadow.colorBlendFactor = 1;
shadow.color = [SKColor blackColor];
shadow.alpha = .25;  // make shadow partly transparent

Then just position it however you like based on desired light direction. Alpha isn't needed if you want it to be solid black.


text:
Q: VB.Net connection I'm slowly transitioning to VB.Net and it seems like the simplest of things are completely different. I'm trying to do a connection to SQL Server and just grab some data. I've tested the connection and it's fine. Now I'm trying to simply select some data from the server and display the first name in the Msgbox (or anything for that matter). Here is the code I've gotten so far....
Imports System.Data
Imports System.Data.SqlClient

Public Class Form1
    Public conn As New SqlConnection("data source=Tuys1;initial catalog=DDDBuyer; user ID=userID; password=password")
    Private dA As New SqlDataAdapter("Select FirstName, LastName from tblBuyers where Buyerid=1473", conn)
    Private dS As New DataSet
End Class

I'm not really sure how to go from here... I understand there is something like
.hasRows

if ds.hasrows then
   msgbox = "HELLO"
End if

or something like displaying the FirstName in txtFirstName
I am trying to get an idea of how ths works and after some research it's hard to find a specific example that would help me do what I'm trying to accomplish.

A: Dim custAdapter As SqlDataAdapter = New SqlDataAdapter( _
  "SELECT * FROM dbo.Customers", customerConnection)

Dim ordAdapter As OleDbDataAdapter = New OleDbDataAdapter( _
  "SELECT * FROM Orders", orderConnection)

Dim customerOrders As DataSet = New DataSet()
custAdapter.Fill(customerOrders, "Customers")
ordAdapter.Fill(customerOrders, "Orders")

Dim relation As DataRelation = _
  customerOrders.Relations.Add("CustOrders", _
  customerOrders.Tables("Customers").Columns("CustomerID"), _
  customerOrders.Tables("Orders").Columns("CustomerID"))

Dim pRow, cRow As DataRow
For Each pRow In customerOrders.Tables("Customers").Rows
  Console.WriteLine(pRow("CustomerID").ToString())

  For Each cRow In pRow.GetChildRows(relation)
    Console.WriteLine(vbTab & cRow("OrderID").ToString())
  Next
Next

As explained here


text:
Q: Help normalizing a wave function I don't see how the author normalizes $u(r)=Asin(kr)$. From Griffiths, Introduction to Quantum Mechanics, 2nd edition, page 141-142:

My integral was
$$\int_0^{\infty} \int_0^{\pi} \int_0^{2\pi}|A|^2 \sin^2(\frac{n\pi r}{a})r^2 \sin \theta drd\theta d\phi=1$$
Mathematica simplifies the integral (without the $A$ for simplicity) to
$$=\int_0^{\infty}4\pi r^2 \sin^2(\frac{n\pi r}{a})dr$$
but it stops there. I don't think this integral converges. Did I make a mistake somewhere?

A: You have to normalise $u(r)$.
What is $u(r)$ if $r>a$?
Are you sure about your upper limit for $r$ in your normalisation integral?


text:
Q: Grails GORM locks table when updating a DB table I am iterating over a large dataset and updating each row.
The data locked as long as its loops and the changes are not saved until its all done
My Code:
In the controller
stocks.each { stock ->

        def s = stockService.updateData(stock)
        stockService.save s
    }

and the save method in the service is the only on with @Transactional:
@Transactional
private void save(Stock stock) {
    stock.save(failOnError: true, flush: true)
}

A: If you dont want that the datasets are locked the whole time, you can create a transaction for each save:
private void save(Stock stock) {
    Stock.withNewTransaction {
        stock.attach()
        stock.save()
    }
}

The disadvantage is, that a rollback of all changed datasets is not possible on errors.


text:
Q: Failure to run protractor from Node.js command prompt Hope all is well. I'm setting up protractor for the first time through Node.js. This is provided as part of a tutorial on the AngularJS website under "Running E2E Tests":
https://docs.angularjs.org/tutorial
However, while executing protractor through the provided command "npm run protractor", I get the following error within the Node.js command prompt:
E/launcher - Process exited with error code 199

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "protractor"
npm ERR! node v6.9.1
npm ERR! npm  v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! angular-phonecat@0.0.0 protractor: `protractor e2e-tests/protractor.conf.js`
npm ERR! Exit status 199
npm ERR!
npm ERR! Failed at the angular-phonecat@0.0.0 protractor script 'protractor e2e-tests/protractor.conf.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the angular-phonecat package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     protractor e2e-tests/protractor.conf.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs angular-phonecat
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls angular-phonecat
npm ERR! There is likely additional logging output above.

Here is the contents on the package.json file:
{
  "name": "angular-phonecat",
  "private": true,
  "version": "0.0.0",
  "description": "A tutorial application for AngularJS",
  "repository": "https://github.com/angular/angular-phonecat",
  "license": "MIT",
  "devDependencies": {
    "bower": "^1.7.7",
    "http-server": "^0.9.0",
    "jasmine-core": "^2.4.1",
    "karma": "^0.13.22",
    "karma-chrome-launcher": "^0.2.3",
    "karma-firefox-launcher": "^0.1.7",
    "karma-jasmine": "^0.3.8",
    "protractor": "^4.0.9"
  },
  "scripts": {
    "postinstall": "bower install",
    "prestart": "npm install",
    "start": "http-server ./app -a localhost -p 8000 -c-1",
    "pretest": "npm install",
    "test": "karma start karma.conf.js",
    "test-single-run": "karma start karma.conf.js --single-run",
    "preupdate-webdriver": "npm install",
    "update-webdriver": "webdriver-manager update",
    "preprotractor": "npm run update-webdriver",
    "protractor": "protractor e2e-tests/protractor.conf.js",
    "update-index-async": "node -e \"var fs=require('fs'),indexFile='app/index-async.html',loaderFile='app/bower_components/angular-loader/angular-loader.min.js',loaderText=fs.readFileSync(loaderFile,'utf-8').split(/sourceMappingURL=angular-loader.min.js.map/).join('sourceMappingURL=bower_components/angular-loader/angular-loader.min.js.map'),indexText=fs.readFileSync(indexFile,'utf-8').split(/\\/\\/@@NG_LOADER_START@@[\\s\\S]*\\/\\/@@NG_LOADER_END@@/).join('//@@NG_LOADER_START@@\\n'+loaderText+'    //@@NG_LOADER_END@@');fs.writeFileSync(indexFile,indexText);\""
  }
}

I don't know if anyone else has tried this same tutorial and is getting the same issue? Any help would be most appreciated, thank you.

A: So Protractor can be started in several ways, the most common are by directConnect or by seleniumAddress. Since no value was set in the e2e-tests/protractor.config.js file, the assumed value is directConnect. To get directConnect to work with the chrome browser, you'll need to get the latest chromedriver. To just install chromedriver:
./node_modules/.bin/webdriver-manager update --standalone=false --gecko=false

Or as suggested in the github angular-seed page which will download, in addition, the selenium standalone jar file and gecko driver (which is used for firefox):
npm update-webdriver


text:
Q: Find the median of binary search tree, C++ Once I was interviewed by "One well known company" and the interviewer asked me to find the median of BST.
int median(treeNode* root)
{

}

I started to implement the first brute-force solution that I came up with. I fill all the data into a std::vector<int> with inorder traversal (to get everything sorted in the vector) and got the middle element.
So my algo is O(N) for inserting every element in the vector and query of middle element with O(1), + O(N) of memory.
So is there more effective way (in terms of memory or in terms of complexity) to do the same thing.
Thanks in advance.

A: It can be done in O(n) time and O(logN) space by doing an in-order traversal and stopping when you reach the n/2th node, just carry a counter that tells you how many nodes have been already traversed - no need to actually populate any vector.
If you can modify your tree to ranks-tree (each node also has information about the number of nodes in the subtree it's a root of) - you can easily solve it in O(logN) time, by simply moving torward the direction of n/2 elements.

A: The binary tree offers a sorted view for your data but in order to take advantage of it, you need to know how many elements are in each subtree. So without this knowledge your algorithm is fast enough.
If you know the size of each subtree, you select each time to visit the left or the right subtree, and this gives an O(log n) algorithm if the binary tree is balanced.

A: Since you know that the median is the middle element of a sorted list of elements, you can just take the middle element of your inorder traversal and stop there, without storing the values in a vector. You might need two traversals if you don't know the number of nodes, but it will make the solution use less memory (O(h) where h is the height of your tree; h = O(log n) for balanced search trees).
If you can augment the tree, you can use the solution I gave here to get an O(log n) algorithm.


text:
Q: Openresty Lua : cannot connect to redis after receiving response from api-server I am making a call limiter based on api key and I am keeping counter of calls in redis where key is my api-key and value is a counter. After threshold or allowed call for that key is reached I throw a message stating your quota reached or something.It works fine and response is also quick, but the problem is I cannot access response status of api-server so even if the response is 500 , the call counter gets increased.
Now, what I need to do is, increase counter only if I get status code 2.x.x , but I can only capture response ngx.status in body_filter_by_lua_file but in this directive I cannot make connection to redis or postgres. It throws failed to run body_filter_by_lua*: attempt to yield across C-call boundary error , I can, however connect to redis in content_by_lua_file but cannot access response status. Hope I made it clear.
PS: I am using latest openresty and lua-resty-redis

A: One workaround I can suggest is to move the code that connects to Redis.
to a separated function and schedule this function with ngx.timer.at.
It works for me, but with one disadvantage compared to using ngx.shared.DICT.
Of course, the next request may come before the Redis data has been updated in the timer.


text:
Q: Emberjs: Handling form submission, params, access to model (Warning: newbie) Going around the block on this one, as each example I see does it differently (and none work for me)
var InitiativesNewRoute = Ember.Route.extend({
  model: function(params) {
    return this.store.createRecord('initiative', params);
  },

  actions: {
    submit: function() {
      var initiative = this.get('model');
      initiative.save().then(function(model) {
        this.transitionTo('initiatives.show', initiative);
      });
    }
  }
});

Saving barfs as initiative is undefined, but I see a record created in the ember chrome plugin. So it looks like creating the record in model works, but fetching it in the action doesn't.
Also tried this example:
submit: function(initiative) {
  initiative.save().then(function(model) {
    this.transitionTo('initiatives.show', initiative);
  });
}

Without passing passing params to createRecord above, and I get the same error. How do I do this?
Using ember-cli 0.0.39 and easy-form, with the fixture adapter.

A: Got some help on #emberjs and managed to get it working like this:
var InitiativesNewRoute = Ember.Route.extend({
  model: function(params) {
    return this.store.createRecord('initiative', params);
  },

  actions: {
    submit: function() {
      var _this = this;
      var initiative = this.get('controller.model');
      initiative.save().then(function(model) {
        _this.transitionTo('initiatives.show', model.get('id'));
      });
    }
  }
});


text: Q: If U is a finite-dimensional subspace of W, prove the orthogonal complement of W is a subspace of the orthogonal complement of U If U is a finite-dimensional subspace of W, prove the orthogonal complement of W is a subspace of the orthogonal complement of U. Not sure how I start with this proof. Can someone help?


text:
Q: If $a+bc$ and $c$ have irreducible factors in common, then $a$ and $c$ have the same irreducible factors in common. Let $a,b,c \in K[t]$ where $K$ is field with characteristic not $2$ or $3$ and see title for the question. This is a problem I encountered in showing the image of some map is finite, which I need in my thesis. I tried decomposing in irreducible elements, but I got stuck. Any help would be appreciated.

A: No. Take $a=6$, and $c=2$. Then $a+bc$ and $c$ have the factor $2$ in common, but $a$ has the factor $3$ that's not common to $c$.
These are integers, you'd object. But it's the same over any UFD with at least two distinct irreducible elements $p$ and $q$. Take $a=pq$ and $c=p$.
The ring $K[t]$ has infinitely many irreducible elements, so you're doomed.


text:
Q: Exist closed forms of the distribution of return time in markov chains? Hi, I am interested in the distribution of return times in simple random walks on finite graphs.
Let $G$ be a connected finite graph with, with two independent random walks. If both random walks start are at time $t_0$ on the same node in the graph, how long does it take until they meet again? I have not found papers on this specific problem, but read that is can be transformed to a single random walk and the question of when the random walk returns to exactly the node where it is at $t_0$.
As such I am interested in the distribution of these return times. Generally I know how to compute the numeric values of the distribution for a given graph. But my question is whether this can be modeled through a given distribution (e.g. exponential).
Besides the PDF I am more interested in the CDF of this return time distribution.

A: I assume you mean the distribution of the time of first return, and I assume you're talking
about finite graphs.
I'll volunteer the naive answer:  let $M$ be the matrix of transition probabilities for your random walk, and let $M_i$ be the matrix obtained by modifyiong $M$ to make the $i$th column all 0's except for $1$ in the $(i,i)$ entry.  In other words, it's the matrix for a new random walk
that matches the old one, except whenever you get to $i$, you're trapped forever.
The CDF for first return from $j$ to $i$ is the sequence of $(i,j)$ entries of
$M_i^{n-1} \cdot M$: you start off with $M$, and afterward use $M_i$, and see if you've gotten
from $j$ to $i$.
If you transform $M_i$ into Jordan canonical form, there is a closed formula for
all its powers $\cdot M$; the $(i,j)$ entry is a linear functional on those powers.
If you want numerical answers for not-too-huge graphs, this should be easily workable. If
you want answers for a totally general directed graph with weighted edges, this corresponds
to a totally general matrix $M$, and it's unreasonable to expect any better answer. If
you have in mind some particular class of graphs with nice properties and nice random walks, then a lot more can be said, but I'm not an expert so I won't plunge in: perhaps some experts will say something about what's known.

A: The question you ask is pretty broad, and it's not clear to me what kind of answers you seek.
In fact, I suggest you clean up the question a little bit (for example, what does "the return times for every pair in the graph." mean?).
I'm not sure whether this is relevant, but Asaf Nachmias and I have a paper on some properties of the distribution of the first time a simple random walk returns to its starting point on an infinite graph. The results can also be adapted, to some extent, to finite graphs.


text:
Q: Equation involving structure constants of Lie algebra - is this proof correct? Let a Lie group $G$ with Lie algebra $\mathfrak{g}$ be given. Suppose further $G$ is compact and semi-simple. Let $X^a\in \mathfrak{g}$ be a basis of the Lie algebra, $a=1,\dots, \dim \mathfrak{g}$, and define the structure constants
$$[X^a,X^b]=f^{ab}_{\phantom{ab}c}X^c\tag{1}$$
where the summation convention is implied (repeated indices are summed over).
I wanted to prove that if $A,B,C\in \mathbb{C}$ the equation
\begin{eqnarray}Af^a_{\phantom{a}dc}f^{cb}_{\phantom{cb}e}+Bf^b_{\phantom{b}dc}f^{ac}_{\phantom{ac}e}= Cf^{ab}_{\phantom{c}}f^{c}_{\phantom{c}de}\tag{2}\end{eqnarray}
implies $A = C$. I have come up with a proof and wanted to know if it is correct.
I start by raising all the indices in (2), writing the equation in the equivalent form
\begin{eqnarray}Af^{adc}f^{cbe}+Bf^{bdc}f^{ace}= Cf^{abc}f^{cde},\tag{3}\end{eqnarray}
then I take $b = d$ and sum over this index. Since $f^{bdc}$ is anti-symmetric in the first two indices, as we see easily from (1), it follows that the middle term vanishes when we do that. The equation becomes
$$Af^{abc}f^{cbe}=Cf^{abc}f^{cbe}\Longrightarrow (A-C)f^{abc}f^{cbe}=0\tag{4}.$$
To finish the proof we must argue that $f^{abc}f^{cbe}\neq 0$ at least for some pair of indices $a,e$. In that case, since $G$ is compact and semi-simple $f^{cbe}$ is totally anti-symmetric and we can write $f^{cbe}=-f^{ebc}$. But then we know that $f^{abc}f^{ebc}=\delta^{ae}$. It follows that for all $a = e$ the quantity $f^{abc}f^{cbe}$ is non-zero and therefore we must have $A =C $.
Now, is this proof correct? I have two very basic doubts about what I did:

*

*I don't know if it is indeed legit to simply raise all the indices when going from (2) to (3).

*I don't know whether the last step, where I invoked that $G$ is compact and semi-simple, is really necessary. I mean, can't we conclude $f^{abc}f^{cbe}\neq 0$ without these assumptions?

A: 1.
Not in general. In index computations, raising and lowering indices usually requires a nondegenerate bilinear form $b$, so that one can define the raising and lowering $U_a:=b_{ab}U^b$, $V^a:=b^{ab}V_b$ where $b^{ab}$ are the coefficients of the inverse of $b$. In the case of a compact Lie algebra, such a form exists: the Killing form (or its negative). In the case of a positive definite form, a common choice is to work in $b$-orthonormal basis satisfying $b_{ab}=b^{ab}=\delta^a_b$, so indices can be raised and lowered "for free", and there's no need to distinguish between upper and lower indices. Your computation only works in such a basis.
2.
We certainly need some information about the structure of the algebra to conclude that the term is nonzero; otherwise, for example, $\mathfrak{g}$ could be Abelian, and all structure constant would vanish.


text:
Q: Bootstrap modal popup close on button (type=submit) post back asp.net c# bootstrap modal popup on post back event of button (type=submit) it's close automatically.asp.net c# web form. (type=submit)
Solutions that don't work:

*

*I could not get it to work with an Update Panel.

*Can't reopen like javascript thorough again modal popup show. Because I am opening modal up from different page.
 function OpenModal() {
    var strUrl = "page.aspx";
    $('.modal-body').load(strUrl, '', function () {
        $('#myModal').modal();
    });
}


text:
Q: How to refactor methods I have two methods. They're very similar.
I've tried use Generics, but it doesn't work with TryParse()
    public static int EnterIntengerNumber()
    {
        while (true)
        {
            Console.Write("Enter an intenger number: ");
            if (int.TryParse(Console.ReadLine(), out int number))
            {
                return number;
            }
            else
            {
                ConsoleError("Incorrect value");
            }
        }
    }

    public static double EnterRealNumber()
    {
        while (true)
        {
            Console.Write("Enter a number: ");
            if (double.TryParse(Console.ReadLine(), out double number))
            {
                return number;
            }
            else
            {
                ConsoleError("Incorrect value");
            }
        }
    }

How can I combine or refactor them?

A: You can make function, that accepts a delegate with the TryParse parameters and return value as generic. Also you can/will have to make string for asking the correct type. but this can be improved from this example:
    static void Main(string[] args)
    {
        var myDouble = EnterSomething<double>("a double", double.TryParse);
        var myInt = EnterSomething<int>("an interger", int.TryParse);
        Console.WriteLine(myDouble);
        Console.WriteLine(myInt);

        Console.ReadLine();
    }

    public delegate bool TryParseFunction<Tout>(string input, out Tout output);

    public static Tout EnterSomething<Tout>(string typeName, TryParseFunction<Tout> parser)
    {
        while (true)
        {
            Console.Write("Enter " + typeName + " number: ");
            if (parser(Console.ReadLine(), out Tout number))
            {
                return number;
            }
            else
            {
                Console.WriteLine("Incorrect value");
            }
        }
    }

Small additional explanation: the int.TryParse - passing to the EnterSomething is not calling the TryParse. It is actually just "passing" the function so that it can be called in the EnterSomething.
The reason of not using Func<> is that it does not support out variables, see here some example: Func<T> with out parameter
EDIT: I remove the Tin-type parameter, as the input is string anyway.

A: You can use Convert.ChangeType
Do keep in mind you will end up using boxing so the point of using generics is lost. Though you do end up having less code.
    public static T EnterNumber<T> ()
    {
        while (true)
        {
            Console.Write("Enter an " + typeof(T) + " number: ");
            try
            {
                return (T) Convert.ChangeType(Console.ReadLine(), typeof(T));
            }
            catch (FormatException ex)
            {
                Console.Write("Incorrect format" + ex.Message);
            }
        }
    }

A: You could try it this way:
public static int EnterIntengerNumber()
{
    return EnterNumber(t => int.TryParse(t, out int v) ? (int?)v : null)
}

public static double EnterRealNumber()
{
    return EnterNumber(t => double.TryParse(t, out double v) ? (double?)v : null)
}

private static T EnterNumber<T>(Func<string, T?> tryParse) where T : struct
{
    while (true)
    {
        Console.Write("Enter a number: ");
        T? result = tryParse(Console.ReadLine());
        if (result.HasValue)
        {
            return result.Value;
        }
        else
        {
            ConsoleError("Incorrect value");
        }
    }
}


text:
Q: Word wrapping in pango with mixed scripts I have a text box implementation that uses pango.  If i put a string that starts with a word in right-to-left script, followed by a space, followed by word in left-to-right based script, the word wrapping that pango uses gets messed up (using PANGO_WRAP_WORD_CHAR).  For the string العربية ENGLISH I get the following:

If I add the unicode character U+200F after the space, then I get the expected word wrapping:

Also, if I replace the Arabic script above with Hindi (which is left-to-right like the English next to it) then I still get the problem, so it doesn't seem to be a strictly left-to-right, right-to-left thing.  In the Hindi case, I put in a hack that inserts a 0x200E after the space it resolves the problem.
Is this a bug in pango?  Are there work-arounds I can try that are generic enough to fix the problem but not break other cases?  The current work around I'm using inserts either a 0x200E or 0x200F after every space based on the direction of the previous strongly directed character in the string, but I'm not sure if there's certain strings that this will cause problems with.
Update: I was able to reproduce this problem on Ubuntu 12.04 with gedit (with Enable Text Wrapping and Do no split words over two lines settings enabled).  I simply typed Hello world over and over until it wrapped several times, then replaced all instances of world with पहुंचगया, and everything collapsed to a single line.

A: The symbols U+200F and U+200E are RIGHT-TO-LEFT and LEFT-TO-RIGHT Marks. S:

*

*between each english text and arabic text, put  a RIGHT-TO-LEFT mark

*between each arabic text and  english text, put a LEFT-TO-RIGHT mark

It is a bug because Pango should this automatically in viewing text but as Pango isnt doing it, you should do it manually.

A: It seems to me a bug or not complete feature as it appears on mixed scripts.
Seem to me you are using an old pango development, may be from Ubuntu 12.04?
Ubuntu 12.04 contains Gedit 3.4
Ubuntu 15.10 contains Gedit 3.10

Pango has radical change in 3.6, it has replaced his shaping engine with HarfBuzz. [2]
I couldn't reproduce the bug using Gedit 15.10, it always moves (2) two words down, also it does not allow me to resize its window to try splitting those two words. See screen-shot.

Update:
It seems its behavior has changed:

*

*It does not wrap the 1st word from English script when start with Arabic.
pango-view  --text "وقعت أطراف سياسية ليبية اليوم في المغرب اتفاق سلام برعاية أممية aljazeeranet" --width=70 --margin=0 --wrap=word

*It same as previous case, does not wrap, and enforce the width
pango-view  --text "elections الجزيرة" --width=30 --margin=0 --wrap=word

References:

*

*Port pango to Harfbuzz

A: Note, we recently upgraded the version of pango we used, from pango version 1.36.1  to 1.38.1, and this issue went away.  So I believe this was a bug in pango or harfbuzz that has since been fixed.


text:
Q: Get request is not authorized when CSRF is disabled in Spring Security Spring Security basic authentication works if I don't add the following
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}

After I add this code piece a GET request without an Authorization header gets the response while I expect a response saying Unauthorized. Before adding this configuration GET response gets 401.
The only change is the above class; nothing else was changed.

A: Try to add .anyRequest().authenticated(), it means, all request must be authenticated. If you want to add an exemption add something like .antMatchers(HttpMethod.GET, "/", "/js/**", "/css/*", "/images/**").permitAll() this will not be authenticated.
Sample Code:
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
            .antMatchers(HttpMethod.GET, "/", "/js/**", "/css/*", "/images/**").permitAll()
            .anyRequest().authenticated();
    }
}


text:
Q: Does Alea GPU allow keeping LLVM IR code in the compilation chain? Nvidia does not allow the access to the generated LLVM IR in the compilation flow of a GPU kernel written in CUDA C/C++. I would like to know if this is possible if I use Alea GPU? In other words, does Alea GPU compilation procedure allows keeping the generated optimized/unoptimized LLVM IR code?

A: Yes, you are right, Nvidia doesnot show you the LLVM IR, you can only get the PTX code. While Alea GPU allows you to access LLVM IR in several ways:
Method 1
You use the workflow-based method to code a GPU module as a template, then you compile the template into an LLVM IR module, then you link the LLVM IRModule, optionally with some other IR modules, into a PTX module. Finally, you load the PTX module into the GPU worker. While you get the LLVM IRModule, you can call its method Dump() to print the IR code to console. Or you can get the bitcode as byte[].
I suggest you read more details here:

*

*Workflow-Based GPU Coding

*Workflows in Detail
The F# would be something like this:
let template = cuda {
    // define your kernel functions or other gpu moudle stuff
    let! kernel = <@ fun .... @> |> Compiler.DefineKernel

    // return an entry pointer for this module, something like the
    // main() function for a C program
    return Entry(fun program ->
        let worker = program.Worker
        let kernel = program.Apply kernel
        let main() = ....
        main ) }

let irModule = Compiler.Compile(template).IRModule
irModule.Dump() // dump the IR code

let ptxModule = Compiler.Link(irModule).PTXModule
ptxModule.Dump()

use program = worker.LoadProgram(ptxModule)
program.Run(...)

Method 2
If you are using Method-based or Instance-based way to code GPU module, you can add event handler for LLVM IR code generated and PTX generated though Alea.CUDA.Events. The code in F# will look like:
let desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
let (@@) a b = Path.Combine(a, b)
Events.Instance.IRCode.Add(fun ircode ->
    File.WriteAllBytes(desktopFolder @@ "module.ir", ircode))
Events.Instance.PTXCode.Add(fun ptxcode ->
    File.WriteAllBytes(desktopFolder @@ "module.ptx", ptxcode))

Extend GPU function by using LLVM code
Finally, there is an undocumented way, to let you directly operate on LLVM IR code to construct the functions. It is done by attribute that implemented some IR building interface. Here is a simple example, that accept the parameter, and print it (in compile-time), and return it back:
[<AttributeUsage(AttributeTargets.Method, AllowMultiple = false)>]
type IdentityAttribute() =
    inherit Attribute()

    interface ICustomCallBuilder with
        member this.Build(ctx, irObject, info, irParams) =
            match irObject, irParams with
            | None, irParam :: [] ->
                // the irParam is of type IRValue, which you
                // can get the LLVM native handle, by irParam.LLVM
                // Also, you can get the type by irParam.Type, which
                // is of type IRType, again, you can get LLVMTypeRef
                // handle by irParam.Type.LLVM
                // You can optionally construct LLVM instructions here.
                printfn "irParam: %A" irParam
                Some irParam
            | _ -> None

[<Identity>]
let identity(x:'T) : 'T = failwith "this is device function, better not call it from host"


text:
Q: Filtering with multiple tables using NOTORM PHP Two Tables defined as below:
----------   Table1 -----------
 id      type
 1        A
 2        B
 3        C

----------  Table2 ----------
id   type    sub_type
1     A      sub_type1
2     B      sub_type1
3     C      sub_type2
4     A      sub_type3
5     B      sub_type2

I want to find out all types which have subTypes sub_type1 or sub_type3, my code is as below:
$SubCategoryFilterArray = ['sub_type1','sub_type3'].

$query = $db->table1();
function SubCategoryFilteredQuery($SubCategoryFilterArray , $query){

  $filterSubArrayQuery = '';
  for($i = 0 ; $i < sizeof($SubCategoryFilterArray); $i++){
    if($i>0)
        $filterSubArrayQuery .= ' OR ' ;
    $filterSubArrayQuery .= $db->table2()->where(' sub_type = "' . $SubCategoryFilterArray[$i].'" ')->select('type');

  }

 //    $q = $db->table2()->where($p)->select('type');
 return $query->where('type', $filterSubArrayQuery);  // doubt
}

$finalQuery  = SubCategoryFilteredQuery($SubCategoryFilterArray , $query);
echo count($finalQuery);


text:
Q: add_menu_page the children get url encoded prefix Here i create the pages:
add_action("admin_menu", "wpa_create_plugin_pages");
function wpa_create_plugin_pages() {
    //Add submenu to Users
    $wpa_profile = "wpa_user_profile_settings";//parent slug

    $wpa_user_meta = get_user_meta(get_current_user_id());//don't mind this
    $wpa_role = $wpa_user_meta["wpa_toto_role"][0];//don't mind this

    //add_menu_page("אזור אישי", "אזור אישי", "read", $wpa_profile, "wpa_user_de", 'dashicons-admin-users');

    add_menu_page("משתמשים", "משתמשים", "read", $wpa_profile, "wpa_user_de", 'dashicons-admin-users');// the parent

    add_submenu_page($wpa_profile, "ערוך פרופיל אישי", "ערוך פרופיל אישי", "read", "wpa_edit_my_profile", "wpa_edit_my_profile");//children

    add_submenu_page($wpa_profile, "רשימת משתמשים", "רשימת משתמשים", "read", "wpa_user_list", "wpa_users_list");//children

    add_submenu_page($wpa_profile, "צור משתמש", "צור משתמש", "read", "wpa_user_profile", "wpa_user_profile");//children

    add_submenu_page($wpa_profile, "שלח נקודות", "שלח נקודות", "read", "wpa_user_send_points", "wpa_user_send_points");//children

    add_submenu_page($wpa_profile, "הוסף נקודות", "הוסף נקודות", "read", "wpa_create_points", "wpa_admin_create_points");//children
}

i used with get_current_screen() to output this data.

and here the issue:

as you can see inside WP_Screen Object the base and the id are %d7%9e%d7%a9%d7%aa%d7%9e%d7%a9%d7%99%d7%9d_page_wpa_user_list...

%d7%9e%d7%a9%d7%aa%d7%9e%d7%a9%d7%99%d7%9d = משתמשים(users in hebrew), it's url encodes the title of the parent page.

even the body class has -d7-9e-d7-a9-d7-aa-d7-9e-d7-a9-d7-99-d7-9d_page_wpa_user_list.
can i put a custom prefix for submenu page?


text:
Q: How can I see which options are available in a RegexOptions enum? How to use this function from powershell script to perform a case insensitive match with using the -cmatch operator:
static System.Text.RegularExpressions.Match Match(
     string input,
     string pattern,
     System.Text.RegularExpressions.RegexOptions options)

I'm thinking its something like this:
PS>  $input = "one two three"

PS>  $m = [regex]::Match($input, "one", ????)

The part I have a question about is the ???? above.
How do you see what System.Text.RegularExpressions.RegexOptions are available from powershell prompt and what's the syntax to use it in the code above?

A: The easy "cheat" way to see what options are available in an enum is to use tab completion within the PowerShell prompt or ISE. Start with [System.Text.RegularExpressions.RegexOptions]:: and then use CTRL SPACE (or TAB) to see the options.
The programmatic way, since RegexOptions is an enum, is this:
[System.Enum]::GetNames([System.Text.RegularExpressions.RegexOptions])

When you need to pass enum values in PowerShell, you can pass the long-form fully-qualified enum value (this is my preference):
[System.Text.RegularExpressions.RegexOptions]::IgnoreCase

Or you can pass the numeric value directly (1), or you can pass a string and it will be matched to the enum's text value 'IgnoreCase'.
For your actual question: using [regex]::Match() is already case sensitive. You can just pass [System.Text.RegularExpressions.RegexOptions]::None to your call (or 0, or 'None').
If you want it to be case-insensitive, then you use the IgnoreCase enum value as above.
Because this type of enum is a series of bit flags, you can combine them. To do that you use the -bor (bitwise or, or binary or) operator:
$myOptions = [System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor
        [System.Text.RegularExpressions.RegexOptions]::SingleLine -bor
        [System.Text.RegularExpressions.RegexOptions]::IgnorePatternWhitespace

But PowerShell's convenient coercion of strings to enums doesn't stop at single values. As mklement0 reminded me, you can comma separate the enum names within a string and PowerShell will still correctly parse it.
So you can use a string like 'IgnoreCase, SingleLine, IgnorePatternWhitespace' directly when you need to pass in RegexOptions. You can also pre-cast it:
$myOptions = 'IgnoreCase, SingleLine, IgnorePatternWhitespace' -as [System.Text.RegularExpressions.RegexOptions]
$myOptions = [System.Text.RegularExpressions.RegexOptions]'IgnoreCase, SingleLine, IgnorePatternWhitespace'

A: Simplifying braintist answer a little bit to use namespaces:
PS> using namespace System.Text.RegularExpressions

PS> [Enum]::GetNames([RegexOptions])
None
IgnoreCase
Multiline
ExplicitCapture
Compiled
Singleline
IgnorePatternWhitespace
RightToLeft
ECMAScript
CultureInvariant

PS>  $input = "one two three"

PS>  $m = [regex]::Match($input, "one", [RegexOptions]::IgnoreCase)