问:
Getting closed implementation type inside Autofac's WithParameter
I'm trying to register generic repository to use specific context based on entity custom attribute. Below is what i have

Globax.asax

```<code>//data layer
foreach (var database in DatabaseManager.Databases)
{
    builder.Register<IDbContext>(c => new CodesObjectContext(database.ConnectionString))
        .As<IDbContext>()
        .Named<IDbContext>(database.Alias)
        .InstancePerLifetimeScope();
}

builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
    .WithParameter(new ResolvedParameter(
        (pi, ctx) => pi.ParameterType == typeof(IDbContext),
        (pi, ctx) => ctx.ResolveNamed<IDbContext>((
            { Generic Type Of EfRepository}.GetType()
                .GetCustomAttributes(typeof(DatabaseAttribute), true)[0]
                    as DatabaseAttribute).Name)))
    .InstancePerLifetimeScope();
</code>```

I cant seem to get here, { Generic Type Of EfRepository }. Is it possible for me to get the current generic type of EfRepository being registered?

答:
You can access the concrete resolved type using the DeclaringType of the parameter info

```<code>builder.RegisterGeneric(typeof(EfRepository<>))
       .As(typeof(IRepository<>))
       .WithParameter(new ResolvedParameter(
               (pi, c) => pi.ParameterType == typeof(IDbContext),
               (pi, c) => c.ResolveNamed<IDbContext>(
                   pi.Member.DeclaringType
                     .GetGenericArguments()[0]
                     .GetCustomAttributes(typeof(DatabaseAttribute), true)
                     .OfType<DatabaseAttribute>()
                     .First()
                     .Name)))
       .InstancePerLifetimeScope();
</code>```

Another solution would be to use the OnPreparing pseudo event and inject a new Parameter

```<code>builder.RegisterGeneric(typeof(EfRepository<>))
       .As(typeof(IRepository<>))
       .OnPreparing(e => {
           e.Parameters = e.Parameters.Union(
               new[] {
                   new ResolvedParameter(
                       (pi, c) => pi.ParameterType == typeof(IDbContext),
                       (pi, c) => {
                           String databaseName =
                               pi.Member
                                 .DeclaringType
                                 .GetGenericArguments()[0]
                                 .GetCustomAttributes(typeof(DatabaseAttribute), true)
                                 .OfType<DatabaseAttribute>()
                                 .FirstOrDefault()
                                 .?Name
                           if (String.IsNullOrEmpty(databaseName)
                           {
                               // TODO
                           }

                           c.ResolveNamed<IDbContext>(databaseName)
                       }
                   )
               });
       })
       .InstancePerLifetimeScope();
</code>```

You can also create add the OnPreparing event on a custom Module. See http://docs.autofac.org/en/latest/examples/log4net.html for more information.

Body:
I'm trying to register generic repository to use specific context based on entity custom attribute. Below is what i have

Globax.asax

//data layer
foreach (var database in DatabaseManager.Databases)
{
    builder.Register<IDbContext>(c => new CodesObjectContext(database.ConnectionString))
        .As<IDbContext>()
        .Named<IDbContext>(database.Alias)
        .InstancePerLifetimeScope();
}

builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
    .WithParameter(new ResolvedParameter(
        (pi, ctx) => pi.ParameterType == typeof(IDbContext),
        (pi, ctx) => ctx.ResolveNamed<IDbContext>((
            { Generic Type Of EfRepository}.GetType()
                .GetCustomAttributes(typeof(DatabaseAttribute), true)[0]
                    as DatabaseAttribute).Name)))
    .InstancePerLifetimeScope();

I cant seem to get here, { Generic Type Of EfRepository }. Is it possible for me to get the current generic type of EfRepository being registered?

Body:
You can access the concrete resolved type using the DeclaringType of the parameter info

builder.RegisterGeneric(typeof(EfRepository<>))
       .As(typeof(IRepository<>))
       .WithParameter(new ResolvedParameter(
               (pi, c) => pi.ParameterType == typeof(IDbContext),
               (pi, c) => c.ResolveNamed<IDbContext>(
                   pi.Member.DeclaringType
                     .GetGenericArguments()[0]
                     .GetCustomAttributes(typeof(DatabaseAttribute), true)
                     .OfType<DatabaseAttribute>()
                     .First()
                     .Name)))
       .InstancePerLifetimeScope();

Another solution would be to use the OnPreparing pseudo event and inject a new Parameter

