问:
webpack2 production build really slow "additional asset processing"
I have a large webpack build that almost hangs at 91% on an "additional asset processing" step that does not give me a lot more information.
Just this step consumes up to 4 minutes and seems to grow almost exponentially as we add modules to the build.
Is there a way to better understand what is done during this step and eventually optimize it?</p>

```<code>56205ms building modules
31ms sealing
0ms optimizing
0ms basic module optimization
15ms module optimization
0ms advanced module optimization
0ms basic chunk optimization
0ms chunk optimization
16ms advanced chunk optimization
14487ms building modules
0ms module and chunk tree optimization
31ms module reviving
0ms module order optimization
16ms module id optimization
0ms chunk reviving
16ms chunk order optimization
31ms chunk id optimization
140ms hashing
0ms module assets processing
265ms chunk assets processing
0ms additional chunk assets processing
0ms recording
206740ms additional asset processing
79781ms chunk asset optimization
1ms asset optimization
906ms emitting
</code>```

答:
In my case it was the webpack babili plugin (now babel-minify-webpack-plugin).
I've replace it with uglifyjs-webpack-plugin.

My config:

```<code>new UglifyJSPlugin({
  parallel: true,
  exclude: /\/node_modules/,
  uglifyOptions: {
    ecma: 8,
    mangle: true,
    compress: {
      sequences: true,
      dead_code: true,
      conditionals: true,
      booleans: true,
      unused: true,
      if_return: true,
      join_vars: true,
      drop_console: true
    },
    output: {
      comments: false,
      beautify: false
    }
  }
})
</code>```

Body:
I have a large webpack build that almost hangs at 91% on an "additional asset processing" step that does not give me a lot more information.
Just this step consumes up to 4 minutes and seems to grow almost exponentially as we add modules to the build.
Is there a way to better understand what is done during this step and eventually optimize it?

56205ms building modules
31ms sealing
0ms optimizing
0ms basic module optimization
15ms module optimization
0ms advanced module optimization
0ms basic chunk optimization
0ms chunk optimization
16ms advanced chunk optimization
14487ms building modules
0ms module and chunk tree optimization
31ms module reviving
0ms module order optimization
16ms module id optimization
0ms chunk reviving
16ms chunk order optimization
31ms chunk id optimization
140ms hashing
0ms module assets processing
265ms chunk assets processing
0ms additional chunk assets processing
0ms recording
206740ms additional asset processing
79781ms chunk asset optimization
1ms asset optimization
906ms emitting

Body:
In my case it was the webpack babili plugin (now babel-minify-webpack-plugin).
I've replace it with uglifyjs-webpack-plugin.

My config:

new UglifyJSPlugin({
  parallel: true,
  exclude: /\/node_modules/,
  uglifyOptions: {
    ecma: 8,
    mangle: true,
    compress: {
      sequences: true,
      dead_code: true,
      conditionals: true,
      booleans: true,
      unused: true,
      if_return: true,
      join_vars: true,
      drop_console: true
    },
    output: {
      comments: false,
      beautify: false
    }
  }
})


来源: stackexchange

问:
My sessions aren't working correctly
I have the following code

```<code>                   <?php
                    if($_SESSION['loggedin']){
                     echo '<li id="login-btn"><a href="logout.php">Logout</a></li>';
                   }
                   else{
                     echo '<li id="login-btn"><a href="login.php">Login</a></li>';
                   }
                   ?>
</code>```

This is inside of the HTML for my Navbar. I want it to where if they are logged in, it will show "Logout", if they aren't logged in, it'll show "Login", (self explanatory)

I have this in my login.php

```<code> $loggedin = "";
 $_SESSION['loggedin'] = true;
</code>```

For some reason, no matter what I do, my navbar keeps displaying "Login"? Help please, thank you!

答:
Session are global variables in php...

Session variables are not passed individually to each new page,
  instead they are retrieved from the session we open at the beginning
  of each page (session_start()).

if you want to access it on different page... you have to add

```<code><?php
         session_start();
?>
</code>```

at the begining .... even in your login.php page

ContentLicense: CC BY-SA 3.0

Title: My sessions aren't working correctly

Body:
I have the following code

                   <?php
                    if($_SESSION['loggedin']){
                     echo '
Logout
';
                   }
                   else{
                     echo '
Login
';
                   }
                   ?>

This is inside of the HTML for my Navbar. I want it to where if they are logged in, it will show "Logout", if they aren't logged in, it'll show "Login", (self explanatory)

I have this in my login.php

 $loggedin = "";
 $_SESSION['loggedin'] = true;

For some reason, no matter what I do, my navbar keeps displaying "Login"? Help please, thank you!

Body:
Session are global variables in php...

Session variables are not passed individually to each new page,
  instead they are retrieved from the session we open at the beginning
  of each page (session_start()).

if you want to access it on different page... you have to add

<?php
         session_start();
?>

at the begining .... even in your login.php page


问:
non-default access to an elevated process from a non-elevated process
sorry for bad english

Is it possible for a non-elevated process to get non-Default access rights(E.g. PROCESS_QUERY_INFORMATION) to an elevated process when they both have the same logon session id by changing the elevated-process security descriptor in the process explorer security tab?
i tried to change security descriptor of an elevated process  and selected  Full Access for the logon session SID.but still in the non-elevated process when i call OpenProcess() with the PROCESS_QUERY_INFORMATION access right  it returns ERROR_ACCESS_DENIED.

答:
begin from vista exist also Mandatory Integrity Control. elevated process have High Mandatory Label (S-1-16-12288) with SYSTEM_MANDATORY_LABEL_NO_WRITE_UP and SYSTEM_MANDATORY_LABEL_NO_READ_UP mask. from another side not elevated process have Medium Mandatory Level (S-1-16-8192) in token. so when it try open process with PROCESS_QUERY_INFORMATION which is part of generic read for process object - we usual fail do this from non-elevated process (medium level) for elevated process (high label and SYSTEM_MANDATORY_LABEL_NO_READ_UP).

for let open with PROCESS_QUERY_INFORMATION elevated process from not elevated - we need change elevated process mandatory label. or set it to medium or low, or remove SYSTEM_MANDATORY_LABEL_NO_READ_UP flag. last option - the best for my look

for remove SYSTEM_MANDATORY_LABEL_NO_READ_UP we can use next code:

```<code>// hProcess must have READ_CONTROL | WRITE_OWNER
ULONG RemoveNoReadUp(HANDLE hProcess = NtCurrentProcess())
{
    union {
        PVOID buf;
        PSECURITY_DESCRIPTOR pSD;
    };

    ULONG cb = 0, rcb = 128;

    static volatile UCHAR guz = 0;
    PVOID stack = alloca(guz);

    ULONG err;
    do
    {
        if (cb < rcb)
        {
            cb = RtlPointerToOffset(buf = alloca(rcb - cb), stack);
        }

        if (GetKernelObjectSecurity(hProcess, LABEL_SECURITY_INFORMATION, pSD, cb, &rcb))
        {
            BOOL bPresent, bDefault;
            PACL Acl;

            if (!GetSecurityDescriptorSacl(pSD, &bPresent, &Acl, &bDefault))
            {
                return GetLastError();
            }

            if (bPresent)
            {
                if (DWORD AceCount = Acl->AceCount)
                {
                    union {
                        PVOID pv;
                        PBYTE pb;
                        PACE_HEADER pAH;
                        PSYSTEM_MANDATORY_LABEL_ACE pMLA;
                    };

                    pv = Acl + 1;
                    do
                    {
                        if (pAH->AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE)
                        {
                            if (pMLA->Mask & SYSTEM_MANDATORY_LABEL_NO_READ_UP)
                            {
                                pMLA->Mask &= ~SYSTEM_MANDATORY_LABEL_NO_READ_UP;

                                return SetKernelObjectSecurity(hProcess, LABEL_SECURITY_INFORMATION, pSD)
                                    ? NOERROR : GetLastError();
                            }
                        }
                    } while (pb += pAH->AceSize, --AceCount);
                }
            }
            return ERROR_NOT_FOUND;
        }

    } while ((err = GetLastError()) == ERROR_INSUFFICIENT_BUFFER);

    return err;
}
</code>```

Body:
begin from vista exist also Mandatory Integrity Control. elevated process have High Mandatory Label (S-1-16-12288) with SYSTEM_MANDATORY_LABEL_NO_WRITE_UP and SYSTEM_MANDATORY_LABEL_NO_READ_UP mask. from another side not elevated process have Medium Mandatory Level (S-1-16-8192) in token. so when it try open process with PROCESS_QUERY_INFORMATION which is part of generic read for process object - we usual fail do this from non-elevated process (medium level) for elevated process (high label and SYSTEM_MANDATORY_LABEL_NO_READ_UP).

for let open with PROCESS_QUERY_INFORMATION elevated process from not elevated - we need change elevated process mandatory label. or set it to medium or low, or remove SYSTEM_MANDATORY_LABEL_NO_READ_UP flag. last option - the best for my look

for remove SYSTEM_MANDATORY_LABEL_NO_READ_UP we can use next code:

// hProcess must have READ_CONTROL | WRITE_OWNER
ULONG RemoveNoReadUp(HANDLE hProcess = NtCurrentProcess())
{
    union {
        PVOID buf;
        PSECURITY_DESCRIPTOR pSD;
    };

    ULONG cb = 0, rcb = 128;

    static volatile UCHAR guz = 0;
    PVOID stack = alloca(guz);

    ULONG err;
    do
    {
        if (cb < rcb)
        {
            cb = RtlPointerToOffset(buf = alloca(rcb - cb), stack);
        }

        if (GetKernelObjectSecurity(hProcess, LABEL_SECURITY_INFORMATION, pSD, cb, &rcb))
        {
            BOOL bPresent, bDefault;
            PACL Acl;

            if (!GetSecurityDescriptorSacl(pSD, &bPresent, &Acl, &bDefault))
            {
                return GetLastError();
            }

            if (bPresent)
            {
                if (DWORD AceCount = Acl->AceCount)
                {
                    union {
                        PVOID pv;
                        PBYTE pb;
                        PACE_HEADER pAH;
                        PSYSTEM_MANDATORY_LABEL_ACE pMLA;
                    };

                    pv = Acl + 1;
                    do
                    {
                        if (pAH->AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE)
                        {
                            if (pMLA->Mask & SYSTEM_MANDATORY_LABEL_NO_READ_UP)
                            {
                                pMLA->Mask &= ~SYSTEM_MANDATORY_LABEL_NO_READ_UP;

                                return SetKernelObjectSecurity(hProcess, LABEL_SECURITY_INFORMATION, pSD)
                                    ? NOERROR : GetLastError();
                            }
                        }
                    } while (pb += pAH->AceSize, --AceCount);
                }
            }
            return ERROR_NOT_FOUND;
        }

    } while ((err = GetLastError()) == ERROR_INSUFFICIENT_BUFFER);

    return err;
}


问:
Creating UCM Component baseline - only for modified components
we have a single application stream with multiple components (UCM Composite baseline) in ClearCase.

It has been split like

```<code>Alpha Primary Component
|
|___W (Sub component - A application)
|
|___X (Sub component - B application)
|
|___Y (Sub component - C application)
|
|___Z (Sub component - D application)
</code>```