builder.RegisterGeneric(typeof(EfRepository<>))
       .As(typeof(IRepository<>))
       .OnPreparing(e => {
           e.Parameters = e.Parameters.Union(
               new[] {
                   new ResolvedParameter(
                       (pi, c) => pi.ParameterType == typeof(IDbContext),
                       (pi, c) => {
                           String databaseName =
                               pi.Member
                                 .DeclaringType
                                 .GetGenericArguments()[0]
                                 .GetCustomAttributes(typeof(DatabaseAttribute), true)
                                 .OfType<DatabaseAttribute>()
                                 .FirstOrDefault()
                                 .?Name
                           if (String.IsNullOrEmpty(databaseName)
                           {
                               // TODO
                           }

                           c.ResolveNamed<IDbContext>(databaseName)
                       }
                   )
               });
       })
       .InstancePerLifetimeScope();

You can also create add the OnPreparing event on a custom Module. See http://docs.autofac.org/en/latest/examples/log4net.html for more information.


来源: stackexchange

问:
div grid tab not in content
I use a php function to put my page content in the index.php, but when I use a grid (tab) in the content it goes out of the content borders.

I put a little bit of the code underneath, you can see the site here: (link deleted > problem solved)

答:
```<code>.content {
    background-color: #fff;
    border-radius: 4px 4px 4px 4px;
    box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.2);
    padding: 15px;
    margin-bottom: 20px;
    clear: both;
    float: left;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: div grid tab not in content


问:
Best way to add left and right cols to responsive Bootstrap rows ? (with TWIG)
I use TWIG to render some HTML/Twitter Boostrap CSS code. I made an image gallery using this following code:

```<code><section class="row align-items-center" style="margin:0px; padding:0px;">
      {% for i in contents %}
      <div class="col-xs-12 col-sm-4 col-md-3 col-lg-2 text-center box">
        <a href="#">
          <img class="ownthumbnail" src="{{ asset('images/'~section~'/'~i) | imagine_filter('mini') }}" alt=":-)">
        </a>
      </div>
      {% endfor %}
</section>
</code>```

I would like, for some design reasons, to add automatically two columns (one left, one right like margins) per rendered rows independently from the size of the window (xs, sm, md or lg). How would you tackle this problem ?

EDIT: to be clear, what I get now is a gallery with 6 columns (col-lg-2), 4 columns (col-md-3), 3 columns (col-sm-4) or 1 column (col-xs-12) depending on the size of the screen. I want the same grid layout, but let the left and right columns empty. This would be ideally like this for the col-lg-2 case, with 9 images:

emp: empty
img: image

```<code>[empt][img1][img2][img3][img4][empt]
[empt][img5][img6][img7][img8][empt]
[empt][img9][empt][empt][empt][empt]
</code>```

答: For the class of your div tag you could set class="col-xs-6 col-sm-6 col-md-6 col-lg-6". I hope this is working. It should set two columns in each row.</p>

Body:
I use TWIG to render some HTML/Twitter Boostrap CSS code. I made an image gallery using this following code:

      {% for i in contents %}

      {% endfor %}

I would like, for some design reasons, to add automatically two columns (one left, one right like margins) per rendered rows independently from the size of the window (xs, sm, md or lg). How would you tackle this problem ?

EDIT: to be clear, what I get now is a gallery with 6 columns (col-lg-2), 4 columns (col-md-3), 3 columns (col-sm-4) or 1 column (col-xs-12) depending on the size of the screen. I want the same grid layout, but let the left and right columns empty. This would be ideally like this for the col-lg-2 case, with 9 images:

emp: empty
img: image

[empt][img1][img2][img3][img4][empt]
[empt][img5][img6][img7][img8][empt]
[empt][img9][empt][empt][empt][empt]


问:
Regex to match text and a specific number
I am looking for a regex which can match the following conditions.

It always starts with "someId":[ and ends with ].

It must contain the number 25 within the square brackets.

There may be numbers before and after number 25

The numbers are separated with a comma (,) apart from the last number

For example:

```<code>"someId":[25]
"someId":[25,27]
"someId":[1,4,25]
"someId":[1,4,25,27,30]
</code>```

I have the following regex which works, however I was wondering if theres a better way to do it which isn't as greedy.

```<code>"someId":\[(\d{1,2},)*?25,?(\d{1,2},)*?(\d{1,2})?]
</code>```

Body:
I am looking for a regex which can match the following conditions.

It always starts with "someId":[ and ends with ].

It must contain the number 25 within the square brackets.

There may be numbers before and after number 25

The numbers are separated with a comma (,) apart from the last number

For example:

"someId":[25]
"someId":[25,27]
"someId":[1,4,25]
"someId":[1,4,25,27,30]

I have the following regex which works, however I was wondering if theres a better way to do it which isn't as greedy.

"someId":\[(\d{1,2},)*?25,?(\d{1,2},)*?(\d{1,2})?]

Body:
a bit simplified:

"someId":\[(\d+,)*25(,\d+)*\]


问:
C++ unresolved external symbol (public static int)
When I try to compile this, I get this linker error:

```
LNK2001 unresolved external symbol "public: static int HooksXD::night" (?night@HooksXD@@2HA)```

The header is this:

```<code>class HooksXD
{
    public:
        static void XD3();
        static int night;
        static int night2;
};
</code>```

Variables are public not private because I need to access them from other voids witch are not in the same class.

The cpp file:

```<code>HooksXD lmao;
void HooksXD::XD3()
{
    //this void will be called from other cpp files
    lmao.night = 1;
    lmao.night2 = 1;
};

bool __stdcall CreateMoveClient_Hooked(float frametime, CUserCmd* pCmd)
{
    if (lmao.night = 1)
    {
        //some code
        lmao.night++;
    }
}
</code>```

答:
You have only declared night and night2, they still need definitions. (because they're static)

In your cpp file :

```<code>int HooksXD::night = 0;
int HooksXD::night2 = 0;
</code>```

And then to access one don't do lmao.night, since it's a static you should access it through the type name : HooksXD::night.
Make sure you actually need static here though.

Body:
When I try to compile this, I get this linker error:

LNK2001 unresolved external symbol "public: static int HooksXD::night" (?night@HooksXD@@2HA)

The header is this:

class HooksXD
{
    public:
        static void XD3();
        static int night;
        static int night2;
};

Variables are public not private because I need to access them from other voids witch are not in the same class.

The cpp file:

HooksXD lmao;
void HooksXD::XD3()
{
    //this void will be called from other cpp files
    lmao.night = 1;
    lmao.night2 = 1;
};

bool __stdcall CreateMoveClient_Hooked(float frametime, CUserCmd* pCmd)
{
    if (lmao.night = 1)
    {
        //some code
        lmao.night++;
    }
}

Body:
You have only declared night and night2, they still need definitions. (because they're static)

In your cpp file :

int HooksXD::night = 0;
int HooksXD::night2 = 0;

And then to access one don't do lmao.night, since it's a static you should access it through the type name : HooksXD::night.
Make sure you actually need static here though.


问:
Parsing key values pairs from text as dictionary
I'm still quite new to Python and I was wondering how would I convert something that is already in key:value form in a text file into a Python dictionary?

Eg.

```<code>2:red
3:orange
5:yellow
6:green
</code>```

(each key:value on a separate line)

I've looked at other posts but none of them seem to work and I know I'm doing something wrong. So far, I have:

```<code>def create_colours_dictionary(filename):
    colours_dict = {}
    file = open(filename,'r')
    contents = file.read()

    for key in contents:
        #???
    return colours_dict
</code>```

答:
The straight-forward way to do this is to use a traditional for loop, and the str.split method.

Rather than reading from a file, I'll embed the input data into the script as a multi-line string, and use str.splitlines to convert it to a list of strings, so we can loop over it, just like looping over the lines of a file.

```<code># Use a list of strings to simulate the file
contents = '''\
2:red
3:orange
5:yellow
6:green
'''.splitlines()

colours_dict = {}
for s in contents:
    k, v = s.split(':')
    colours_dict[k] = v

print(colours_dict)
</code>```

output

```<code>{'2': 'red', '3': 'orange', '5': 'yellow', '6': 'green'}
</code>```

Be aware that this code will only work correctly if there are no spaces surrounding the colon. If there could be spaces (or spaces at the start or end of the line), they you can use the str.strip method to remove them.

There are a couple of ways to make this more compact.

We could use a list comprehension nested inside a dictionary comprehension:

```<code>colours_dict = {k: v for k, v in [s.split(':') for s in contents]}
</code>```

But it's even more compact to use the dict constructor on a generator expression:

```<code>colours_dict = dict(s.split(':') for s in contents)
</code>```

If you aren't familiar with comprehensions, please see
List Comprehensions and Dictionaries in the official tutorial.

ContentLicense: CC BY-SA 4.0

Body:
I'm still quite new to Python and I was wondering how would I convert something that is already in key:value form in a text file into a Python dictionary?

Eg.

2:red
3:orange
5:yellow
6:green

(each key:value on a separate line)

I've looked at other posts but none of them seem to work and I know I'm doing something wrong. So far, I have:

def create_colours_dictionary(filename):
    colours_dict = {}
    file = open(filename,'r')
    contents = file.read()

    for key in contents:
        #???
    return colours_dict

Body:
The straight-forward way to do this is to use a traditional for loop, and the str.split method.

Rather than reading from a file, I'll embed the input data into the script as a multi-line string, and use str.splitlines to convert it to a list of strings, so we can loop over it, just like looping over the lines of a file.

# Use a list of strings to simulate the file
contents = '''\
2:red
3:orange
5:yellow
6:green
'''.splitlines()

colours_dict = {}
for s in contents:
    k, v = s.split(':')
    colours_dict[k] = v

print(colours_dict)

output

{'2': 'red', '3': 'orange', '5': 'yellow', '6': 'green'}

Be aware that this code will only work correctly if there are no spaces surrounding the colon. If there could be spaces (or spaces at the start or end of the line), they you can use the str.strip method to remove them.

There are a couple of ways to make this more compact.

We could use a list comprehension nested inside a dictionary comprehension:

colours_dict = {k: v for k, v in [s.split(':') for s in contents]}

But it's even more compact to use the dict constructor on a generator expression:

colours_dict = dict(s.split(':') for s in contents)

If you aren't familiar with comprehensions, please see
List Comprehensions and Dictionaries in the official tutorial.


问:
Yii model to array?
How can I convert the result of Trips::model()->findAll() to an array?

答:
Use DAO for arrays</p>

```<code>$array = Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();
</code>```

ContentLicense: CC BY-SA 2.5

Title: Yii model to array?

Body:
Use DAO for arrays

$array = Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();


问:
Jquery Animation Left to right not working
Why is this not working? This should be animate the arrow from left to right and then back to left again and so on, but this is not working. Why is that?

function moveRight(){
    $('#myIcon').animate({left: "+=50"}, 1000, function(){
        $('#myIcon').animate({left: "-=50"}, 1000, moveRight)
    })
}
moveRight();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a{
  text-decoration: none;
}</code>```

←  Go Back
```

答:
Add style position:absolute to the icon

function moveRight(){
    $('#myIcon').animate({left: "+=50"}, 1000, function(){
        $('#myIcon').animate({left: "-=50"}, 1000, moveRight)
    })
}
moveRight();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a{
  text-decoration: none;
}

#myIcon{
 position:absolute;
}</code>```

←  Go Back
```

Body:
Why is this not working? This should be animate the arrow from left to right and then back to left again and so on, but this is not working. Why is that?

function moveRight(){
    $('#myIcon').animate({left: "+=50"}, 1000, function(){
        $('#myIcon').animate({left: "-=50"}, 1000, moveRight)
    })
}
moveRight();

a{
  text-decoration: none;
}

←  Go Back

Body:
Add style position:absolute to the icon

function moveRight(){
    $('#myIcon').animate({left: "+=50"}, 1000, function(){
        $('#myIcon').animate({left: "-=50"}, 1000, moveRight)
    })
}
moveRight();

a{
  text-decoration: none;
}

#myIcon{
 position:absolute;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="btn btn-danger btn-lg">
<span id="myIcon">←</span>&nbsp; Go Back
</a>


问:
How to apply learning curves on Azure Machine Learning
I have started using the Azure Studio ML and would like to know if there is a way of inputting a learning curve code (python or R) into my model.

I am training with Two-Class Boosted Decision Tree and I want to check if my results are overfitting or not.

I have also found some codes for Learning Curves and I know there is a box to execute the codes in either R or Python but I do not know what I have change in the code (if I actually have to) and how do I connect my dataset to this code

Code source: http://www.ritchieng.com/machinelearning-learning-curve/

Thank you,
Lucas

答:
I reviewed the document you linked, there are some Python packages used in the code source, which include sklearn, matplotlib & numpy that be supported on Azure ML studio. So you just need to refer to the offical tutorial Execute Python machine learning scripts in Azure Machine Learning Studio to write your script.

For how to connect your dataset or load data, you can refer to these documents if using Python to do it.

Access datasets with Python using the Azure Machine Learning Python client library

Move data to and from Azure Blob Storage using Python

Create features for data in SQL Server using SQL and Python

For other ways to connect dataset or load data, please move to here to filter the topic via the key words Acquire and understand data.


问:
Xcode 9 simulator remove frames
The new simulator comes with the frames that make it look more like a phone in Xcode 9 beta. Is there any way to remove this frames and make it look more like the simulator in Xcode 8?</p>

答:
Yes there is and it was the first thing I removed. To remove the frames do the following:

Click on the simulator

Go to Window (top menu)

Click on Show Device Bezels (which should have a checkmark on it)

The simulator will now have the same look as the one in Xcode 8.

Title: Xcode 9 simulator remove frames


问:
npm ERR! remote: Invalid username or password
I am able to add the vcs root and test the connection in Teamcity, the connection is successful.
But I'm getting an Authentiation failed error. Please advice.</p>

```<code>Step 1/1: Install npm packages (Node.js NPM) (3s)
[00:00:00][Step 1/2] Executing npm via wrapping shell script
[00:00:00][Step 1/2] Starting: cmd /c npm install
[00:00:00][Step 1/2] in directory: F:\BuildAgent\work\abc13213
[00:00:00][Step 1/2] npm install (3s)
[00:00:00][npm install] npm ERR! git fetch -a origin (https://git@bitbucket.org/team/repo.git) remote: Invalid username or password. If you log in via a third party service you must ensure you have an account password set in your account profile.
[00:00:00][npm install] npm ERR! git fetch -a origin (https://git@bitbucket.org/team/repo.git) fatal: Authentication failed for 'https://git@bitbucket.org/team/repo.git/';
[00:00:00][npm install] npm ERR! Windows_NT 6.3.9600
[00:00:00][npm install] npm ERR! argv "F:\\nodejs\\node.exe" "C:\\Users\\svc-p-teamcity\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install"
[00:00:00][npm install] npm ERR! node v6.10.2
[00:00:00][npm install] npm ERR! npm  v4.3.0
[00:00:00][npm install] npm ERR! code 128
[00:00:00][npm install]
[00:00:00][npm install] npm ERR! Command failed: git -c core.longpaths=true fetch -a origin
[00:00:00][npm install] npm ERR! remote: Invalid username or password. If you log in via a third party service you must ensure you have an account password set in your account profile.
[00:00:00][npm install] npm ERR! fatal: Authentication failed for 'https://git@bitbucket.org/team/repo.git/';
[00:00:00][npm install] npm ERR!
[00:00:00][npm install] npm ERR!
[00:00:00][npm install] npm ERR! If you need help, you may report this error at:
[00:00:00][npm install] npm ERR!     <https://github.com/npm/npm/issues>;
[00:00:00][npm install]
[00:00:00][npm install] npm ERR! Please include the following file with any support request:
[00:00:00][npm install] npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2017-06-05T19_50_00_082Z-debug.log
[00:00:00][Step 1/2] Process exited with code 1
[00:00:00][Step 1/2] Step Install npm packages (Node.js NPM) failed
</code>```

答:
You configured VCS root in the Teamcity, so before the build starts, Teamcity will automatically checkout required repository paths to the local machine.

The problem you showed in the original log is different: npm is trying to connect to bitbucket repository to install some dependencies and fails, because authorization.

To solve this issue, you have to configure SSH key for Teamcity user (user as far as I can see from your log). You can verify that it works via running the same command from the original host, where Teamcity agent sits:

```<code>git clone 'https://git@bitbucket.org/team/repo.git/'
</code>```

Otherwise, you have to change the source of your dependencies: maybe you have an Artifactory instance somewhere, which doesn't require authorisation.

Body:
I am able to add the vcs root and test the connection in Teamcity, the connection is successful.
But I'm getting an Authentiation failed error. Please advice.

Step 1/1: Install npm packages (Node.js NPM) (3s)
[00:00:00][Step 1/2] Executing npm via wrapping shell script
[00:00:00][Step 1/2] Starting: cmd /c npm install
[00:00:00][Step 1/2] in directory: F:\BuildAgent\work\abc13213
[00:00:00][Step 1/2] npm install (3s)
[00:00:00][npm install] npm ERR! git fetch -a origin (https://git@bitbucket.org/team/repo.git) remote: Invalid username or password. If you log in via a third party service you must ensure you have an account password set in your account profile.
[00:00:00][npm install] npm ERR! git fetch -a origin (https://git@bitbucket.org/team/repo.git) fatal: Authentication failed for 'https://git@bitbucket.org/team/repo.git/';
[00:00:00][npm install] npm ERR! Windows_NT 6.3.9600
[00:00:00][npm install] npm ERR! argv "F:\\nodejs\\node.exe" "C:\\Users\\svc-p-teamcity\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install"
[00:00:00][npm install] npm ERR! node v6.10.2
[00:00:00][npm install] npm ERR! npm  v4.3.0
[00:00:00][npm install] npm ERR! code 128
[00:00:00][npm install]
[00:00:00][npm install] npm ERR! Command failed: git -c core.longpaths=true fetch -a origin
[00:00:00][npm install] npm ERR! remote: Invalid username or password. If you log in via a third party service you must ensure you have an account password set in your account profile.
[00:00:00][npm install] npm ERR! fatal: Authentication failed for 'https://git@bitbucket.org/team/repo.git/';
[00:00:00][npm install] npm ERR!
[00:00:00][npm install] npm ERR!
[00:00:00][npm install] npm ERR! If you need help, you may report this error at:
[00:00:00][npm install] npm ERR!     <https://github.com/npm/npm/issues>;
[00:00:00][npm install]
[00:00:00][npm install] npm ERR! Please include the following file with any support request:
[00:00:00][npm install] npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2017-06-05T19_50_00_082Z-debug.log
[00:00:00][Step 1/2] Process exited with code 1
[00:00:00][Step 1/2] Step Install npm packages (Node.js NPM) failed

Body:
You configured VCS root in the Teamcity, so before the build starts, Teamcity will automatically checkout required repository paths to the local machine.

The problem you showed in the original log is different: npm is trying to connect to bitbucket repository to install some dependencies and fails, because authorization.

To solve this issue, you have to configure SSH key for Teamcity user (user as far as I can see from your log). You can verify that it works via running the same command from the original host, where Teamcity agent sits:

git clone 'https://git@bitbucket.org/team/repo.git/'

Otherwise, you have to change the source of your dependencies: maybe you have an Artifactory instance somewhere, which doesn't require authorisation.


问:
How to still have my app run when it is suspended because of lock screen and then wake the device
I have a Windows UWP app, targeting Windows 10 Mobile for the most part. This application monitors the user's foot traffic and when they are in or out of defined geofences. I then have a web back end that uses SignalR to send position data to/from the device.

The issue is with the lock screen. Let's say that the app is started and running but the user locks the device OR the setting option for timeout to lock the screen expires and the device locks. You could hit power, swipe to unlock and see that the app is still running. However, during the time it is locked, I assume that the app is suspended?

So, I am wondering first of all, what happens to my location updates while suspended? I use these to send the position update via SignalR to my hub but also check if they are in/out of a geofence. I am doing something like this:

```<code>_geolocator = new Geolocator { ReportInterval = 0, DesiredAccuracyInMeters = 10, MovementThreshold = 4};

// Subscribe to PositionChanged event to get updated tracking positions
_geolocator.PositionChanged += OnPositionChanged;

// Subscribe to StatusChanged event to get updates of location status changes
_geolocator.StatusChanged += OnStatusChanged;
</code>```

I assume that when the lock screen has taken over and my app is suspended, I will no longer get my OnPositionChanged events? How is this handled with other things like turn by turn navigation where it will still track your location even if the app is suspended or the lock screen is on?

Also, second question is what to do with the SignalR connection? I would love to still be able to push out my location updates when the OnPositionChanged event fires like I do when the app is not suspended. Can I also do that?

I have read about the background tasks but it seems these only run at 15 minute intervals (unless I misunderstood and this is configurable). For my application, 15 minutes is far too long. The most I would want is 30 seconds or 1 minute.

By the way, yes I understand that all of this has serious implications on battery life. Let's assume that I am not concerned about battery life for this.

Thanks!

答:
The issue is with the lock screen. Let's say that the app is started and running but the user locks the device OR the setting option for timeout to lock the screen expires and the device locks. You could hit power, swipe to unlock and see that the app is still running. However, during the time it is locked, I assume that the app is suspended?

When you minimizes an app Windows waits a few seconds to see whether the user will switch back to it. If you do not switch back within this time window, and no extended execution, background task, or activity sponsored execution is active, Windows suspends the app. An app is also suspended when the lock screen appears as long as no extended execution session, etc. is active in that app. For more detail you could refer to Windows 10 universal Windows platform (UWP) app lifecycle.

I assume that when the lock screen has taken over and my app is suspended, I will no longer get my OnPositionChanged events? How is this handled with other things like turn by turn navigation where it will still track your location even if the app is suspended or the lock screen is on?

For your requirement, you could run your app while minimized with ExtendedExecutionReason.LocationTracking. For example, if you want to realize turn by turn navigation, you could refer to the following code.

Specify ExtendedExecutionReason.LocationTracking when you create an ExtendedExecutionSession if your app needs to regularly log the location from the GeoLocator. Apps for fitness tracking and navigation that need to regularly monitor the user's location and should use this reason.

For more detail you could refer to Track the user's location and App Lifecycle - Keep Apps Alive with Background Tasks and Extended Execution.

```<code>private async void StartTbTNavigationSession()
{
  using (var session = new ExtendedExecutionSession())
  {
    session.Reason = ExtendedExecutionReason.LocationTracking;
    session.Description = "Turn By Turn Navigation";
    session.Revoked += session_Revoked;
    var result = await session.RequestExtensionAsync();
    if (result == ExtendedExecutionResult.Denied
    {
      ShowUserWarning("Background location tracking not available");
    }
    // Do Navigation
    var completionTime = await DoNavigationSessionAsync(session);
  }
}
</code>```

Body:
I have a Windows UWP app, targeting Windows 10 Mobile for the most part. This application monitors the user's foot traffic and when they are in or out of defined geofences. I then have a web back end that uses SignalR to send position data to/from the device.

The issue is with the lock screen. Let's say that the app is started and running but the user locks the device OR the setting option for timeout to lock the screen expires and the device locks. You could hit power, swipe to unlock and see that the app is still running. However, during the time it is locked, I assume that the app is suspended?

So, I am wondering first of all, what happens to my location updates while suspended? I use these to send the position update via SignalR to my hub but also check if they are in/out of a geofence. I am doing something like this:

_geolocator = new Geolocator { ReportInterval = 0, DesiredAccuracyInMeters = 10, MovementThreshold = 4};

// Subscribe to PositionChanged event to get updated tracking positions
_geolocator.PositionChanged += OnPositionChanged;

// Subscribe to StatusChanged event to get updates of location status changes
_geolocator.StatusChanged += OnStatusChanged;

I assume that when the lock screen has taken over and my app is suspended, I will no longer get my OnPositionChanged events? How is this handled with other things like turn by turn navigation where it will still track your location even if the app is suspended or the lock screen is on?

Also, second question is what to do with the SignalR connection? I would love to still be able to push out my location updates when the OnPositionChanged event fires like I do when the app is not suspended. Can I also do that?

I have read about the background tasks but it seems these only run at 15 minute intervals (unless I misunderstood and this is configurable). For my application, 15 minutes is far too long. The most I would want is 30 seconds or 1 minute.

By the way, yes I understand that all of this has serious implications on battery life. Let's assume that I am not concerned about battery life for this.

Thanks!

Body:
The issue is with the lock screen. Let's say that the app is started and running but the user locks the device OR the setting option for timeout to lock the screen expires and the device locks. You could hit power, swipe to unlock and see that the app is still running. However, during the time it is locked, I assume that the app is suspended?

When you minimizes an app Windows waits a few seconds to see whether the user will switch back to it. If you do not switch back within this time window, and no extended execution, background task, or activity sponsored execution is active, Windows suspends the app. An app is also suspended when the lock screen appears as long as no extended execution session, etc. is active in that app. For more detail you could refer to Windows 10 universal Windows platform (UWP) app lifecycle.

I assume that when the lock screen has taken over and my app is suspended, I will no longer get my OnPositionChanged events? How is this handled with other things like turn by turn navigation where it will still track your location even if the app is suspended or the lock screen is on?

For your requirement, you could run your app while minimized with ExtendedExecutionReason.LocationTracking. For example, if you want to realize turn by turn navigation, you could refer to the following code.

Specify ExtendedExecutionReason.LocationTracking when you create an ExtendedExecutionSession if your app needs to regularly log the location from the GeoLocator. Apps for fitness tracking and navigation that need to regularly monitor the user's location and should use this reason.

For more detail you could refer to Track the user's location and App Lifecycle - Keep Apps Alive with Background Tasks and Extended Execution.

private async void StartTbTNavigationSession()
{
  using (var session = new ExtendedExecutionSession())
  {
    session.Reason = ExtendedExecutionReason.LocationTracking;
    session.Description = "Turn By Turn Navigation";
    session.Revoked += session_Revoked;
    var result = await session.RequestExtensionAsync();
    if (result == ExtendedExecutionResult.Denied
    {
      ShowUserWarning("Background location tracking not available");
    }
    // Do Navigation
    var completionTime = await DoNavigationSessionAsync(session);
  }
}


问:
UIViewController's view background color is not changed
I have a UIViewController that only shows a UIView at the bottom with a fixed height:

```<code>fileprivate lazy var box: UIView = {
    let box = UIView()
    box.backgroundColor = UIColor.blue
    return box
}()
</code>```

And I'd like to set a clear color to the rest of the view (self.view). I'm presenting the view controller from a navigation controller. I'm trying this:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.clear
    view.isOpaque = false

    configView()
    configConstraints()
}
</code>```

The subview is displayed in blue but the rest of the view is opaque white, I need it to be transparent to see the previous viewController's view.

What can I be missing?

答:
To have transparent Model view controller background you have to set UIViewController providesPresentationContextTransitionStyle and definesPresentationContext properties while presenting the view controller.

Example

```<code>if let vc = self.storyboard?.instantiateViewController(withIdentifier: "YOUR_VIEW_CONTROLLER_ID") {
    vc.providesPresentationContextTransitionStyle = true
    vc.definesPresentationContext = true
    vc.modalPresentationStyle=UIModalPresentationStyle.overCurrentContext
    self.present(vc, animated: true, completion: nil)
}
</code>```

Body:
I have a UIViewController that only shows a UIView at the bottom with a fixed height:

fileprivate lazy var box: UIView = {
    let box = UIView()
    box.backgroundColor = UIColor.blue
    return box
}()

And I'd like to set a clear color to the rest of the view (self.view). I'm presenting the view controller from a navigation controller. I'm trying this:

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.clear
    view.isOpaque = false

    configView()
    configConstraints()
}

The subview is displayed in blue but the rest of the view is opaque white, I need it to be transparent to see the previous viewController's view.

What can I be missing?

Body:
To have transparent Model view controller background you have to set UIViewController providesPresentationContextTransitionStyle and definesPresentationContext properties while presenting the view controller.

Example

if let vc = self.storyboard?.instantiateViewController(withIdentifier: "YOUR_VIEW_CONTROLLER_ID") {
    vc.providesPresentationContextTransitionStyle = true
    vc.definesPresentationContext = true
    vc.modalPresentationStyle=UIModalPresentationStyle.overCurrentContext
    self.present(vc, animated: true, completion: nil)
}


问:
visual studio 2015 debug in chrome opens new window then nothing
I don't really know how this happened but after a restart on my company computer which updated the antivirus program, every time I press F5 to debug in Chrome, all it does is open a new window, then does nothing. I read this thing sort of happens in 2017 but I'm using VS 2015 professional

Whats odd is that, when I debug in IE Edge & 11, Firefox and Opera, it creates a new tab and actually opens the site. In Chrome it just opens a NEW WINDOW, then nothing. Ideas anyone?

答:
If it still has this issue without debugging and other browser works well using the same web site project, I feel that it would be not the debugger tool issue.

We would think about the browser itself. If possible, please reset your VS settings, and then create a new default web site project, not add any breakpoint, debug it again after you set the Chrome as the default browser. If still no help, I suggest you uninstall and re-install this browser. Of course, please also close all third party tools in your windows.

Update:

Based on our discussions, it would be related to your Windows Environment or the browser itself, I agree with you, use other browser like Opera as your browser in debug would be a better workaround now if you could re-install your windows now. Have a nice day:)


问:
How can I shrink an image in HTML whilst maintaining its sharpness?
I have an image that I use many times. In several cases I want to shrink its size, but obviously it loses sharpness when I do this in HTML.

Is there a way to fix this? The image is located elsewhere and I can’t save it locally.

Thanks

答:
As dheerosaur states, SVG graphics can be used when you need to have the same image in multiple sizes but don't want to compromise quality.

Another thing to do is use an online service, such as Resize.co. You pass them the URL for your image file, the attributes and they take care of everything else.


问:
How to find count of second degree followers in a database as below?
```<code>Followee Follower
A        B
B        C
B        D
B        E
A        F
F        G
F        H
B        H
</code>```

how can query to find the count of 2nd degree followers of "A" which is 5 in this case?

答:
Assume the table's name is tbl.

```<code>SELECT count (distinct tbl.follower)
FROM tbl
JOIN
(SELECT distinct follower FROM tbl WHERE followee = 'A') AS tbl2
ON tbl.followee = tbl2.follower
</code>```

The answer is 5.

Body:
Followee Follower
A        B
B        C
B        D
B        E
A        F
F        G
F        H
B        H

how can query to find the count of 2nd degree followers of "A" which is 5 in this case?

Body:
Assume the table's name is tbl.

SELECT count (distinct tbl.follower)
FROM tbl
JOIN
(SELECT distinct follower FROM tbl WHERE followee = 'A') AS tbl2
ON tbl.followee = tbl2.follower

The answer is 5.


问:
Laravel - creating dynamic form with different fields
Is there a way to create a dynamic form using Laravel and MySQL? I am trying to build a form, adding to it different fields and input types such as:

text box, text area

radio buttons

checkboxes

file upload

and so on. I am thinking of something similar to gravity forms. The user would customize the form by stating which fields are mandatory, optional or not available.

What I have reach so far is creating the fields normally in the database, have another table responsible for their status as mandatory, optional or off and then displaying them accordingly.

This works normally without any issue. However I am trying to make it more dynamic by defining some sort of generic way to create future forms without the need to create a field for each in the database. Bear in mind that the fields now are just text box.

Would MySQL help doing such forms or would I need to use something like MongoDB?

答:
The very nature of MySQL is static: you store stuff, persistently ;-)

If I get this right you want users to create a form, using a form that can have any amount of inputs and types, and then store it for later use.

My advice: use VueJS for the dynamic form - it's perfect for something like this! Then, when the user has created the form, either save the full HTML as an escaped blob/text in a single column or use a custom JS object that saves all the chosen options. Something like this:

```<code>{
    field1: {
        type: text,
        placeholder: name,
        value: '',
    },
    field2: {
        type: textarea,
        placeholder: 'address',
        style: 'width: 50%'
    }
}
</code>```

etc.

That way it's easy to retrieve and use (a la Gravity Forms) + with a bit of work you can even have it load again into your custom VueJS form wizard so that the user can edit it later.

Body:
The very nature of MySQL is static: you store stuff, persistently ;-)

If I get this right you want users to create a form, using a form that can have any amount of inputs and types, and then store it for later use.

My advice: use VueJS for the dynamic form - it's perfect for something like this! Then, when the user has created the form, either save the full HTML as an escaped blob/text in a single column or use a custom JS object that saves all the chosen options. Something like this:

{
    field1: {
        type: text,
        placeholder: name,
        value: '',
    },
    field2: {
        type: textarea,
        placeholder: 'address',
        style: 'width: 50%'
    }
}

etc.

That way it's easy to retrieve and use (a la Gravity Forms) + with a bit of work you can even have it load again into your custom VueJS form wizard so that the user can edit it later.


问:
sql query appears in the outpout of spool command(file.txt)
i want to save the result of a query using spool command.
But i got the query and its output in the result file (result.txt)

```<code> spool "result.txt"
 select * from table;
 spool off
</code>```

how can i remove the query from the file result.txt?

答:
You need to add the following set command:

```<code>  set termout off
</code>```

If you store the complete script in a script file (for instance getData.sql) and then run it from SQL Plus with the following command you will have the results wanted.

```<code>@getData.sql
</code>```

Note that typing these commands directly in SQL Plus will cause the select statement to be in the file, even with the set parameter.

Body:
i want to save the result of a query using spool command.
But i got the query and its output in the result file (result.txt)

 spool "result.txt"
 select * from table;
 spool off