We use to Make baseline for whole project/stream (Primary Component- XXX_application_.002) through GUI it internally reflects in the corresponding components too (XXX_applcation_.002.yyyy) where we have code changes but not on the other components.

Is there any way, if I add a baseline for Alpha (increment primary baseline) it need to increment the particular component also which have changes (For EX: I have code changes in B application (X component)?) in cleartool command?

I have tried the below command to Make Baseline which is working for single component application, but not for multiple component (composite baseline) application.

```<code>cleartool mkbl -nc -view $ucmintgview -all -incremental $incrematalBaseline
</code>```

Now I am looking for a command which makes baseline for Primary component which internally need to reflect in the modified application components also not the other components.

答:
Is there any way, if I add a baseline for Alpha (increment primary baseline) it needs to increment the particular component also which have changes (For Ex: I have code changes in B application (X component)?) in cleartool command.

If Alpha is a rootless component, with its dependency list composed of the four components A, B, C and D, then making a baseline on Alpha will be default generate a baseline only on the modified components of its dependency list.

See "About rooted and rootless ClearCase UCM components"

The baseline created on Alpha will be a composite baseline: see "To create a composite baseline".

So your mkbl command could target only one component -- Alpha --, which would in turn trigger baselines on the modified components of its dependency list.

A composite baseline is a baseline that selects baselines in other components. You can use a composite baseline to represent the entire project baseline; this is easier than keeping track of a set of baselines, one for each component.

```<code>cleartool mkbl -comp Alpha@/vobs/aPVob -view $ucmintgview aBaselineName
</code>```

(by default, a baseline is incremental)

Body:
we have a single application stream with multiple components (UCM Composite baseline) in ClearCase.

It has been split like

Alpha Primary Component
|
|___W (Sub component - A application)
|
|___X (Sub component - B application)
|
|___Y (Sub component - C application)
|
|___Z (Sub component - D application)

We use to Make baseline for whole project/stream (Primary Component- XXX_application_.002) through GUI it internally reflects in the corresponding components too (XXX_applcation_.002.yyyy) where we have code changes but not on the other components.

Is there any way, if I add a baseline for Alpha (increment primary baseline) it need to increment the particular component also which have changes (For EX: I have code changes in B application (X component)?) in cleartool command?

I have tried the below command to Make Baseline which is working for single component application, but not for multiple component (composite baseline) application.

cleartool mkbl -nc -view $ucmintgview -all -incremental $incrematalBaseline

Now I am looking for a command which makes baseline for Primary component which internally need to reflect in the modified application components also not the other components.

Body:
Is there any way, if I add a baseline for Alpha (increment primary baseline) it needs to increment the particular component also which have changes (For Ex: I have code changes in B application (X component)?) in cleartool command.

If Alpha is a rootless component, with its dependency list composed of the four components A, B, C and D, then making a baseline on Alpha will be default generate a baseline only on the modified components of its dependency list.

See "About rooted and rootless ClearCase UCM components"

The baseline created on Alpha will be a composite baseline: see "To create a composite baseline".

So your mkbl command could target only one component -- Alpha --, which would in turn trigger baselines on the modified components of its dependency list.

A composite baseline is a baseline that selects baselines in other components. You can use a composite baseline to represent the entire project baseline; this is easier than keeping track of a set of baselines, one for each component.

cleartool mkbl -comp Alpha@/vobs/aPVob -view $ucmintgview aBaselineName

(by default, a baseline is incremental)


问:
vhdl function is not being called
I have written a vhdl code something like this

```<code>entity myentity is
 port( number : in integer range 0 to 15; result : out integer);
 function myfunction(num: integer range 0 to 15) return integer is
 variable i: integer :=1;
 variable error1, error2, error, temp, concat: integer;
 variable res: integer;
 begin
  if (num<=1)then
   res := num;
  else
   while (2**i < num) loop
    i:=i+1;
   end loop;
   error2 := num-(2**i);
   error1 := num-(2**(i-1));
   if abs(error1)<error2 then
    error := error1;
   else error := error2;
   end if;
   if error=0 then
   res := to_integer(to_unsigned(num,8) sll i);
   else
   temp := num-error;
   concat := myfunction(temp);
   res :=to_integer(to_unsigned(temp,4) & to_unsigned(concat,i-1));
   end if;
  end if;
 return res;
end myfunction;
end myentity;

architecture Behavioral of myentity is
begin
 result<=myfunction(number);
end Behavioral;
</code>```

Function is recursive. The problem is, the architecture body is not calling the function. i.e., function lines are not being executed. When I compile the program, it shows no error. Any help?
I changed the example to the original code.

答:
With your new question code formatted for readability, report statements added for debugging and an added testbench to drive all possible integer values of number (0 to 15), creating a Minimal, Complete and Verifiable example:

```<code>library ieee;             -- CONTEXT CLAUSE ADDED
use ieee.numeric_std.all; -- unsigned, to_unsigned, to_integer, sll
 -- superfluous parentheses removed, indentation added  for clarity:
entity myentity is
    port (
        number:  in  integer range 0 to 15;
        result:  out integer
    );

    function myfunction (num: integer range 0 to 15) return integer is
        variable i: integer := 1;
        variable error1, error2, error, temp, concat: integer;
        variable res: integer;
    begin
        if num <= 1 then  -- CONDITION COULD BE num = 0
            res := num;
            report "num = " & integer'image(num);        -- ADDED REPORT
        else
            while 2 ** i < num loop
                i := i + 1;
            end loop;
            report "i = " & integer'image(i);            -- ADDED REPORT
            error2 := num - 2 ** i;
            report "error2 = " & integer'image(error2);  -- ADDED REPORT
            error1 := num - 2 ** (i - 1);
            report "error1 = " & integer'image(error1);  -- ADDED REPORT
            if abs error1 < error2 then
                error := error1;
            else
                error := error2;
            end if;
            report "error = " & integer'image(error);    -- ADDED REPORT
            if error = 0 then
                res := to_integer(to_unsigned(num, 8) sll i);
                report "res = " & integer'image(res);    -- ADDED REPORT
            else
                temp := num - error;
                report "temp = " & integer'image(temp);  -- ADDED REPORT
                concat := myfunction(temp);
                report "concat = " & integer'image(concat); -- ADDED REPORT
                res := to_integer(to_unsigned(temp, 4) &
                       to_unsigned(concat, i - 1) );
                report "res = " & integer'image(res);    -- ADDED REPORT
            end if;
        end if;
        return res;
    end myfunction;
end entity myentity;

architecture behavioral of myentity is
begin
    result <= myfunction(number);
end architecture behavioral;

entity myentity_tb is
end entity;

architecture foo of myentity_tb is
    signal result: integer;
    signal number: integer range 0 to 15;
begin

DUT:
    entity work.myentity
        port map (
            number => number,
            result => result
        );
STIMULI:
    process
    begin
        for i in 0 to 15 loop
            number <= i;
            report "number = " & integer'image(i);
            wait for 10 ns;
        end loop;
        wait;
    end process;
end architecture;
</code>```

Analyzing the code, elaborating and running the testbench produces with a VHDL implementation dependent report statement format:

```<code>myentity.vhdl:17:13:@0ms:(report note): num = 0
myentity.vhdl:74:13:@0ms:(report note): number = 0
myentity.vhdl:74:13:@10ns:(report note): number = 1
myentity.vhdl:17:13:@10ns:(report note): num = 1
myentity.vhdl:74:13:@20ns:(report note): number = 2
myentity.vhdl:22:13:@20ns:(report note): i = 1
myentity.vhdl:24:13:@20ns:(report note): error2 = 0
myentity.vhdl:26:13:@20ns:(report note): error1 = 1
myentity.vhdl:32:13:@20ns:(report note): error = 0
myentity.vhdl:35:17:@20ns:(report note): res = 4
myentity.vhdl:74:13:@30ns:(report note): number = 3
myentity.vhdl:22:13:@30ns:(report note): i = 2
myentity.vhdl:24:13:@30ns:(report note): error2 = -1
myentity.vhdl:26:13:@30ns:(report note): error1 = 1
myentity.vhdl:32:13:@30ns:(report note): error = -1
myentity.vhdl:38:17:@30ns:(report note): temp = 4
myentity.vhdl:22:13:@30ns:(report note): i = 2
myentity.vhdl:24:13:@30ns:(report note): error2 = 0
myentity.vhdl:26:13:@30ns:(report note): error1 = 2
myentity.vhdl:32:13:@30ns:(report note): error = 0
myentity.vhdl:35:17:@30ns:(report note): res = 16
myentity.vhdl:40:17:@30ns:(report note): concat = 16
../../src/ieee/numeric_std-body.v93:2151:7:@30ns:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated
myentity.vhdl:43:17:@30ns:(report note): res = 8
myentity.vhdl:74:13:@40ns:(report note): number = 4
myentity.vhdl:22:13:@40ns:(report note): i = 2
myentity.vhdl:24:13:@40ns:(report note): error2 = 0
myentity.vhdl:26:13:@40ns:(report note): error1 = 2
myentity.vhdl:32:13:@40ns:(report note): error = 0
myentity.vhdl:35:17:@40ns:(report note): res = 16
myentity.vhdl:74:13:@50ns:(report note): number = 5
myentity.vhdl:22:13:@50ns:(report note): i = 3
myentity.vhdl:24:13:@50ns:(report note): error2 = -3
myentity.vhdl:26:13:@50ns:(report note): error1 = 1
myentity.vhdl:32:13:@50ns:(report note): error = -3
myentity.vhdl:38:17:@50ns:(report note): temp = 8
myentity.vhdl:22:13:@50ns:(report note): i = 3
myentity.vhdl:24:13:@50ns:(report note): error2 = 0
myentity.vhdl:26:13:@50ns:(report note): error1 = 4
myentity.vhdl:32:13:@50ns:(report note): error = 0
myentity.vhdl:35:17:@50ns:(report note): res = 64
myentity.vhdl:40:17:@50ns:(report note): concat = 64
../../src/ieee/numeric_std-body.v93:2151:7:@50ns:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated
myentity.vhdl:43:17:@50ns:(report note): res = 32
myentity.vhdl:74:13:@60ns:(report note): number = 6
myentity.vhdl:22:13:@60ns:(report note): i = 3
myentity.vhdl:24:13:@60ns:(report note): error2 = -2
myentity.vhdl:26:13:@60ns:(report note): error1 = 2
myentity.vhdl:32:13:@60ns:(report note): error = -2
myentity.vhdl:38:17:@60ns:(report note): temp = 8
myentity.vhdl:22:13:@60ns:(report note): i = 3
myentity.vhdl:24:13:@60ns:(report note): error2 = 0
myentity.vhdl:26:13:@60ns:(report note): error1 = 4
myentity.vhdl:32:13:@60ns:(report note): error = 0
myentity.vhdl:35:17:@60ns:(report note): res = 64
myentity.vhdl:40:17:@60ns:(report note): concat = 64
../../src/ieee/numeric_std-body.v93:2151:7:@60ns:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated
myentity.vhdl:43:17:@60ns:(report note): res = 32
myentity.vhdl:74:13:@70ns:(report note): number = 7
myentity.vhdl:22:13:@70ns:(report note): i = 3
myentity.vhdl:24:13:@70ns:(report note): error2 = -1
myentity.vhdl:26:13:@70ns:(report note): error1 = 3
myentity.vhdl:32:13:@70ns:(report note): error = -1
myentity.vhdl:38:17:@70ns:(report note): temp = 8
myentity.vhdl:22:13:@70ns:(report note): i = 3
myentity.vhdl:24:13:@70ns:(report note): error2 = 0
myentity.vhdl:26:13:@70ns:(report note): error1 = 4
myentity.vhdl:32:13:@70ns:(report note): error = 0
myentity.vhdl:35:17:@70ns:(report note): res = 64
myentity.vhdl:40:17:@70ns:(report note): concat = 64
../../src/ieee/numeric_std-body.v93:2151:7:@70ns:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated
myentity.vhdl:43:17:@70ns:(report note): res = 32
myentity.vhdl:74:13:@80ns:(report note): number = 8
myentity.vhdl:22:13:@80ns:(report note): i = 3
myentity.vhdl:24:13:@80ns:(report note): error2 = 0
myentity.vhdl:26:13:@80ns:(report note): error1 = 4
myentity.vhdl:32:13:@80ns:(report note): error = 0
myentity.vhdl:35:17:@80ns:(report note): res = 64
myentity.vhdl:74:13:@90ns:(report note): number = 9
myentity.vhdl:22:13:@90ns:(report note): i = 4
myentity.vhdl:24:13:@90ns:(report note): error2 = -7
myentity.vhdl:26:13:@90ns:(report note): error1 = 1
myentity.vhdl:32:13:@90ns:(report note): error = -7
myentity.vhdl:38:17:@90ns:(report note): temp = 16
./myentity_tb:error: bound check failure at myentity.vhdl:39
./myentity_tb:error: simulation failed
</code>```

Where we can see for a number value of 0 the function returns 0 which is assigned to result.  That explains why without driving different values (1 through 15) on number through stimuli (here a testbench, a higher level in the design hierarchy) why result is 0 and produces no error. (Note without an assignment to result it's value would have been INTEGER'LOW the minimum value for that type, result has no subtype constraint and inherits it's subtype from the type mark in the port declaration for result).

There are two classes of messages causing concern in the output for number values 1 through 15.

The first is the report message from package numeric_std telling you you clipped left elements from the binary number eventually converted to integer and assigned to res. This represents inaccuracy in your algorithm that needs to be addressed. You can note that res (assigned to result in the concurrent signal assignment statement) is 64 when that occurs.

The second is the error message when number was assigned a value of 9 and the value passed to the recursive call to myfunction was outside it's parameter num's range (0 to 15, the value 16 for variable temp). A bounds violation error is sufficient to cause simulation to cease, the integrity of the simulation is compromised. (And this is what strong typing does for you, the subtype of parameter num should have been chosen for a purpose in implementing myfunction).

You can easily remove every report statement added for debugging when your algorithm functions satisfactorily after which you can test again.

Note the values of number can be distinguished by what time they occur at during simulation.

This answer shows why your code reports no error as well as showing how to tell what it's doing to allow debugging for other values of number.

As we can see my the presence of the very first report statement the function myfunction is getting called. Also if result were not assigned it's default value would be a negative number.

Title: vhdl function is not being called

Body:
I have written a vhdl code something like this

entity myentity is
 port( number : in integer range 0 to 15; result : out integer);
 function myfunction(num: integer range 0 to 15) return integer is
 variable i: integer :=1;
 variable error1, error2, error, temp, concat: integer;
 variable res: integer;
 begin
  if (num<=1)then
   res := num;
  else
   while (2**i < num) loop
    i:=i+1;
   end loop;
   error2 := num-(2**i);
   error1 := num-(2**(i-1));
   if abs(error1)<error2 then
    error := error1;
   else error := error2;
   end if;
   if error=0 then
   res := to_integer(to_unsigned(num,8) sll i);
   else
   temp := num-error;
   concat := myfunction(temp);
   res :=to_integer(to_unsigned(temp,4) & to_unsigned(concat,i-1));
   end if;
  end if;
 return res;
end myfunction;
end myentity;

architecture Behavioral of myentity is
begin
 result<=myfunction(number);
end Behavioral;

Function is recursive. The problem is, the architecture body is not calling the function. i.e., function lines are not being executed. When I compile the program, it shows no error. Any help?
I changed the example to the original code.

Body:
With your new question code formatted for readability, report statements added for debugging and an added testbench to drive all possible integer values of number (0 to 15), creating a Minimal, Complete and Verifiable example:

library ieee;             -- CONTEXT CLAUSE ADDED
use ieee.numeric_std.all; -- unsigned, to_unsigned, to_integer, sll
 -- superfluous parentheses removed, indentation added  for clarity:
entity myentity is
    port (
        number:  in  integer range 0 to 15;
        result:  out integer
    );

    function myfunction (num: integer range 0 to 15) return integer is
        variable i: integer := 1;
        variable error1, error2, error, temp, concat: integer;
        variable res: integer;
    begin
        if num <= 1 then  -- CONDITION COULD BE num = 0
            res := num;
            report "num = " & integer'image(num);        -- ADDED REPORT
        else
            while 2 ** i < num loop
                i := i + 1;
            end loop;
            report "i = " & integer'image(i);            -- ADDED REPORT
            error2 := num - 2 ** i;
            report "error2 = " & integer'image(error2);  -- ADDED REPORT
            error1 := num - 2 ** (i - 1);
            report "error1 = " & integer'image(error1);  -- ADDED REPORT
            if abs error1 < error2 then
                error := error1;
            else
                error := error2;
            end if;
            report "error = " & integer'image(error);    -- ADDED REPORT
            if error = 0 then
                res := to_integer(to_unsigned(num, 8) sll i);
                report "res = " & integer'image(res);    -- ADDED REPORT
            else
                temp := num - error;
                report "temp = " & integer'image(temp);  -- ADDED REPORT
                concat := myfunction(temp);
                report "concat = " & integer'image(concat); -- ADDED REPORT
                res := to_integer(to_unsigned(temp, 4) &
                       to_unsigned(concat, i - 1) );
                report "res = " & integer'image(res);    -- ADDED REPORT
            end if;
        end if;
        return res;
    end myfunction;
end entity myentity;

architecture behavioral of myentity is
begin
    result <= myfunction(number);
end architecture behavioral;

entity myentity_tb is
end entity;

architecture foo of myentity_tb is
    signal result: integer;
    signal number: integer range 0 to 15;
begin

DUT:
    entity work.myentity
        port map (
            number => number,
            result => result
        );
STIMULI:
    process
    begin
        for i in 0 to 15 loop
            number <= i;
            report "number = " & integer'image(i);
            wait for 10 ns;
        end loop;
        wait;
    end process;
end architecture;

Analyzing the code, elaborating and running the testbench produces with a VHDL implementation dependent report statement format:

myentity.vhdl:17:13:@0ms:(report note): num = 0
myentity.vhdl:74:13:@0ms:(report note): number = 0
myentity.vhdl:74:13:@10ns:(report note): number = 1
myentity.vhdl:17:13:@10ns:(report note): num = 1
myentity.vhdl:74:13:@20ns:(report note): number = 2
myentity.vhdl:22:13:@20ns:(report note): i = 1
myentity.vhdl:24:13:@20ns:(report note): error2 = 0
myentity.vhdl:26:13:@20ns:(report note): error1 = 1
myentity.vhdl:32:13:@20ns:(report note): error = 0
myentity.vhdl:35:17:@20ns:(report note): res = 4
myentity.vhdl:74:13:@30ns:(report note): number = 3
myentity.vhdl:22:13:@30ns:(report note): i = 2
myentity.vhdl:24:13:@30ns:(report note): error2 = -1
myentity.vhdl:26:13:@30ns:(report note): error1 = 1
myentity.vhdl:32:13:@30ns:(report note): error = -1
myentity.vhdl:38:17:@30ns:(report note): temp = 4
myentity.vhdl:22:13:@30ns:(report note): i = 2
myentity.vhdl:24:13:@30ns:(report note): error2 = 0
myentity.vhdl:26:13:@30ns:(report note): error1 = 2
myentity.vhdl:32:13:@30ns:(report note): error = 0
myentity.vhdl:35:17:@30ns:(report note): res = 16
myentity.vhdl:40:17:@30ns:(report note): concat = 16
../../src/ieee/numeric_std-body.v93:2151:7:@30ns:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated
myentity.vhdl:43:17:@30ns:(report note): res = 8
myentity.vhdl:74:13:@40ns:(report note): number = 4
myentity.vhdl:22:13:@40ns:(report note): i = 2
myentity.vhdl:24:13:@40ns:(report note): error2 = 0
myentity.vhdl:26:13:@40ns:(report note): error1 = 2
myentity.vhdl:32:13:@40ns:(report note): error = 0
myentity.vhdl:35:17:@40ns:(report note): res = 16
myentity.vhdl:74:13:@50ns:(report note): number = 5
myentity.vhdl:22:13:@50ns:(report note): i = 3
myentity.vhdl:24:13:@50ns:(report note): error2 = -3
myentity.vhdl:26:13:@50ns:(report note): error1 = 1
myentity.vhdl:32:13:@50ns:(report note): error = -3
myentity.vhdl:38:17:@50ns:(report note): temp = 8
myentity.vhdl:22:13:@50ns:(report note): i = 3
myentity.vhdl:24:13:@50ns:(report note): error2 = 0
myentity.vhdl:26:13:@50ns:(report note): error1 = 4
myentity.vhdl:32:13:@50ns:(report note): error = 0
myentity.vhdl:35:17:@50ns:(report note): res = 64
myentity.vhdl:40:17:@50ns:(report note): concat = 64
../../src/ieee/numeric_std-body.v93:2151:7:@50ns:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated
myentity.vhdl:43:17:@50ns:(report note): res = 32
myentity.vhdl:74:13:@60ns:(report note): number = 6
myentity.vhdl:22:13:@60ns:(report note): i = 3
myentity.vhdl:24:13:@60ns:(report note): error2 = -2
myentity.vhdl:26:13:@60ns:(report note): error1 = 2
myentity.vhdl:32:13:@60ns:(report note): error = -2
myentity.vhdl:38:17:@60ns:(report note): temp = 8
myentity.vhdl:22:13:@60ns:(report note): i = 3
myentity.vhdl:24:13:@60ns:(report note): error2 = 0
myentity.vhdl:26:13:@60ns:(report note): error1 = 4
myentity.vhdl:32:13:@60ns:(report note): error = 0
myentity.vhdl:35:17:@60ns:(report note): res = 64
myentity.vhdl:40:17:@60ns:(report note): concat = 64
../../src/ieee/numeric_std-body.v93:2151:7:@60ns:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated
myentity.vhdl:43:17:@60ns:(report note): res = 32
myentity.vhdl:74:13:@70ns:(report note): number = 7
myentity.vhdl:22:13:@70ns:(report note): i = 3
myentity.vhdl:24:13:@70ns:(report note): error2 = -1
myentity.vhdl:26:13:@70ns:(report note): error1 = 3
myentity.vhdl:32:13:@70ns:(report note): error = -1
myentity.vhdl:38:17:@70ns:(report note): temp = 8
myentity.vhdl:22:13:@70ns:(report note): i = 3
myentity.vhdl:24:13:@70ns:(report note): error2 = 0
myentity.vhdl:26:13:@70ns:(report note): error1 = 4
myentity.vhdl:32:13:@70ns:(report note): error = 0
myentity.vhdl:35:17:@70ns:(report note): res = 64
myentity.vhdl:40:17:@70ns:(report note): concat = 64
../../src/ieee/numeric_std-body.v93:2151:7:@70ns:(assertion warning): NUMERIC_STD.TO_UNSIGNED: vector truncated
myentity.vhdl:43:17:@70ns:(report note): res = 32
myentity.vhdl:74:13:@80ns:(report note): number = 8
myentity.vhdl:22:13:@80ns:(report note): i = 3
myentity.vhdl:24:13:@80ns:(report note): error2 = 0
myentity.vhdl:26:13:@80ns:(report note): error1 = 4
myentity.vhdl:32:13:@80ns:(report note): error = 0
myentity.vhdl:35:17:@80ns:(report note): res = 64
myentity.vhdl:74:13:@90ns:(report note): number = 9
myentity.vhdl:22:13:@90ns:(report note): i = 4
myentity.vhdl:24:13:@90ns:(report note): error2 = -7
myentity.vhdl:26:13:@90ns:(report note): error1 = 1
myentity.vhdl:32:13:@90ns:(report note): error = -7
myentity.vhdl:38:17:@90ns:(report note): temp = 16
./myentity_tb:error: bound check failure at myentity.vhdl:39
./myentity_tb:error: simulation failed

Where we can see for a number value of 0 the function returns 0 which is assigned to result.  That explains why without driving different values (1 through 15) on number through stimuli (here a testbench, a higher level in the design hierarchy) why result is 0 and produces no error. (Note without an assignment to result it's value would have been INTEGER'LOW the minimum value for that type, result has no subtype constraint and inherits it's subtype from the type mark in the port declaration for result).

There are two classes of messages causing concern in the output for number values 1 through 15.

The first is the report message from package numeric_std telling you you clipped left elements from the binary number eventually converted to integer and assigned to res. This represents inaccuracy in your algorithm that needs to be addressed. You can note that res (assigned to result in the concurrent signal assignment statement) is 64 when that occurs.

The second is the error message when number was assigned a value of 9 and the value passed to the recursive call to myfunction was outside it's parameter num's range (0 to 15, the value 16 for variable temp). A bounds violation error is sufficient to cause simulation to cease, the integrity of the simulation is compromised. (And this is what strong typing does for you, the subtype of parameter num should have been chosen for a purpose in implementing myfunction).

You can easily remove every report statement added for debugging when your algorithm functions satisfactorily after which you can test again.

Note the values of number can be distinguished by what time they occur at during simulation.

This answer shows why your code reports no error as well as showing how to tell what it's doing to allow debugging for other values of number.

As we can see my the presence of the very first report statement the function myfunction is getting called. Also if result were not assigned it's default value would be a negative number.


问:
Where do I put the missing "}"?
I'm am trying to add some structured data, but I keep getting an error in Google's SDTT:

Missing '}' or object member name.

JSON-LD:

```

Where am I going wrong?

答:
In objects, the , separates "a value from a following name" (RFC 4627, section 2.2).

If no name follows, the comma must not be used.

So instead of

{
  "name": "…",
  "description": "…",
}
```
<p>it has to be</p>
<pre class="lang-json prettyprint-override"><code>{
  "name": "…",
  "description": "…"
}
</code>```

(For your example, it means that the last two commas have to be removed.)

Title: Where do I put the missing "}"?

Body:
I'm am trying to add some structured data, but I keep getting an error in Google's SDTT:

Missing '}' or object member name.

JSON-LD:

Where am I going wrong?

Body:
In objects, the , separates "a value from a following name" (RFC 4627, section 2.2).

If no name follows, the comma must not be used.

So instead of

{
  "name": "…",
  "description": "…",
}

it has to be

{
  "name": "…",
  "description": "…"
}

(For your example, it means that the last two commas have to be removed.)


问:
how to call another form within first in qt
I've qt 5.3.1 & mysql client in centos 6.6 (x86) in one VM and second VM contains server Mysql.
in qt i want to call second form ( "tabledispalaydialog.ui" ) from first form ("myappmanwindow.ui")

"tabledispalaydialog.ui" file contains one tableviewLoginForm ( tableview object from components of Qt creator design page)

the first form is this - login form(mainWindow):

second form to display query result :-
tableview in second form

now i want to call form "tabledispalaydialog.ui" in signal "click" of login button in form "myappmanwindow.ui".

And also i want to show "login table" from mysql server in second form, query
 passed  as argument from first form.

finally how to connect(this, SIGNAL(otherform(QString Query)),this, SLOT(callThisForm(QString Query)));

myappmainwindow.h :-

  #ifndef MYAPPMAINWINDOW_H
  #define MYAPPMAINWINDOW_H

  #include <QMainWindow>
  #include "tabledispalaydialog.h"
  #include <QSqlQueryModel>
  #include <QSqlDatabase>
  #include <QSqlDriver>
  #include <QMessageBox>
  #include <QSqlQuery>
  #include <QSqlRecord>
  #include <QMessageBox>

  namespace Ui {
  class MyappMainWindow;
  }

  class TableDispalayDialog;

  class MyappMainWindow : public QMainWindow
  {
      Q_OBJECT

  public:
      explicit MyappMainWindow(QWidget *parent = 0);
      ~MyappMainWindow();

  private:
      Ui::MyappMainWindow *ui;

      TableDispalayDialog *tableDisplayform;
      QSqlDatabase *db;

  signals:
      void otherform(QString Query);

  private slots:
      void on_pushButtonLogin_clicked();
  };

  #endif // MYAPPMAINWINDOW_H
```

<h2>tabledispalaydoialog.h:-</h2>

<pre class="lang-c++ prettyprint-override"><code>   #ifndef TABLEDISPALAYDIALOG_H
   #define TABLEDISPALAYDIALOG_H

   #include <QDialog>
   #include <QSqlQueryModel>

   namespace Ui {
   class TableDispalayDialog;
   }

   class TableDispalayDialog : public QDialog
   {
       Q_OBJECT

   public:
       explicit TableDispalayDialog(QWidget *parent = 0);
       ~TableDispalayDialog();

   private:
       Ui::TableDispalayDialog *ui;

       QSqlQueryModel *model;

   public slots:

       void callThisForm(QString Query);
   };

   #endif        // TABLEDISPALAYDIALOG_H
</code>```

myappmainwindow.cpp :-

  #include "myappmainwindow.h"
  #include "ui_myappmainwindow.h"

  MyappMainWindow::MyappMainWindow(QWidget *parent) :
      QMainWindow(parent),
      ui(new Ui::MyappMainWindow)
        {
            ui->setupUi(this);

            TableDispalayDialog *tableDisplayform = new         ableDispalayDialog();
      //connect(this, SIGNAL(otherform(QString Query)),tableDisplayform, SLOT(callThisForm(QString Query)));
      //connect(this, SIGNAL(otherform(QString Query)),, SLOT(callThisForm(QString Query)));

       db = new QSqlDatabase(QSqlDatabase::addDatabase("QMYSQL"));
       db->setDatabaseName("test");
       db->setHostName("oracle");
       db->setPort(3306);
       db->setUserName("rahul");
       db->setPassword("rahul");
  }

  MyappMainWindow::~MyappMainWindow()
  {
      db->close();
      delete ui;
  }

  void MyappMainWindow::on_pushButtonLogin_clicked()
  {
      QString susername = ui->lineEditUser->text();
      QString spassword = ui->lineEditPassword->text();
      QString strquery;

          strquery = "select * from tablelogin where user = \"" + susername.trimmed() +"\" " +" and password = \""+
                              spassword.trimmed()+ "\";";

      QMessageBox::information(this, "login button", strquery);
      }
```

<h2>and at last table tabledispalaydialog.cpp :-</h2>

<pre class="lang-c++ prettyprint-override"><code>   #include "tabledispalaydialog.h"
   #include "ui_tabledispalaydialog.h"

   TableDispalayDialog::TableDispalayDialog(QWidget *parent) :
       QDialog(parent),
       ui(new Ui::TableDispalayDialog)
   {
       ui->setupUi(this);
   }

   TableDispalayDialog::~TableDispalayDialog()
   {
       delete ui;
   }

   void  TableDispalayDialog::callThisForm(QString Query)
   {
       this->model = new QSqlQueryModel();
       this->model->setQuery(Query);
       this->ui->tableViewLoginForm->setModel(model);
       this->show();
       this->setModal(true);
       this->exec();
   }
</code>```

how can I call second form (TableDispalayDialog ) within first form(myappmanwindow) in button "login" click signal, and also having login table(from mysql) details in form TableDispalayDialog's tableview component.

答:
try using QSignalMapper http://doc.qt.io/qt-5/qsignalmapper.html
to emit signals like clicked with a QString Parameter
or you can simply create a slot to call the form and pass the string as a parameter to the form constructor
or create a top level widget that handles all other widgets</p>

Body:
I've qt 5.3.1 & mysql client in centos 6.6 (x86) in one VM and second VM contains server Mysql.
in qt i want to call second form ( "tabledispalaydialog.ui" ) from first form ("myappmanwindow.ui")

"tabledispalaydialog.ui" file contains one tableviewLoginForm ( tableview object from components of Qt creator design page)

the first form is this - login form(mainWindow):

second form to display query result :-
tableview in second form

now i want to call form "tabledispalaydialog.ui" in signal "click" of login button in form "myappmanwindow.ui".

And also i want to show "login table" from mysql server in second form, query
 passed  as argument from first form.

finally how to connect(this, SIGNAL(otherform(QString Query)),this, SLOT(callThisForm(QString Query)));

myappmainwindow.h :-

  #ifndef MYAPPMAINWINDOW_H
  #define MYAPPMAINWINDOW_H

  #include <QMainWindow>
  #include "tabledispalaydialog.h"
  #include <QSqlQueryModel>
  #include <QSqlDatabase>
  #include <QSqlDriver>
  #include <QMessageBox>
  #include <QSqlQuery>
  #include <QSqlRecord>
  #include <QMessageBox>

  namespace Ui {
  class MyappMainWindow;
  }

  class TableDispalayDialog;

  class MyappMainWindow : public QMainWindow
  {
      Q_OBJECT

  public:
      explicit MyappMainWindow(QWidget *parent = 0);
      ~MyappMainWindow();

  private:
      Ui::MyappMainWindow *ui;

      TableDispalayDialog *tableDisplayform;
      QSqlDatabase *db;

  signals:
      void otherform(QString Query);

  private slots:
      void on_pushButtonLogin_clicked();
  };

  #endif // MYAPPMAINWINDOW_H

tabledispalaydoialog.h:-

   #ifndef TABLEDISPALAYDIALOG_H
   #define TABLEDISPALAYDIALOG_H

   #include <QDialog>
   #include <QSqlQueryModel>

   namespace Ui {
   class TableDispalayDialog;
   }

   class TableDispalayDialog : public QDialog
   {
       Q_OBJECT

   public:
       explicit TableDispalayDialog(QWidget *parent = 0);
       ~TableDispalayDialog();

   private:
       Ui::TableDispalayDialog *ui;

       QSqlQueryModel *model;

   public slots:

       void callThisForm(QString Query);
   };

   #endif        // TABLEDISPALAYDIALOG_H

myappmainwindow.cpp :-

  #include "myappmainwindow.h"
  #include "ui_myappmainwindow.h"

  MyappMainWindow::MyappMainWindow(QWidget *parent) :
      QMainWindow(parent),
      ui(new Ui::MyappMainWindow)
        {
            ui->setupUi(this);

            TableDispalayDialog *tableDisplayform = new         ableDispalayDialog();
      //connect(this, SIGNAL(otherform(QString Query)),tableDisplayform, SLOT(callThisForm(QString Query)));
      //connect(this, SIGNAL(otherform(QString Query)),, SLOT(callThisForm(QString Query)));

       db = new QSqlDatabase(QSqlDatabase::addDatabase("QMYSQL"));
       db->setDatabaseName("test");
       db->setHostName("oracle");
       db->setPort(3306);
       db->setUserName("rahul");
       db->setPassword("rahul");
  }

  MyappMainWindow::~MyappMainWindow()
  {
      db->close();
      delete ui;
  }

  void MyappMainWindow::on_pushButtonLogin_clicked()
  {
      QString susername = ui->lineEditUser->text();
      QString spassword = ui->lineEditPassword->text();
      QString strquery;

          strquery = "select * from tablelogin where user = \"" + susername.trimmed() +"\" " +" and password = \""+
                              spassword.trimmed()+ "\";";

      QMessageBox::information(this, "login button", strquery);
      }

and at last table tabledispalaydialog.cpp :-

   #include "tabledispalaydialog.h"
   #include "ui_tabledispalaydialog.h"

   TableDispalayDialog::TableDispalayDialog(QWidget *parent) :
       QDialog(parent),
       ui(new Ui::TableDispalayDialog)
   {
       ui->setupUi(this);
   }

   TableDispalayDialog::~TableDispalayDialog()
   {
       delete ui;
   }

   void  TableDispalayDialog::callThisForm(QString Query)
   {
       this->model = new QSqlQueryModel();
       this->model->setQuery(Query);
       this->ui->tableViewLoginForm->setModel(model);
       this->show();
       this->setModal(true);
       this->exec();
   }

how can I call second form (TableDispalayDialog ) within first form(myappmanwindow) in button "login" click signal, and also having login table(from mysql) details in form TableDispalayDialog's tableview component.


问:
build/install/<project>-shadow directory -- what is it?
What is build/install/gradleHelloWorld-shadow?  What should or shouldn't be in that directory?

simplest possible "hello world" fails to build:

```<code>thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean runShadow

> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
 - No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':installShadowDist'.
> The specified installation directory '/home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow' is neither empty nor does it contain an installation for 'gradleHelloWorld'.
  If you really want to install to this directory, delete it and run the install task again.
  Alternatively, choose a different installation directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
5 actionable tasks: 5 executed

Publishing build scan...
https://gradle.com/s/t7jbmhjz23giw

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
</code>```

build file:

```<code>plugins {
    id 'com.gradle.build-scan' version '1.8'
    id 'java'
    id 'application'
    id 'com.github.johnrengelman.shadow' version '2.0.1'
}

buildScan {
    licenseAgreementUrl = 'https://gradle.com/terms-of-service'
    licenseAgree = 'yes'
    publishAlways()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

mainClassName = 'net.bounceme.dur.gradle.hello.App'

shadowJar {
    baseName = 'greeter'
    classifier = null
    version = null
}

repositories {
    jcenter()
}

configurations {
    provided
}

dependencies {
}
</code>```

project after aborted runShadow:

```<code>thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ tree
.
├── build
│   ├── classes
│   │   └── java
│   │       └── main
│   │           └── net
│   │               └── bounceme
│   │                   └── dur
│   │                       └── gradle
│   │                           └── hello
│   │                               └── App.class
│   ├── install
│   │   └── gradleHelloWorld-shadow
│   ├── libs
│   │   └── greeter.jar
│   ├── scriptsShadow
│   │   ├── gradleHelloWorld
│   │   └── gradleHelloWorld.bat
│   └── tmp
│       ├── compileJava
│       └── shadowJar
│           └── MANIFEST.MF
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   └── java
    │       ├── dur
    │       └── net
    │           └── bounceme
    │               └── dur
    │                   └── gradle
    │                       └── hello
    │                           └── App.java
    └── test
        └── java

29 directories, 12 files
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
</code>```

the /home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow directory at issue is removed by clean, establishing that gradle is building this directory.

Just upgraded gradle:

```<code>thufir@dur:~$
thufir@dur:~$ sdk ls gradle
==== INTERNET NOT REACHABLE! ===================================================

 Some functionality is disabled or only partially available.
 If this persists, please enable the offline mode:

   $ sdk offline

================================================================================

--------------------------------------------------------------------------------
Offline: only showing installed gradle versions
--------------------------------------------------------------------------------
 > 4.3.1
 * 4.2.1
--------------------------------------------------------------------------------
* - installed
> - currently in use
--------------------------------------------------------------------------------
thufir@dur:~$
</code>```

(The wi-fi can be a bit flaky.)

答:
better solution, still a work-around.  Switching back to gradle 4.2.1 from 4.3.1 works:

```<code>thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ sdk use gradle 4.3.1

Using gradle version 4.3.1 in this shell.
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean runShadow

> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
 - No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':installShadowDist'.
> The specified installation directory '/home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow' is neither empty nor does it contain an installation for 'gradleHelloWorld'.
  If you really want to install to this directory, delete it and run the install task again.
  Alternatively, choose a different installation directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
5 actionable tasks: 5 executed
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ sdk use gradle 4.2.1

Using gradle version 4.2.1 in this shell.
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean runShadow
Starting a Gradle Daemon (subsequent builds will be faster)

> Task :shadowJar
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :runShadow
Nov 13, 2017 12:02:51 PM net.bounceme.dur.gradle.hello.App run
INFO: helloooo

BUILD SUCCESSFUL in 12s
6 actionable tasks: 6 executed
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
</code>```

Is this a bug?

Body:
What is build/install/gradleHelloWorld-shadow?  What should or shouldn't be in that directory?

simplest possible "hello world" fails to build:

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean runShadow

> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
 - No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':installShadowDist'.
> The specified installation directory '/home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow' is neither empty nor does it contain an installation for 'gradleHelloWorld'.
  If you really want to install to this directory, delete it and run the install task again.
  Alternatively, choose a different installation directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
5 actionable tasks: 5 executed

Publishing build scan...
https://gradle.com/s/t7jbmhjz23giw

thufir@dur:~/NetBeansProjects/gradleHelloWorld$

build file:

plugins {
    id 'com.gradle.build-scan' version '1.8'
    id 'java'
    id 'application'
    id 'com.github.johnrengelman.shadow' version '2.0.1'
}

buildScan {
    licenseAgreementUrl = 'https://gradle.com/terms-of-service'
    licenseAgree = 'yes'
    publishAlways()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

mainClassName = 'net.bounceme.dur.gradle.hello.App'

shadowJar {
    baseName = 'greeter'
    classifier = null
    version = null
}

repositories {
    jcenter()
}

configurations {
    provided
}

dependencies {
}

project after aborted runShadow:

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ tree
.
├── build
│   ├── classes
│   │   └── java
│   │       └── main
│   │           └── net
│   │               └── bounceme
│   │                   └── dur
│   │                       └── gradle
│   │                           └── hello
│   │                               └── App.class
│   ├── install
│   │   └── gradleHelloWorld-shadow
│   ├── libs
│   │   └── greeter.jar
│   ├── scriptsShadow
│   │   ├── gradleHelloWorld
│   │   └── gradleHelloWorld.bat
│   └── tmp
│       ├── compileJava
│       └── shadowJar
│           └── MANIFEST.MF
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   └── java
    │       ├── dur
    │       └── net
    │           └── bounceme
    │               └── dur
    │                   └── gradle
    │                       └── hello
    │                           └── App.java
    └── test
        └── java

29 directories, 12 files
thufir@dur:~/NetBeansProjects/gradleHelloWorld$

the /home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow directory at issue is removed by clean, establishing that gradle is building this directory.

Just upgraded gradle:

thufir@dur:~$
thufir@dur:~$ sdk ls gradle
==== INTERNET NOT REACHABLE! ===================================================

 Some functionality is disabled or only partially available.
 If this persists, please enable the offline mode:

   $ sdk offline

================================================================================

--------------------------------------------------------------------------------
Offline: only showing installed gradle versions
--------------------------------------------------------------------------------
 > 4.3.1
 * 4.2.1
--------------------------------------------------------------------------------
* - installed
> - currently in use
--------------------------------------------------------------------------------
thufir@dur:~$

(The wi-fi can be a bit flaky.)

Body:
better solution, still a work-around.  Switching back to gradle 4.2.1 from 4.3.1 works:

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ sdk use gradle 4.3.1

Using gradle version 4.3.1 in this shell.
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean runShadow

> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
 - No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':installShadowDist'.
> The specified installation directory '/home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow' is neither empty nor does it contain an installation for 'gradleHelloWorld'.
  If you really want to install to this directory, delete it and run the install task again.
  Alternatively, choose a different installation directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
5 actionable tasks: 5 executed
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ sdk use gradle 4.2.1

Using gradle version 4.2.1 in this shell.
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean runShadow
Starting a Gradle Daemon (subsequent builds will be faster)

> Task :shadowJar
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :runShadow
Nov 13, 2017 12:02:51 PM net.bounceme.dur.gradle.hello.App run
INFO: helloooo

BUILD SUCCESSFUL in 12s
6 actionable tasks: 6 executed
thufir@dur:~/NetBeansProjects/gradleHelloWorld$

Is this a bug?


问:
Fetching data from database into checkbox
I am trying to edit my form. Currently, i am able to retrieve data into my input textbox but not the checkbox. Now when, i am inserting data, i check the items that i want to insert, get the ids and save into my database.

Now when i want to edit, i want to retrieve the items that i previously selected (the checkbox of which i selected should be checked ).

In my Json below, i am able to display the id of the food that i selected when i was storing. How can i fetch that into my checkbox back

Desired output

I want to have the selected items checked. As in my JSON, i have stored chicken wings. If i click on edit, chicken wings should be checked already.

PS: I am a beginner and my english is not really good.

Controller

```<code>     $item = Item::findOrFail($id);
     return view('edit',compact('item'));
</code>```

HTML

```<code><div class="panel label_container">
<input onclick="return items(this)" type="checkbox" id="" name="" value="" />
</div>
</code>```

JSON

答:
If I understood the question correctly, you want to see if chicken wings (or any other food) is set and if it is, output a checked check box.

What you can do is use an if(strlen($json_file['name']) > 0) to see if chicken wings has text or not and then do  /> Chicken wings.

Example:

```<code><?php

if(strlen($json_file['name']) > 0) {
?>
<input type="checkbox" <? echo 'checked="checked"'; ?> />
}

?>
</code>```

I realized that the name could be set but have another name such as chicken breasts instead of wings, you can do an if($json_file['name'] == 'Chicken wings') {}.

Good luck!

Body:
I am trying to edit my form. Currently, i am able to retrieve data into my input textbox but not the checkbox. Now when, i am inserting data, i check the items that i want to insert, get the ids and save into my database.

Now when i want to edit, i want to retrieve the items that i previously selected (the checkbox of which i selected should be checked ).

In my Json below, i am able to display the id of the food that i selected when i was storing. How can i fetch that into my checkbox back

Desired output

I want to have the selected items checked. As in my JSON, i have stored chicken wings. If i click on edit, chicken wings should be checked already.

PS: I am a beginner and my english is not really good.

Controller

     $item = Item::findOrFail($id);
     return view('edit',compact('item'));

HTML

<input onclick="return items(this)" type="checkbox" id="" name="" value="" />

JSON

Body:
If I understood the question correctly, you want to see if chicken wings (or any other food) is set and if it is, output a checked check box.

What you can do is use an if(strlen($json_file['name']) > 0) to see if chicken wings has text or not and then do  /> Chicken wings.

Example:

<?php

if(strlen($json_file['name']) > 0) {
?>
<input type="checkbox" <? echo 'checked="checked"'; ?> />
}

?>

I realized that the name could be set but have another name such as chicken breasts instead of wings, you can do an if($json_file['name'] == 'Chicken wings') {}.

Good luck!


问:
Returning Promise from action creator in React Native using redux-thunk
I have an action creator that is called from my React component:

```<code>// ...
import { connect } from 'react-redux';
// ...
import { submitProfile } from '../actions/index';

// ...

  onSubmit() {
    const profile = {
      name: this.state.name
      // ...
    };

    this.props.submitProfile(profile)
      .then(() => { // I keep getting an error here saying cannot read property 'then' of undefined...
        console.log("Profile submitted. Redirecting to another scene.");
        this.props.navigator.push({ ... });
      });
  }

export default connect(mapStateToProps, { submitProfile })(MyComponent);
</code>```

The definition of the action creator is something like the following. Note I am using the redux-thunk middleware.

```<code>export function submitProfile(profile) {
  return dispatch => {
    axios.post(`some_url`, profile)
      .then(response => {
        console.log("Profile submission request was successful!");

        dispatch({ ... }); // dispatch some action

        // this doesn't seem to do anything . . .
        return Promise.resolve();
      })
      .catch(error => {
        console.log(error.response.data.error);
      });
  };
}
</code>```

What I want to be able to do is call the action creator to submit the profile and then after that request was successful, push a new route into the navigator from my component. I just want to be able to determine that the post request was successful so I can push the route; otherwise, I would not push anything, but say an error occurred, try again.

I looked up online and found Promise.resolve(), but it doesn't not seem to solve my problem. I know that I could just do a .then after calling an action creator if I was using the redux-promise middleware. How do I do it with redux-thunk?

答:
The return value from the function defined as the thunk will be returned. So the axios request must be returned from the thunk in order for things to work out properly. </p>

```<code>export function submitProfile(profile) {
  return dispatch => {
    return axios.post(`some_url`, profile) // don't forget the return here
      .then(response => {
        console.log("Profile submission request was successful!");

        dispatch({ ... }); // dispatch some action

        return Promise.resolve();
      })
      .catch(error => {
        console.log(error.response.data.error);
      });
  };
}
</code>```

Body:
I have an action creator that is called from my React component:

// ...
import { connect } from 'react-redux';
// ...
import { submitProfile } from '../actions/index';

// ...

  onSubmit() {
    const profile = {
      name: this.state.name
      // ...
    };

    this.props.submitProfile(profile)
      .then(() => { // I keep getting an error here saying cannot read property 'then' of undefined...
        console.log("Profile submitted. Redirecting to another scene.");
        this.props.navigator.push({ ... });
      });
  }

export default connect(mapStateToProps, { submitProfile })(MyComponent);

The definition of the action creator is something like the following. Note I am using the redux-thunk middleware.

export function submitProfile(profile) {
  return dispatch => {
    axios.post(`some_url`, profile)
      .then(response => {
        console.log("Profile submission request was successful!");

        dispatch({ ... }); // dispatch some action

        // this doesn't seem to do anything . . .
        return Promise.resolve();
      })
      .catch(error => {
        console.log(error.response.data.error);
      });
  };
}

What I want to be able to do is call the action creator to submit the profile and then after that request was successful, push a new route into the navigator from my component. I just want to be able to determine that the post request was successful so I can push the route; otherwise, I would not push anything, but say an error occurred, try again.

I looked up online and found Promise.resolve(), but it doesn't not seem to solve my problem. I know that I could just do a .then after calling an action creator if I was using the redux-promise middleware. How do I do it with redux-thunk?

Body:
The return value from the function defined as the thunk will be returned. So the axios request must be returned from the thunk in order for things to work out properly.

export function submitProfile(profile) {
  return dispatch => {
    return axios.post(`some_url`, profile) // don't forget the return here
      .then(response => {
        console.log("Profile submission request was successful!");

        dispatch({ ... }); // dispatch some action

        return Promise.resolve();
      })
      .catch(error => {
        console.log(error.response.data.error);
      });
  };
}


问:
How to count total items in a column, if header name is provided
Sorry! May be I couldn't give a nice question title. I have following sample data. Obviously in case of actual data it will be different and more...

Data Screenshot

Suppose, I put Pen in D17 cell then expected result will be 6 in E17 cell as in table/DataArray Pen column has 6 items. Count should be 4 if I put T-Shirt in D17 cell and so on....

Believe me, I tried combination of many formulas, search on google but no satisfied solution found. I can achieve it by VBA but I am trying to solve it by using excel formulas only.

答:
Some of the suggested formulas here look a little like overkill to me.....try this normally entered formula

=SUMPRODUCT((B3:K3=D17)*(B4:K13<>""))

or this will do the same

=SUM((B3:K3=D17)*(B4:K13<>""))

confirmed with CTRL+SHIFT+ENTER


问:
How to add objects to a pointer
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:

```<code>int *ptr;
ptr = new int;
</code>```

How after using that, can you add more objects to that pointer? (make it an array). Thanks!

答: Most implementations start off with a small array, and whenever it reaches its capacity, a new array of double the size is allocated and the old elements are copied to the new array.</p>

ContentLicense: CC BY-SA 4.0

Title: How to add objects to a pointer

Body:
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:

int *ptr;
ptr = new int;

How after using that, can you add more objects to that pointer? (make it an array). Thanks!

ContentLicense: CC BY-SA 2.5


问:
Align button with text input and select tag bootstrap4
i can't get my button to align with the select tag , there is a little space in the bottom that i couldn't remove.
as you can see in this picture

This my Code :

```<code><form>
    <div class="row ">
        <div class="col mt-4">
          <input type="text" name="">
        </div>
        <div class="col mt-4">
          <select></select>
        </div>
        <div class="col mt-4">
          <select></select>
        </div>

        <div class="col mt-4">
            <input type="submit" name="" value="Search" id="" class="btn btn-danger" style="border-radius: 5%;">
        </div>
    </div>
</form>
</code>```

答:
With bootstrap you can align items with flex

try this

```<code><div class="col mt-4 align-self-center">
        <input type="submit" name="" value="Search" id="" class="btn btn-danger" style="border-radius: 5%;">
    </div>
</code>```

This will center the input inside the column. The height of the button is decided by its padding and font size used.

Body:
i can't get my button to align with the select tag , there is a little space in the bottom that i couldn't remove.
as you can see in this picture

This my Code :

<form>

          <input type="text" name="">

          <select></select>

          <select></select>

            <input type="submit" name="" value="Search" id="" class="btn btn-danger" style="border-radius: 5%;">

</form>

Body:
With bootstrap you can align items with flex

try this

<div class="col mt-4 align-self-center">
        <input type="submit" name="" value="Search" id="" class="btn btn-danger" style="border-radius: 5%;">
    </div>

This will center the input inside the column. The height of the button is decided by its padding and font size used.


问:
Font scaling based on width of container with js libs
I'm trying to implement font-size scaling based on width of container (I want my long h1 to be in one line).

Here is my HTML with bootstrap 3:

```<code><div class="someclass">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1 class="responsive-headline">LONG TEXT IS
                LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG</h1>
                <ul class="breadcrumbs">
                    ...
                </ul>
            </div>
        </div>
    </div>
</div>
</code>```

CSS styles:

```<code>.responsive-headline {
    margin: 0px 0px 3px;
    color: #fff;
    text-transform: uppercase;
    font-size: 32px;
    letter-spacing: 1.7px;
    line-height: 1.4;
}
</code>```

Ok. Let's start from FitText.js library:

```<code>jQuery(document).ready(function($) {
   $('.responsive-headline').fitText();
});
</code>```

Result font-size: 114px;! What?
Add some parameters:

```<code>$('h1.responsive-headline').fitText(1.2, { minFontSize: '18px',
maxFontSize: '32px' });
</code>```

Result font-size: 32px;. Better but not what I want, I need smaller font-size. Also tried to add width: 1000px; display: block; white-space: nowrap; to h1 without success.

Second library that I tried is FlowType.js. Add some code:

```<code>jQuery(document).ready(function($) {
   $('h1.responsive-headline').flowtype();
});
</code>```

Result font-size: 32.5714px;. Little bigger than default.
And with parameters:

```<code>$('h1.responsive-headline').flowtype({
    minFont   : 12,
    maxFont   : 32
});
</code>```

Result font-size: 32px;.

Why my h1 becomes bigger but not smaller?

答:
Might it be because you are calculating the font-size on (document).ready?
If you're looking for a more dynamic sizing "responsive", maybe try the resize() method?
https://api.jquery.com/resize/

My appologies if im misunderstanding.

Body:
I'm trying to implement font-size scaling based on width of container (I want my long h1 to be in one line).

Here is my HTML with bootstrap 3:

LONG TEXT IS
                LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG

                    ...

CSS styles:

.responsive-headline {
    margin: 0px 0px 3px;
    color: #fff;
    text-transform: uppercase;
    font-size: 32px;
    letter-spacing: 1.7px;
    line-height: 1.4;
}

Ok. Let's start from FitText.js library:

jQuery(document).ready(function($) {
   $('.responsive-headline').fitText();
});

Result font-size: 114px;! What?
Add some parameters:

$('h1.responsive-headline').fitText(1.2, { minFontSize: '18px',
maxFontSize: '32px' });

Result font-size: 32px;. Better but not what I want, I need smaller font-size. Also tried to add width: 1000px; display: block; white-space: nowrap; to h1 without success.

Second library that I tried is FlowType.js. Add some code:

jQuery(document).ready(function($) {
   $('h1.responsive-headline').flowtype();
});

Result font-size: 32.5714px;. Little bigger than default.
And with parameters:

$('h1.responsive-headline').flowtype({
    minFont   : 12,
    maxFont   : 32
});

Result font-size: 32px;.

Why my h1 becomes bigger but not smaller?


问:
mysql query browser for sqlite with ssh tunneling (linux)
Is there a tool like mysql query browser for sqlite with ssh tunneling as well (linux) ?
Thanks in advance.</p>

答: Have a look at the SSH Filesystem to mount the remote filesystem into a local path. Then you can open the SQLite files with a common SQLite utility (if it isn't already locked on the remote machine).</p>


问:
In Linux , I want to search number of files & directories present in a directory
For example:
I have a directory with project.
In that 3 sub directories.
In that 3 sub directories 1 text file in each.

Now I am using scandir() to find how many files& directive present in that project. But scandir() is only scanning 1 level  mean it is not scanning sub directories how to scan them also.

答:
If you are using the command line, you can use find and wc.

To count all files recursively:

```<code>find . -type f | wc -l
</code>```

To find directory count:

```<code>find . -type d | wc -l
</code>```

+++++++++++++++++++++++++++++

-type f = file

-type d = directory

wc = prints newline, word or byte count which takes a parameter -l to give you line count

If you are referring to using scandir in PHP, you can try something like this:

```<code><?php
function dirToArray($dir) {

   $result = array();

   $cdir = scandir($dir);
   foreach ($cdir as $key => $value)
   {
      if (!in_array($value,array(".","..")))
      {
         if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
         {
            $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
         }
         else
         {
            $result[] = $value;
         }
      }
   }

   return $result;
}
?>
</code>```

Source: comment #88 http://php.net/manual/en/function.scandir.php

Body:
If you are using the command line, you can use find and wc.

To count all files recursively:

find . -type f | wc -l

To find directory count:

find . -type d | wc -l

+++++++++++++++++++++++++++++

-type f = file

-type d = directory

wc = prints newline, word or byte count which takes a parameter -l to give you line count

If you are referring to using scandir in PHP, you can try something like this:

<?php
function dirToArray($dir) {

   $result = array();

   $cdir = scandir($dir);
   foreach ($cdir as $key => $value)
   {
      if (!in_array($value,array(".","..")))
      {
         if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
         {
            $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
         }
         else
         {
            $result[] = $value;
         }
      }
   }

   return $result;
}
?>

Source: comment #88 http://php.net/manual/en/function.scandir.php


问:
Doctrine 2 optimistic locking only on changed fields
Is anyone aware of any bundle, or of any plans for Doctrine to implement a new optimistic locking strategy like the one in Telerik framework?

http://docs.telerik.com/data-access/developers-guide/crud-operations/concurrency-control/data-access-tasks-define-model-concurrency-optimistic#checking_for_any_changes

This strategy is great because it's not using version numbers, or timestamps, it compares the old values of the inputs with new values, and only for the changed inputs.

So if I have two different forms updating the same entity, using the current strategies (timestamp or versioning), 2 users will get into conflict even if the do not update the same data.

答:
I know this is a rather old question on the interwebs, so, I'm going to glaze over how this can be done in theory.

The per column lock implies there is a mechanism for detecting per column changes - therefore either the row is hashed (or the columns we are concerned about) and that hash comparison is used to detect/track changes OR we track each column individually.

This tracking would then have to be applied on a per request basis to determine what's changed, when. This is where the normal @Version decorator logic would apply.

Telerik is able to handle the per column changes because the information is compared (array comparisons, most likely) in the browser. This is an isolated state of the data that is not in sync with other browsers/database until update.

Easiest option here is to not allow the two forms to collide (in terms of data) and remove the lock - OR - decouple the forms data from the primary table and allow them to be updated separately (and merged with a sql join).


问:
Why I can store null in Int when doing conversion from Java but not otherwise?
In the following code, I am creating a Java collection. Later when I convert it to Scala, I can store null in Int. But I cannot store null if I straightaway create a scala map. Why?

```<code>scala> import collection.JavaConverters._
import collection.JavaConverters._

scala> val mapJava:java.util.HashMap[String,java.lang.Integer] =  new java.util.HashMap[String,java.lang.Integer]
mapJava: java.util.HashMap[String,Integer] = {}

scala> mapJava.put("key",null)
res2: Integer = null

scala> println(mapJava)
{key=null}

scala> val mapScala = mapJava.asScala
mapScala: scala.collection.mutable.Map[String,Integer] = Map(key -> null)

scala> val mapScalaI = mapScala.asInstanceOf[scala.collection.Map[String,Int]]
mapScalaI: scala.collection.Map[String,Int] = Map(key -> null) //storing null in Int

//but I cannot store null in Int in following code. why?
scala> val mapScalaI2 = Map[String,Int]("key"->null)
<console>:14: error: an expression of type Null is ineligible for implicit conversion
       val mapScalaI2 = Map[String,Int]("key"->null)
                                               ^
</code>```

答:
...

scala> val mapScala = mapJava.asScala
mapScala: scala.collection.mutable.Map[String,Integer] = Map(key -> null)

scala> val mapScalaI = mapScala.asInstanceOf[scala.collection.Map[String,Int]]
mapScalaI: scala.collection.Map[String,Int] = Map(key -> null) //storing null in Int

...
```

Theoretically, mapScala.asInstanceOf[scala.collection.Map[String,Int]] should fail because the Integer type argument is different from the Int type argument. However, it does not actually do so because asInstanceOf does not (or cannot) check the type arguments of Map[String, Int] due to Java type erasure. From scala.Any.asInstanceOf:

Note that the success of a cast at runtime is modulo Scala's erasure semantics. Therefore the expression 1.asInstanceOf[String] will throw a ClassCastException at runtime, while the expression List(1).asInstanceOf[List[String]] will not. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the requested type.

Body:
In the following code, I am creating a Java collection. Later when I convert it to Scala, I can store null in Int. But I cannot store null if I straightaway create a scala map. Why?

scala> import collection.JavaConverters._
import collection.JavaConverters._

scala> val mapJava:java.util.HashMap[String,java.lang.Integer] =  new java.util.HashMap[String,java.lang.Integer]
mapJava: java.util.HashMap[String,Integer] = {}

scala> mapJava.put("key",null)
res2: Integer = null

scala> println(mapJava)
{key=null}

scala> val mapScala = mapJava.asScala
mapScala: scala.collection.mutable.Map[String,Integer] = Map(key -> null)

scala> val mapScalaI = mapScala.asInstanceOf[scala.collection.Map[String,Int]]
mapScalaI: scala.collection.Map[String,Int] = Map(key -> null) //storing null in Int

//but I cannot store null in Int in following code. why?
scala> val mapScalaI2 = Map[String,Int]("key"->null)
<console>:14: error: an expression of type Null is ineligible for implicit conversion
       val mapScalaI2 = Map[String,Int]("key"->null)
                                               ^

Body:
...

scala> val mapScala = mapJava.asScala
mapScala: scala.collection.mutable.Map[String,Integer] = Map(key -> null)

scala> val mapScalaI = mapScala.asInstanceOf[scala.collection.Map[String,Int]]
mapScalaI: scala.collection.Map[String,Int] = Map(key -> null) //storing null in Int

...

Theoretically, mapScala.asInstanceOf[scala.collection.Map[String,Int]] should fail because the Integer type argument is different from the Int type argument. However, it does not actually do so because asInstanceOf does not (or cannot) check the type arguments of Map[String, Int] due to Java type erasure. From scala.Any.asInstanceOf:

Note that the success of a cast at runtime is modulo Scala's erasure semantics. Therefore the expression 1.asInstanceOf[String] will throw a ClassCastException at runtime, while the expression List(1).asInstanceOf[List[String]] will not. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the requested type.


问:
Assign torch.cuda.FloatTensor
I'd like to know how can I do the following code, but now using pytorch,
where dtype = torch.cuda.FloatTensor. There's the code straight python (using numpy):

```<code>import numpy as np
import random as rand
xmax, xmin = 5, -5
pop = 30
x = (xmax-xmin)*rand.random(pop,1)
y = x**2
[minz, indexmin] = np.amin(y), np.argmin(y)
best = x[indexmin]
</code>```

This is my attempt to do it:

```<code>import torch
dtype = torch.cuda.FloatTensor
def fit (position):
    return  position**2
def main():
    pop = 30
    xmax, xmin = 5, -5
    x= (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
    y = fit(x)
    [miny, indexmin] = torch.min(y,0)
    best = x[indexmin]
    print(best)
</code>```

The last part where I define the variable best as the value of x with index equal to indexmin it doesn't work. What am I doing wrong here.

The following messenge appears:

```<code>RuntimeError: expecting vector of indices at /opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/THC/generic/THCTensorIndex.cu:405
</code>```

答:
The above code works fine in pytorch 0.2. Let me analyze your code so that you can identify the problem.

```<code>x= (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
y = fit(x)
</code>```

Here, x and y is a 2d tensor of shape 30x1. In the next line:

```<code>[miny, indexmin] = torch.min(y,0)
</code>```

The returned tensor miny is a 2d tensor of shape 30x1 and indexmin is a 1d tensor of size 1. So, when you execute:

```<code>best = x[indexmin]
</code>```

It (probably) gives error (in old pytorch version) because x is a 2d tensor of shape 30x1 and indexmin is a 1d tensor of size 1. To resolve this error, you can simply do:

```<code>best = x.squeeze()[indexmin] # x.squeeze() returns a 1d tensor of size `30`
</code>```

Please note, a 2d tensor of shape 30x1 is same as a 1d tensor of size 30. So, you can modify your program as follows.

```<code>import torch
dtype = torch.cuda.FloatTensor
def main():
    pop, xmax, xmin = 30, 5, -5
    x= (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
    y = torch.pow(x, 2)
    minz, indexmin = y.min(0)
    best = x[indexmin]
    print(best)

main()
</code>```

Title: Assign torch.cuda.FloatTensor

Body:
I'd like to know how can I do the following code, but now using pytorch,
where dtype = torch.cuda.FloatTensor. There's the code straight python (using numpy):

import numpy as np
import random as rand
xmax, xmin = 5, -5
pop = 30
x = (xmax-xmin)*rand.random(pop,1)
y = x**2
[minz, indexmin] = np.amin(y), np.argmin(y)
best = x[indexmin]

This is my attempt to do it:

import torch
dtype = torch.cuda.FloatTensor
def fit (position):
    return  position**2
def main():
    pop = 30
    xmax, xmin = 5, -5
    x= (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
    y = fit(x)
    [miny, indexmin] = torch.min(y,0)
    best = x[indexmin]
    print(best)

The last part where I define the variable best as the value of x with index equal to indexmin it doesn't work. What am I doing wrong here.

The following messenge appears:

RuntimeError: expecting vector of indices at /opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/THC/generic/THCTensorIndex.cu:405

Body:
The above code works fine in pytorch 0.2. Let me analyze your code so that you can identify the problem.

x= (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
y = fit(x)

Here, x and y is a 2d tensor of shape 30x1. In the next line:

[miny, indexmin] = torch.min(y,0)

The returned tensor miny is a 2d tensor of shape 30x1 and indexmin is a 1d tensor of size 1. So, when you execute:

best = x[indexmin]

It (probably) gives error (in old pytorch version) because x is a 2d tensor of shape 30x1 and indexmin is a 1d tensor of size 1. To resolve this error, you can simply do:

best = x.squeeze()[indexmin] # x.squeeze() returns a 1d tensor of size `30`

Please note, a 2d tensor of shape 30x1 is same as a 1d tensor of size 30. So, you can modify your program as follows.

import torch
dtype = torch.cuda.FloatTensor
def main():
    pop, xmax, xmin = 30, 5, -5
    x= (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
    y = torch.pow(x, 2)
    minz, indexmin = y.min(0)
    best = x[indexmin]
    print(best)

main()


问:
how to pass Action type in bundle type to AppCompatActivity android xamarin
I have Action in MainActivity. I want to pass it to another ViewPagerActivity: AppCompatActivty. As here is: </p>

```<code> Action<ImageView> btnAction = PickSelected;

    ...
     private void PickSelected(ImageView img)
        {

        }

    ...
   var intentVP = new Android.Content.Intent(this, typeof(ViewPagerActivity));
   Bundle mb = new Bundle();
   mb.PutParcelable("bundle",btnAction); // here it give me the error
   intentVP.PutExtra("MainBundle",mb);

   StartActivity(intentVP);
</code>```

<p>The error is next: "btnAction cannot be converted from System.Action to Android.OS.IParcelable". Is it possible pass Action type or there is another way? </p>

答:
I can't make comments so I will just answer instead.

From what I can see here, it looks like you are using an Action delegate and wanting to return a result based of what was picked in the "PickSelected" method.

The problem though is Action delegate return void, so you cannot do this.

Instead, you need to make the btnAction a  Func and change the signature of PickSelected to the Android.OS.IParcelable (or whatever the type is required for that, I don't code for Android sadly) and in the method where you're passing the delegate, you need to invoke it and pass the ImageView object.

```<code>Func<ImageView, Android.OS.IParcelable> btnAction = PickSelected;
 private Android.OS.IParcelable PickSelected(ImageView img)
    {
        //// Insert logic here

        return Android.OS.IParcelable object;
    }
var intentVP = new Android.Content.Intent(this, typeof(ViewPagerActivity));
Bundle mb = new Bundle();
mb.PutParcelable("bundle",btnAction.Invoke(ImageViewObject));
StartActivity(intentVP);
</code>```

Body:
I have Action in MainActivity. I want to pass it to another ViewPagerActivity: AppCompatActivty. As here is:

 Action<ImageView> btnAction = PickSelected;

    ...
     private void PickSelected(ImageView img)
        {

        }

    ...
   var intentVP = new Android.Content.Intent(this, typeof(ViewPagerActivity));
   Bundle mb = new Bundle();
   mb.PutParcelable("bundle",btnAction); // here it give me the error
   intentVP.PutExtra("MainBundle",mb);

   StartActivity(intentVP);

The error is next: "btnAction cannot be converted from System.Action to Android.OS.IParcelable". Is it possible pass Action type or there is another way?

Body:
I can't make comments so I will just answer instead.

From what I can see here, it looks like you are using an Action delegate and wanting to return a result based of what was picked in the "PickSelected" method.

The problem though is Action delegate return void, so you cannot do this.

Instead, you need to make the btnAction a  Func and change the signature of PickSelected to the Android.OS.IParcelable (or whatever the type is required for that, I don't code for Android sadly) and in the method where you're passing the delegate, you need to invoke it and pass the ImageView object.

Func<ImageView, Android.OS.IParcelable> btnAction = PickSelected;
 private Android.OS.IParcelable PickSelected(ImageView img)
    {
        //// Insert logic here

        return Android.OS.IParcelable object;
    }
var intentVP = new Android.Content.Intent(this, typeof(ViewPagerActivity));
Bundle mb = new Bundle();
mb.PutParcelable("bundle",btnAction.Invoke(ImageViewObject));
StartActivity(intentVP);


问:
Continued - Vehicle License Plate Detection
Continuing from this thread:

What are good algorithms for vehicle license plate detection?

I've developed my image manipulation techniques to emphasise the license plate as much as possible, and overall I'm happy with it, here are two samples.

Now comes the most difficult part, actually detecting the license plate. I know there are a few edge detection methods, but my maths is quite poor so I'm unable to translate some of the complex formulas into code.

My idea so far is to loop through every pixel within the image (for loop based on img width & height) From this compare each pixel against a list of colours, from this an algorithm is checked to see if the colors keep differentiating between the license plate white, and the black of the text. If this happens to be true these pixels are built into a new bitmap within memory, then an OCR scan is performed once this pattern has stopped being detected.

I'd appreciate some input on this as it might be a flawed idea, too slow or intensive.

Thanks

答:
Colour, as much as looks good, will present quite some challenges with shading and light conditions. Depends really how much you want to make it robust but real world cases have to deal with such issues.

I have done research on road footage (see my profile page and look here for sample) and have found that the real-world road footage is extremely noisy in terms of light conditions and your colours can change from Brown to White for a yellow back-number-plate.

Most algorithms use line detection and try to find a box with an aspect ratio within an acceptable range.

I suggest you do a literature review on the subject but this was achieved back in 1993 (if I remember correctly) so there will be thousands of articles.

This is quite a scientific domain so just an algorithm will not solve it and you will needs numerous pre/post processing steps.

In brief, my suggestion is to use Hough transform to find lines and then try to look for rectangles that could create acceptable aspect ratio.

Harris feature detection could provide important edges but if the car is light-coloured this will not work.


问:
Makefile will link files upon a file change, but not recompile the source file that changed
I have the following makefile which seems to work pretty well:

```<code>HDRS =  include/config.h include/opcode_def.h include/x86lib.h include/x86lib_internal.h
CXX ?= g++
AR ?= ar

TEST_CC ?= i386-elf-gcc
TEST_CFLAGS ?= -fdata-sections -ffunction-sections

CXX_VM_SRC = vm/x86lib.cpp vm/modrm.cpp vm/device_manager.cpp vm/cpu_helpers.cpp vm/ops/strings.cpp vm/ops/store.cpp vm/ops/maths.cpp \
          vm/ops/groups.cpp vm/ops/flow.cpp vm/ops/flags.cpp vm/ops/etc.cpp

CXX_VM_OBJS = $(subst .cpp,.o,$(CXX_VM_SRC))

CXX_TESTBENCH_SRC = testbench/testbench.cpp

CXX_TESTBENCH_OBJS = $(subst .cpp,.o,$(CXX_TESTBENCH_SRC))

CXXFLAGS ?= -Wall -g3 -fexceptions -fPIC -Wall
CXXFLAGS += -DX86LIB_BUILD -I./include

VERSION=1.1

VM_OUTPUTS = libx86lib.a libx86lib.so.$(VERSION)
OUTPUTS = $(VM_OUTPUTS) x86testbench

default: build

build: $(OUTPUTS)

libx86lib.a: $(CXX_VM_OBJS) $(CXX_VM_SRC)
    ar crs libx86lib.a $(CXX_VM_OBJS)

libx86lib.so.$(VERSION): $(CXX_VM_OBJS) $(CXX_VM_SRC)
    $(CXX) -shared $(CXX_VM_OBJS) -o libx86lib.so.$(VERSION)

x86testbench: $(CXX_TESTBENCH_OBJS) $(VM_OUTPUTS)
    $(CXX) $(CXXFLAGS) -static -o x86testbench $(CXX_TESTBENCH_OBJS) -lx86lib -L.

$(CXX_TESTBENCH_OBJS): $(HDRS)
    $(CXX) $(CXXFLAGS) -c $*.cpp -o $@

$(CXX_VM_OBJS): $(HDRS)
    $(CXX) $(CXXFLAGS) -c $*.cpp -o $@

clean:
    rm $(CXX_VM_OBJS) $(OUTPUTS) $(CXX_TESTBENCH_OBJS)
</code>```

My problem is that if I change a file, such as "vm/x86lib.cpp" then it will relink the final outputs and such, but it will not recompile vm/x86lib.o. I don't know how to express this recompile requirement to the $(CXX_VM_OBJS) build rule.

How do I fix this so that it will recompile my the source files as well as relink them?

Note: if I put $(CXX_VM_SRC) as a dependency on $(CXX_VM_OBJS), then it will recompile every file anytime a single file changes. Also, I'm only concerned about GNU Make and OSX/Linux environments.

答:
In the dependency list for CXX_VM_OBJS, try to add the source filenames that you want the object to depend on, for example:</p>

```<code>$(CXX_VM_OBJS): $(HDRS) vm/x86lib.cpp
    $(CXX) $(CXXFLAGS) -c $*.cpp -o $@
</code>```

Body:
I have the following makefile which seems to work pretty well:

HDRS =  include/config.h include/opcode_def.h include/x86lib.h include/x86lib_internal.h
CXX ?= g++
AR ?= ar

TEST_CC ?= i386-elf-gcc
TEST_CFLAGS ?= -fdata-sections -ffunction-sections

CXX_VM_SRC = vm/x86lib.cpp vm/modrm.cpp vm/device_manager.cpp vm/cpu_helpers.cpp vm/ops/strings.cpp vm/ops/store.cpp vm/ops/maths.cpp \
          vm/ops/groups.cpp vm/ops/flow.cpp vm/ops/flags.cpp vm/ops/etc.cpp

CXX_VM_OBJS = $(subst .cpp,.o,$(CXX_VM_SRC))

CXX_TESTBENCH_SRC = testbench/testbench.cpp

CXX_TESTBENCH_OBJS = $(subst .cpp,.o,$(CXX_TESTBENCH_SRC))

CXXFLAGS ?= -Wall -g3 -fexceptions -fPIC -Wall
CXXFLAGS += -DX86LIB_BUILD -I./include

VERSION=1.1

VM_OUTPUTS = libx86lib.a libx86lib.so.$(VERSION)
OUTPUTS = $(VM_OUTPUTS) x86testbench

default: build

build: $(OUTPUTS)

libx86lib.a: $(CXX_VM_OBJS) $(CXX_VM_SRC)
    ar crs libx86lib.a $(CXX_VM_OBJS)

libx86lib.so.$(VERSION): $(CXX_VM_OBJS) $(CXX_VM_SRC)
    $(CXX) -shared $(CXX_VM_OBJS) -o libx86lib.so.$(VERSION)

x86testbench: $(CXX_TESTBENCH_OBJS) $(VM_OUTPUTS)
    $(CXX) $(CXXFLAGS) -static -o x86testbench $(CXX_TESTBENCH_OBJS) -lx86lib -L.

$(CXX_TESTBENCH_OBJS): $(HDRS)
    $(CXX) $(CXXFLAGS) -c $*.cpp -o $@

$(CXX_VM_OBJS): $(HDRS)
    $(CXX) $(CXXFLAGS) -c $*.cpp -o $@

clean:
    rm $(CXX_VM_OBJS) $(OUTPUTS) $(CXX_TESTBENCH_OBJS)

My problem is that if I change a file, such as "vm/x86lib.cpp" then it will relink the final outputs and such, but it will not recompile vm/x86lib.o. I don't know how to express this recompile requirement to the $(CXX_VM_OBJS) build rule.

How do I fix this so that it will recompile my the source files as well as relink them?

Note: if I put $(CXX_VM_SRC) as a dependency on $(CXX_VM_OBJS), then it will recompile every file anytime a single file changes. Also, I'm only concerned about GNU Make and OSX/Linux environments.

Body:
In the dependency list for CXX_VM_OBJS, try to add the source filenames that you want the object to depend on, for example:

$(CXX_VM_OBJS): $(HDRS) vm/x86lib.cpp
    $(CXX) $(CXXFLAGS) -c $*.cpp -o $@