how can i remove the query from the file result.txt?

Body:
You need to add the following set command:

  set termout off

If you store the complete script in a script file (for instance getData.sql) and then run it from SQL Plus with the following command you will have the results wanted.

@getData.sql

Note that typing these commands directly in SQL Plus will cause the select statement to be in the file, even with the set parameter.


问:
How To Get Hidden TD Value when i click on a TR
im trying to make a task manger based on web system that can monitor tasks at work , im using html and php .
im trying to show all the tasks in table and when i click on a task (row) i want to get a hidden td value (id of task) and send it as arg to another page for more information about the task .
i searched the web how can i do that , but i didnt realy understand how to do it with my table .
here is my table code

```<code>                   <table id="thickets_show">
                    <tr id="show_ticket_table_header">
                        <td>Work Week</td>
                        <td>Task Submited Date</td>
                        <td>Task Submited Time</td>
                        <td>Task</td>
                        <td>Project</td>
                        <td>Task Owner</td>
                        <td>Task Assigend to</td>
                        <td>Priority</td>
                        <td>Status</td>
                        <td>Task Total Work Time</td>
                        <td>Task Due Date</td>
                        <td>Task Finish Date</td>
                        <td>Team</td>
                    </tr>';
                    foreach ($tasks as $key => $value) {
                        if ($value['ticket_status']=="done")
                            echo '<tr id="done_ticket" >';
                        elseif ($value['ticket_priority']=="high")
                             echo '<tr id="high_ticket" class="ticket_raw">';
                        else
                            echo '<tr class="ticket_raw">';
                        echo '
                                <td>
                                    '.$value['work_week'].'
                                </td>
                                <td>
                                    '.$value['ticket_date'].'
                                </td>
                                <td>
                                    '.$value['ticket_time_submit'].'
                                </td>
                                <td>
                                    '.$value['ticket_request'].'
                                </td>
                                <td>
                                    '.$value['ticket_project'].'
                                </td>
                                <td>
                                    '.$value['ticket_onwer'].'
                                </td>
                                <td>
                                    '.$value['ticket_assigned_user'].'
                                </td>
                                <td>
                                    '.$value['ticket_priority'].'
                                </td>
                                <td>
                                    '.$value['ticket_status'].'
                                </td>
                                <td>
                                    '.$value['ticket_worktime'].'
                                </td>
                                <td>
                                    '.$value['ticket_due_date'].'
                                </td>
                                <td>
                                    '.$value['ticket_finish_date'].'
                                </td>
                                <td>
                                    '.$value['team'].'
                                </td>
                                <td style="display:none;" id="ticket_id class="divOne">
                                    '.$value['id'].'
                                </td>
                              </tr>
</code>```

this is the function that im using

```<code>$(function(){
            $(".ticket_raw" ).on(\'click\',function(e){
                e.preventDefault();
                var id = $(this).attr("#ticket_id");
                alert(id);
            });
        });
</code>```

答:
There is a small issue to correct, then you can make this work nice and easily:

echo '
'; is invalid - if you're creating multiple elements in a loop like this, you can't give them all the same "id", that's illegal in the HTML specification. You have to use classes instead.

Rewrite it slightly like this:

```<code>foreach ($tasks as $key => $value) {
  echo '<tr data-id="'.$value['id'].'" class="ticket ';
  if ($value['ticket_status']=="done")
    echo 'done_ticket';
  elseif ($value['ticket_priority']=="high")
     echo 'high_ticket ticket_raw';
  else
    echo 'ticket_raw';
  echo '">';
  echo '
    <td>
    //etc...
</code>```

Note the extra class "ticket" on the tr element, regardless of the status, and the "data-id" attribute containing the ID (instead of a hidden field).

Now, you can write some jQuery to get the ticket ID:

```<code>$(".ticket").click(function(event) {
  var id = $(this).data("id"); //gets the data-id value from the clicked tr
  window.location.href = "ticket.php?id=" + id; //example URL to redirect to, passing the ID from the tr
});
</code>```

Lastly you can delete this code:

```<code><td style="display:none;" id="ticket_id class="divOne">
  '.$value['id'].'
</td>
</code>```

Body:
im trying to make a task manger based on web system that can monitor tasks at work , im using html and php .
im trying to show all the tasks in table and when i click on a task (row) i want to get a hidden td value (id of task) and send it as arg to another page for more information about the task .
i searched the web how can i do that , but i didnt realy understand how to do it with my table .
here is my table code

                        Work Week
                        Task Submited Date
                        Task Submited Time
                        Task
                        Project
                        Task Owner
                        Task Assigend to
                        Priority
                        Status
                        Task Total Work Time
                        Task Due Date
                        Task Finish Date
                        Team

';
                    foreach ($tasks as $key => $value) {
                        if ($value['ticket_status']=="done")
                            echo '
';
                        elseif ($value['ticket_priority']=="high")
                             echo '
';
                        else
                            echo '
';
                        echo '

                                    '.$value['work_week'].'

                                    '.$value['ticket_date'].'

                                    '.$value['ticket_time_submit'].'

                                    '.$value['ticket_request'].'

                                    '.$value['ticket_project'].'

                                    '.$value['ticket_onwer'].'

                                    '.$value['ticket_assigned_user'].'

                                    '.$value['ticket_priority'].'

                                    '.$value['ticket_status'].'

                                    '.$value['ticket_worktime'].'

                                    '.$value['ticket_due_date'].'

                                    '.$value['ticket_finish_date'].'

                                    '.$value['team'].'

                                    '.$value['id'].'

this is the function that im using

$(function(){
            $(".ticket_raw" ).on(\'click\',function(e){
                e.preventDefault();
                var id = $(this).attr("#ticket_id");
                alert(id);
            });
        });

Body:
There is a small issue to correct, then you can make this work nice and easily:

echo '<tr id="done_ticket" >'; is invalid - if you're creating multiple elements in a loop like this, you can't give them all the same "id", that's illegal in the HTML specification. You have to use classes instead.

Rewrite it slightly like this:

foreach ($tasks as $key => $value) {
  echo '<tr data-id="'.$value['id'].'" class="ticket ';
  if ($value['ticket_status']=="done")
    echo 'done_ticket';
  elseif ($value['ticket_priority']=="high")
     echo 'high_ticket ticket_raw';
  else
    echo 'ticket_raw';
  echo '">';
  echo '
    <td>
    //etc...

Note the extra class "ticket" on the tr element, regardless of the status, and the "data-id" attribute containing the ID (instead of a hidden field).

Now, you can write some jQuery to get the ticket ID:

$(".ticket").click(function(event) {
  var id = $(this).data("id"); //gets the data-id value from the clicked tr
  window.location.href = "ticket.php?id=" + id; //example URL to redirect to, passing the ID from the tr
});

Lastly you can delete this code:

<td style="display:none;" id="ticket_id class="divOne">
  '.$value['id'].'
</td>


问:
How to calculate the time span in Tcl using clock commands
I need to calculate the time difference between two periods of a day in a 24:00 hr format clock using Tcl.

Let's say my start time is 06:30:00 in the morning and end time is 18:30:00 in the evening. I've tried the following in using Active Tcl 8.5 and 8.6 in windows.

```<code>set morn [clock scan 06:30:00 -format %H:%M:%S]
set even [clock scan 18:30:00 -format %H:%M:%S]
set diff [clock format [expr $even - $morn ] -format %H:%M:%S]
</code>```

The answer is supposed to be 12:00:00 which is the actual difference but, I get the answer as 17:30:00 which is totally confusing.

I presume that the GMT time difference of 05:30:00 is being added to the difference as I'm in a GMT+5:30 time zone (IST).

How do I get the exact difference?

答:
I don't understand why you don't use the -timezone option ?
I'm in TZ=CET so for me the answer is 13:00:00

If I add the "-timezone UTC" option I get the right answer:

```<code>set morn [clock scan 06:30:00 -format %T]
puts "morn = $morn"

set even [clock scan 18:30:00 -format %T]
puts "even = $even"

set diff [clock format [expr $even - $morn ] -format "%Y:%m:%d %T"]
puts "diff = $diff"

puts "difference = [expr $even - $morn]"

puts "with -timezone UTC = [clock format [expr $even - $morn ] -timezone UTC -format %T]"
</code>```

The display is

```<code>morn = 1496723400
even = 1496766600
diff = 1970:01:01 13:00:00
difference = 43200
with -timezone UTC = 12:00:00
</code>```

Body:
I need to calculate the time difference between two periods of a day in a 24:00 hr format clock using Tcl.

Let's say my start time is 06:30:00 in the morning and end time is 18:30:00 in the evening. I've tried the following in using Active Tcl 8.5 and 8.6 in windows.

set morn [clock scan 06:30:00 -format %H:%M:%S]
set even [clock scan 18:30:00 -format %H:%M:%S]
set diff [clock format [expr $even - $morn ] -format %H:%M:%S]

The answer is supposed to be 12:00:00 which is the actual difference but, I get the answer as 17:30:00 which is totally confusing.

I presume that the GMT time difference of 05:30:00 is being added to the difference as I'm in a GMT+5:30 time zone (IST).

How do I get the exact difference?

Body:
I don't understand why you don't use the -timezone option ?
I'm in TZ=CET so for me the answer is 13:00:00

If I add the "-timezone UTC" option I get the right answer:

set morn [clock scan 06:30:00 -format %T]
puts "morn = $morn"

set even [clock scan 18:30:00 -format %T]
puts "even = $even"

set diff [clock format [expr $even - $morn ] -format "%Y:%m:%d %T"]
puts "diff = $diff"

puts "difference = [expr $even - $morn]"

puts "with -timezone UTC = [clock format [expr $even - $morn ] -timezone UTC -format %T]"

The display is

morn = 1496723400
even = 1496766600
diff = 1970:01:01 13:00:00
difference = 43200
with -timezone UTC = 12:00:00


问:
Python 3 - Get n greatest values in dict
I have a dict, with strings as keys and lists as values and want to find the n keys with the longest lists (length).

How could I approach this problem?

答:
From here : I see you can build a sorted list from a dictionnary. That may not be the best way to do in terms of complexity.

here's with python 3 :

```<code>myDict = {'first':[1, 2, 3], 'second':[117, 2], 'third':[8, 37, 3, 4], 'fourth':[1], 'fifth': [3,2,3]}
for i in sorted(myDict, key = lambda x: len(myDict[x]), reverse=True):
    print i, len(myDict[i])
</code>```

and it prints out :

```<code>third 4
fifth 3
first 3
second 2
fourth 1
</code>```

I don't know if that's what youre looking for, post more details for a more detailed answer.

Body:
From here : I see you can build a sorted list from a dictionnary. That may not be the best way to do in terms of complexity.

here's with python 3 :

myDict = {'first':[1, 2, 3], 'second':[117, 2], 'third':[8, 37, 3, 4], 'fourth':[1], 'fifth': [3,2,3]}
for i in sorted(myDict, key = lambda x: len(myDict[x]), reverse=True):
    print i, len(myDict[i])

and it prints out :

third 4
fifth 3
first 3
second 2
fourth 1

I don't know if that's what youre looking for, post more details for a more detailed answer.


问:
Why does InsertText from UITextInput breaks keyboard suggestions?
So we recently had an issue with our Keyboard extension showing wrong suggestions in the accompanying app. We found out that the text returned from context (super.textDocumentProxy.documentContextBeforeInput) was all wrong and since its a build in apple component something must go wrong with text insertion. We had following implementation for inserting text:

```<code>    if (replaceRange.length > 0) {
        [self.textView.textStorage replaceCharactersInRange:replaceRange withString:selectedWord];
        [textView setSelectedRange:NSMakeRange(newLocation, 0)];  //Place cursor after inserted word
    } else {
        [self.textView insertText:selectedWord];
    }
</code>```

Would return something like:

There. . .

While the real text would be something like:

There it was. It was a little test. Test of everything.

答:
The issue was found to be with insertText apparently it will properly insert text but the Keyboard context will not be able to read the inserted text. Now the fix was simply to use the replaceCharactersInRange for both insertions (meaning no if / else clause):

```<code>[self.textView.textStorage replaceCharactersInRange:replaceRange withString:selectedWord];
        [textView setSelectedRange:NSMakeRange(newLocation, 0)];  //Place cursor after inserted word
</code>```

This solved the issue and has made us conclude that insertText doesn't work as intended. Note that this will only be an issue if suggestions are to be used in the text field.

Body:
So we recently had an issue with our Keyboard extension showing wrong suggestions in the accompanying app. We found out that the text returned from context (super.textDocumentProxy.documentContextBeforeInput) was all wrong and since its a build in apple component something must go wrong with text insertion. We had following implementation for inserting text:

    if (replaceRange.length > 0) {
        [self.textView.textStorage replaceCharactersInRange:replaceRange withString:selectedWord];
        [textView setSelectedRange:NSMakeRange(newLocation, 0)];  //Place cursor after inserted word
    } else {
        [self.textView insertText:selectedWord];
    }

Would return something like:

There. . .

While the real text would be something like:

There it was. It was a little test. Test of everything.

Body:
The issue was found to be with insertText apparently it will properly insert text but the Keyboard context will not be able to read the inserted text. Now the fix was simply to use the replaceCharactersInRange for both insertions (meaning no if / else clause):

[self.textView.textStorage replaceCharactersInRange:replaceRange withString:selectedWord];
        [textView setSelectedRange:NSMakeRange(newLocation, 0)];  //Place cursor after inserted word

This solved the issue and has made us conclude that insertText doesn't work as intended. Note that this will only be an issue if suggestions are to be used in the text field.


问:
How do I get sourcemap files to output to my build folder?
I have a minimal webpack1 config that I've whittled a massive project down to just to reproduce this.

When I run my config with webpack-dev-server it works just fine, except the file is only accessible at localhost:port/bundle.js.map not in my local projects dist folder.

link to repo with instructions: https://github.com/rublev/webpack-nosourcemaps

webpack.config.base.js

```<code>module.exports = {
    output: {
        path: path.join(process.cwd(), '/dist'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    resolve: {
        root: path.join(__dirname, ''),
        modulesDirectories: [
            'node_modules',
            'app'
        ],
        extensions: ['', '.html', '.js'] // removing '' makes everything explode
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'webpack-sourcemap',
            template: 'app/index.html'
        })
    ],
    module: {
        loaders: [],
    }
}
</code>```

webpack.config.production.js

```<code>var config = require('./webpack.config.base.js')

config.devtool = 'source-map'

if (process.env.NODE_ENV !== 'test') {
    config.entry = {
        main: path.join(process.cwd(), '/app/') + 'app.js',
        vendor: [
            'react',
            'react-dom'
        ]
    }
}

config.output = {
    path: path.join(process.cwd(), '/dist'),
    pathInfo: true,
    publicPath: '/',
    filename: 'bundle.js'
}

config.module.loaders = config.module.loaders.concat([
    {
        test: /\.js$/,
        loaders: ['babel'],
        exclude: /node_modules/
    }
])

config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        filename: 'vendor.js'
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
            warnings: false
        }
    }),
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('production')
        }
    })
])

module.exports = config
</code>```

答:
You run this code

NODE_ENV=production webpack-dev-server ...

add -d flag like this

NODE_ENV=production webpack-dev-server -d...

Development shortcut -d

Equals to --debug --devtool source-map --output-pathinfo

Body:
I have a minimal webpack1 config that I've whittled a massive project down to just to reproduce this.

When I run my config with webpack-dev-server it works just fine, except the file is only accessible at localhost:port/bundle.js.map not in my local projects dist folder.

link to repo with instructions: https://github.com/rublev/webpack-nosourcemaps

webpack.config.base.js

module.exports = {
    output: {
        path: path.join(process.cwd(), '/dist'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    resolve: {
        root: path.join(__dirname, ''),
        modulesDirectories: [
            'node_modules',
            'app'
        ],
        extensions: ['', '.html', '.js'] // removing '' makes everything explode
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'webpack-sourcemap',
            template: 'app/index.html'
        })
    ],
    module: {
        loaders: [],
    }
}

webpack.config.production.js

var config = require('./webpack.config.base.js')

config.devtool = 'source-map'

if (process.env.NODE_ENV !== 'test') {
    config.entry = {
        main: path.join(process.cwd(), '/app/') + 'app.js',
        vendor: [
            'react',
            'react-dom'
        ]
    }
}

config.output = {
    path: path.join(process.cwd(), '/dist'),
    pathInfo: true,
    publicPath: '/',
    filename: 'bundle.js'
}

config.module.loaders = config.module.loaders.concat([
    {
        test: /\.js$/,
        loaders: ['babel'],
        exclude: /node_modules/
    }
])

config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        filename: 'vendor.js'
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
            warnings: false
        }
    }),
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('production')
        }
    })
])

module.exports = config


问:
My Configuration file is unable to find the hibernate mapping
enter image description hereThis is my project

Please check my configuration file and mapping file, the config file is unable to locate the mapping resource even though they are in the same folder.

My hibernate Config file

[>

```<code><!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>

<!-- Related to the connection START -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:3306:XE</property>
<property name="connection.user">root</property>
<property name="connection.password">maherukh</property>
<!-- Related to the connection END -->

<!-- Related to hibernate properties START -->
<property name="show_sql">true </property>
<property name="dialet">org.hibernate.dialect.OracleDialect </property>
<property name="hbm2ddl.auto">update </property>
<!-- Related to hibernate properties END -->

<!-- Related to mapping START -->
<mapping resource="Product.hbm.xml" />
<!-- Related to the mapping END -->

</session-factory>
</hibernate-configuration>][2]
</code>```

My hibernate Mapping file

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Product" table="PRODUCTS">

<id name="productId" column="pid"  >
<generator class="assigned" />
</id>

<property name="proName" column="pname" />
<property name="price"/>

</class>
</hibernate-mapping>
</code>```

答:
Have you tried with : <mapping resource="str/Product.hbm.xml" />
By default your classpath is src so hibernate will probably search your mapping files in src

Body:
enter image description hereThis is my project

Please check my configuration file and mapping file, the config file is unable to locate the mapping resource even though they are in the same folder.

My hibernate Config file

[>

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:3306:XE</property>
<property name="connection.user">root</property>
<property name="connection.password">maherukh</property>

<property name="show_sql">true </property>
<property name="dialet">org.hibernate.dialect.OracleDialect </property>
<property name="hbm2ddl.auto">update </property>

<mapping resource="Product.hbm.xml" />

</session-factory>
</hibernate-configuration>][2]

My hibernate Mapping file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Product" table="PRODUCTS">

<id name="productId" column="pid"  >
<generator class="assigned" />
</id>

<property name="proName" column="pname" />
<property name="price"/>

</class>
</hibernate-mapping>


问:
.appendTo not working
I am trying to count how many items there are in a list and then show the result in a div. But no matter what I do the code below crashes my wordpress site.</p>

```<code>$(document).ready(function(){
  var myfunction = $(".group_users-ul > li").size();
  $(myfunction).appendTo("#result");
});
</code>```

答:
write this way</p>

```<code>jQuery(document).ready(function($) {

  var myfunction = $(".group_users-ul > li").size();
  $(myfunction).appendTo("#result");

} );
</code>```

Title: .appendTo not working

Body:
I am trying to count how many items there are in a list and then show the result in a div. But no matter what I do the code below crashes my wordpress site.

$(document).ready(function(){
  var myfunction = $(".group_users-ul > li").size();
  $(myfunction).appendTo("#result");
});

Body:
write this way

jQuery(document).ready(function($) {

  var myfunction = $(".group_users-ul > li").size();
  $(myfunction).appendTo("#result");

} );


问:
String concatenation without strcat in C
I am having trouble concatenating strings in C, without strcat library function. Here is my code

```<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}
</code>```

I made corrections to the code. This is working. Now can I do it without strcpy?

答:
You cannot safely write into those arrays, since you have not made sure that enough space is available. If you use malloc() to allocate space, you can't then overwrite the pointer by assigning to string literal. You need to use strcpy() to copy a string into the newly allocated buffers, in that case.

Also, the length of a string in C is computed by the strlen() function, not length() that you're using.

When concatenating, you need to terminate at the proper location, which your code doesn't seem to be doing.

Here's how I would re-implement strcat(), if needed for some reason:

```<code>char * my_strcat(char *out, const char *in)
{
  char *anchor = out;
  size_t olen;

  if(out == NULL || in == NULL)
    return NULL;

  olen = strlen(out);
  out += olen;
  while(*out++ = *in++)
    ;
  return anchor;
}
</code>```

Note that this is just as bad as strcat() when it comes to buffer overruns, since it doesn't support limiting the space used in the output, it just assumes that there is enough space available.

Body:
I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}

I made corrections to the code. This is working. Now can I do it without strcpy?

Body:
You cannot safely write into those arrays, since you have not made sure that enough space is available. If you use malloc() to allocate space, you can't then overwrite the pointer by assigning to string literal. You need to use strcpy() to copy a string into the newly allocated buffers, in that case.

Also, the length of a string in C is computed by the strlen() function, not length() that you're using.

When concatenating, you need to terminate at the proper location, which your code doesn't seem to be doing.

Here's how I would re-implement strcat(), if needed for some reason:

char * my_strcat(char *out, const char *in)
{
  char *anchor = out;
  size_t olen;

  if(out == NULL || in == NULL)
    return NULL;

  olen = strlen(out);
  out += olen;
  while(*out++ = *in++)
    ;
  return anchor;
}

Note that this is just as bad as strcat() when it comes to buffer overruns, since it doesn't support limiting the space used in the output, it just assumes that there is enough space available.


问:
fatal: unable to stat "file": Permission denied
I searched and tried answer but problem didn't solve, I git init into android project and after making first push, I changed alot of things removed added new files and fonts (I don't remember if i git added during this) now when I ready to pus i ran command git status I see files in red as untract files, then I ran git add . but Im getting this error:

```<code>warning: LF will be replaced by CRLF in app/app.iml.
The file will have its original line endings in your working directory.
fatal: unable to stat 'app/src/main/res/drawable/slide_thre.jpg':
Permission denied
</code>```

the file slide_thre.jpg I deleted way before git add wen I was working but its still showing this error, I dont know if its cached

I tried closing IDE before git add and tried other solution but didn't work

">

答:
Try closing any programs that have the folder open, such as editors,
  explorer windows, command prompts, and FTP programs. This always fixes
  the issue for me on Windows.

You can also try "invalidate & restart" your IDE, that should clean the caches.
Lastly, try disabling the virus checker just to see if it would let you through then.

SO Post

Body:
I searched and tried answer but problem didn't solve, I git init into android project and after making first push, I changed alot of things removed added new files and fonts (I don't remember if i git added during this) now when I ready to pus i ran command git status I see files in red as untract files, then I ran git add . but Im getting this error:

warning: LF will be replaced by CRLF in app/app.iml.
The file will have its original line endings in your working directory.
fatal: unable to stat 'app/src/main/res/drawable/slide_thre.jpg':
Permission denied

the file slide_thre.jpg I deleted way before git add wen I was working but its still showing this error, I dont know if its cached

I tried closing IDE before git add and tried other solution but didn't work

">


问:
Can we customize CCAVENUE payment page?
Can we customize CCAVENUE payment page where??is that possible?? I'm using INDIPAY package in laravel 5.3.

Please check attached Image for more details.

答: No you cannot. These pages are hosted by the payment processor and not in your application. All the package does is redirect to the payment processor with the appropriate payment data from your application. Unless the payment processor allows for customization of their payment page, this cannot be achieved.</p>

Title: Can we customize CCAVENUE payment page?


问:
ValueError: The given username must be set
I'm trying register a user in my project, but when I try to do it I get next error:

ValueError: The given username must be set

In my project I'm using Django 1.11 and AngularJS 1.6

View.py

```<code>def registrarCliente(request):
    if request.method=='POST':
        usuariosfinales=[]
        nombre=request.POST.get('nombre')
        email=request.POST.get('email')
        password=request.POST.get('password')

        user=User.objects.create_user(email, email, password)
        user.save()

        usermodelo=Usuario(usuario=user, nombre=nombre)
        usermodelo.save()

        userfinal=authenticate(username=email, password=password)
        login(request, userfinal)

        usuariosfinales.append(userfinal)

        data=serializers.serialize('json', usuariosfinales)

        return HttpResponse(data, content_type="application/json")

    return render (request, "login/login.html")
</code>```

login.html

```<code><div class="login-wrap" id="login" ng-app="appLogin" ng-controller="conLogin">
  <div class="login-right striped-bg" ng-show="Registro">
    <div class="login-form">
      <div class="heading">
        ¡Registrate!
      </div>
      <div class="input">

        {% csrf_token %}

        <div class="login-input-group spacer-field">
          <span class="login-input-group-addon">
            <i class="fa fa-user fa-fw"></i>
          </span>
          <input type="text" class="form-control" name="nombre" placeholder="Nombre" ng-model="user.nombre">
        </div>
        <div class="login-input-group spacer-field">
          <span class="login-input-group-addon">
            <i class="fa fa-at fa-fw"></i>
          </span>
          <input type="email" class="form-control" name="email" placeholder="Correo electrónico" ng-model="user.email">
        </div>
        <div class="login-input-group spacer-field">
          <span class="login-input-group-addon">
            <i class="fa fa-key fa-fw"></i>
          </span>
          <input type="password" class="form-control" name="password" placeholder="Contraseña" ng-model="user.password">
        </div>
        <div class="login-input-group">
          <span class="login-input-group-addon">
            <i class="fa fa-key fa-fw"></i>
          </span>
          <input type="password" class="form-control" name="password2" placeholder="Repetir contraseña">
        </div>

        <button class="btn btn-default btn-lg submit" type="submit" ng-click="registrar()">Registrarme</button>
      </div>
    </div>
  </div>
</div>
</code>```

appLogin.js

```<code>(function(angular) {

// body...
angular
    .module('appLogin', [])
    .controller('conLogin', ['$scope', '$http', function($scope, $http){
        //Registro de usuario
        $scope.user = {nombre:'', email:'', password:''};

        $scope.registrar = function(email, password){
            $http({method:'POST',
                url:'/registro/',
                data:{nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password}
            }).then(
                function(response2){
                    window.location.href='';
                },function(response2){
                    $scope.user = response2.data || 'Request failed';
                }
            );
        }

        $scope.Ingreso = true;
        $scope.Registro = false;

        $scope.cambioRegistro = function(){
            $scope.Ingreso = false;
            $scope.Registro = true;
        }

        $scope.cambioIngreso = function(){
            $scope.Ingreso = true;
            $scope.Registro = false;
        }
    }])

var my_app = angular
    .module('appLogin').config(
        function($interpolateProvider, $httpProvider) {
            $interpolateProvider.startSymbol('{$');
            $interpolateProvider.endSymbol('$}');
            $httpProvider.defaults.xsrfCookieName = 'csrftoken';
            $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
            $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
            $httpProvider.defaults.withCredentials = true;
            $httpProvider.defaults.cache = true;
        }
    );

})(window.angular);
</code>```

The debug page says me that my error is in:

user=User.objects.create_user(email, email, password)

But I don't understand why.

答:
I was sending data just like this:

```<code>data:{nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password}
</code>```

There I wasn't using $.param jquery function because I don't had jquery, I imported jquery, I changed the code above for a code with $.param just like this:

```<code>data:$.param({nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password})
</code>```

And finally works!

The final AngularJS code is:

appLogin.js

```<code>angular
    .module('appLogin', [])
    .controller('conLogin', ['$scope', '$http', function($scope, $http){
        //Registro de usuario
        $scope.user = {nombre:'', email:'', password:''};

        $scope.registrar = function(email, password){
            $http({method:'POST',
                url:'/cliente/registro/',
                data:$.param({nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password})
            }).then(
                function(response2){
                    window.location.href='';
                },function(response2){
                    $scope.user = response2.data || 'Request failed';
                }
            );
        }
    }])
</code>```

Body:
I'm trying register a user in my project, but when I try to do it I get next error:

ValueError: The given username must be set

In my project I'm using Django 1.11 and AngularJS 1.6

View.py

def registrarCliente(request):
    if request.method=='POST':
        usuariosfinales=[]
        nombre=request.POST.get('nombre')
        email=request.POST.get('email')
        password=request.POST.get('password')

        user=User.objects.create_user(email, email, password)
        user.save()

        usermodelo=Usuario(usuario=user, nombre=nombre)
        usermodelo.save()

        userfinal=authenticate(username=email, password=password)
        login(request, userfinal)

        usuariosfinales.append(userfinal)

        data=serializers.serialize('json', usuariosfinales)

        return HttpResponse(data, content_type="application/json")

    return render (request, "login/login.html")

login.html

        ¡Registrate!

        {% csrf_token %}

          <input type="text" class="form-control" name="nombre" placeholder="Nombre" ng-model="user.nombre">

          <input type="email" class="form-control" name="email" placeholder="Correo electrónico" ng-model="user.email">

          <input type="password" class="form-control" name="password" placeholder="Contraseña" ng-model="user.password">

          <input type="password" class="form-control" name="password2" placeholder="Repetir contraseña">

        <button class="btn btn-default btn-lg submit" type="submit" ng-click="registrar()">Registrarme</button>

appLogin.js

(function(angular) {

// body...
angular
    .module('appLogin', [])
    .controller('conLogin', ['$scope', '$http', function($scope, $http){
        //Registro de usuario
        $scope.user = {nombre:'', email:'', password:''};

        $scope.registrar = function(email, password){
            $http({method:'POST',
                url:'/registro/',
                data:{nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password}
            }).then(
                function(response2){
                    window.location.href='';
                },function(response2){
                    $scope.user = response2.data || 'Request failed';
                }
            );
        }

        $scope.Ingreso = true;
        $scope.Registro = false;

        $scope.cambioRegistro = function(){
            $scope.Ingreso = false;
            $scope.Registro = true;
        }

        $scope.cambioIngreso = function(){
            $scope.Ingreso = true;
            $scope.Registro = false;
        }
    }])

var my_app = angular
    .module('appLogin').config(
        function($interpolateProvider, $httpProvider) {
            $interpolateProvider.startSymbol('{$');
            $interpolateProvider.endSymbol('$}');
            $httpProvider.defaults.xsrfCookieName = 'csrftoken';
            $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
            $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
            $httpProvider.defaults.withCredentials = true;
            $httpProvider.defaults.cache = true;
        }
    );

})(window.angular);

The debug page says me that my error is in:

user=User.objects.create_user(email, email, password)

But I don't understand why.

Body:
I was sending data just like this:

data:{nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password}

There I wasn't using $.param jquery function because I don't had jquery, I imported jquery, I changed the code above for a code with $.param just like this:

data:$.param({nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password})

And finally works!

The final AngularJS code is:

appLogin.js

angular
    .module('appLogin', [])
    .controller('conLogin', ['$scope', '$http', function($scope, $http){
        //Registro de usuario
        $scope.user = {nombre:'', email:'', password:''};

        $scope.registrar = function(email, password){
            $http({method:'POST',
                url:'/cliente/registro/',
                data:$.param({nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password})
            }).then(
                function(response2){
                    window.location.href='';
                },function(response2){
                    $scope.user = response2.data || 'Request failed';
                }
            );
        }
    }])


问:
need someone to look at this javascript code i dont know how to solve this
I've created a Rock Paper scissors game using JavaScript, I want to show an image of element that won in the end.

For example:

If rock wins: show a image/jpg of a rock

If paper wins: show a image/jpg of a paper

Below is the code:

```<code>var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
}
else if (computerChoice <= 0.67) {
    computerChoice = "paper";
}
else {
    computerChoice = "scissors";
}
//console.log("Computer chooses: " + computerChoice);
var compare = function (choice1, choice2) {
    if (choice1 === choice2) {
        return "The result is a tie!" + " " + "Lets play again.";
    }
    else if (choice1 === "rock") {

        if (choice2 === "scissors") {
            return "rock wins" + "<br>" + "You beat the computer, nice job!";
        }
        else {
            return "paper wins" + "<br>" + "Your really smart computer beat you.";
        }
    }
    else if (choice1 === "paper") {

        if (choice2 === "rock") {
            return "paper wins" + "<br>" + "You beat the computer, nice job!";
        }
        else {
            return "scissors wins" + "<br>" + "Your really smart computer beat you.";
        }
    }

    else if (choice1 === "scissors") {

        if (choice2 === "rock") {
            return "rock wins" + "<br>" + "Your really smart computer beat you.";
        }
        else {
            return "scissors win" + "<br>" + "You beat the computer, nice job!";
        }
    }

} //closes compare function
document.write("Computer chose: " + computerChoice + "<br>");
document.write(compare(userChoice, computerChoice));
</code>```

答:
Instead of using

```<code>computerChoice = Math.random()
</code>```

Use math.floor()

```<code>computerChoice = Math.floor((Math.random() * 3) + 1)
</code>```

Now use this to tell what the computer meant:

```<code>if(computerChoice == '1') { computerChoice = 'stone' };
if(computerChoice == '2') { computerChoice = 'paper' };
if(computerChoice == '3') { computerChoice = 'scissors' };
</code>```

Body:
I've created a Rock Paper scissors game using JavaScript, I want to show an image of element that won in the end.

For example:

If rock wins: show a image/jpg of a rock

If paper wins: show a image/jpg of a paper

Below is the code:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
}
else if (computerChoice <= 0.67) {
    computerChoice = "paper";
}
else {
    computerChoice = "scissors";
}
//console.log("Computer chooses: " + computerChoice);
var compare = function (choice1, choice2) {
    if (choice1 === choice2) {
        return "The result is a tie!" + " " + "Lets play again.";
    }
    else if (choice1 === "rock") {

        if (choice2 === "scissors") {
            return "rock wins" + "
" + "You beat the computer, nice job!";
        }
        else {
            return "paper wins" + "
" + "Your really smart computer beat you.";
        }
    }
    else if (choice1 === "paper") {

        if (choice2 === "rock") {
            return "paper wins" + "
" + "You beat the computer, nice job!";
        }
        else {
            return "scissors wins" + "
" + "Your really smart computer beat you.";
        }
    }

    else if (choice1 === "scissors") {

        if (choice2 === "rock") {
            return "rock wins" + "
" + "Your really smart computer beat you.";
        }
        else {
            return "scissors win" + "
" + "You beat the computer, nice job!";
        }
    }

} //closes compare function
document.write("Computer chose: " + computerChoice + "
");
document.write(compare(userChoice, computerChoice));

Body:
Instead of using

computerChoice = Math.random()

Use math.floor()

computerChoice = Math.floor((Math.random() * 3) + 1)

Now use this to tell what the computer meant:

if(computerChoice == '1') { computerChoice = 'stone' };
if(computerChoice == '2') { computerChoice = 'paper' };
if(computerChoice == '3') { computerChoice = 'scissors' };


问:
What is the maximum length of a table name in Oracle?
What are the maximum length of a table name and column name in Oracle? </p>

答:
I'm working on Oracle 12c 12.1. However, doesn't seem like it allows more than 30 characters for column/table names.

Read through an oracle page which mentions 30 bytes.
https://docs.oracle.com/database/121/SQLRF/sql_elements008.htm#SQLRF00223

In 12c although the all_tab_columns do say VARCHAR2(128) for Table_Name, it does not allow more than 30 bytes name.

Found another article about 12c R2, which seems to be allowing this up to 128 characters.
https://community.oracle.com/ideas/3338

LastEditorDisplayName: Mark Brady


问:
Error: Could not find or load main class .library.path=
I am trying to run DynamoDB locally, with the instructions here:

http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html

I've downloaded the zip file, and unzipped everything into a folder.

I'm on Windows 10.

In Powershell, in that directory when I run:

java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb

I get:

Error: Could not find or load main class .library.path=..DynamoDBLocal_lib

I've read this which is very similar - closest I could find but it didn't help:
java.lang.UnsatisfiedLinkError: no sqljdbc_auth in java.library.path

I don't think the issue is that it cannot find the class, it is that it doesn't know what library.path means.

I have java installed:

C:\Dynamo> java -version
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b15)
Java HotSpot(TM) Client VM (build 25.91-b15, mixed mode)

In my PATH I have C:\ProgramData\Oracle\Java\javapath which I think is correct.

Do I need the JDK? not just JRE? Am I doing something else wrong?

I think that the path in the example may not be correct for windows, but I don't think that is the problem, I have tried dozens of different paths, but they all say the same thing.

答:
We found that PowerShell misinterprets the -Djava.library.path parameter.
Enclosing either the parameter name or the entire name & value fixed the issue in our case.

java -D"java.library.path"=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb

or

java "-Djava.library.path=./DynamoDBLocal_lib" -jar DynamoDBLocal.jar -sharedDb

The answers to this question also helped
How to pass Properties to jar from Powershell?