问:
Posted ViewModel is always NULL
My ViewModel always returns null and don't know why. Can someone look at my code and check what is wrong here and why my filled model with data from view returns to controller as null?

```<code>public class PaintballWorkerCreateViewModel
{
    public PaintballWorker PaintballWorker { get; set; }
    public PaintballWorkerHourlyRate HourlyRate { get; set; }
}
</code>```

Controller

```<code>public ActionResult Create()
{
    PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
    {
        PaintballWorker = new PaintballWorker(),
        HourlyRate = new PaintballWorkerHourlyRate()
        {
            Date = DateTime.Now
        }
    };
    return View(model);
}

[HttpPost]
[PreventSpam(DelayRequest = 20)]
[ValidateAntiForgeryToken]
public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
{
    (...)
}
</code>```

View, even added HiddenFor IDs (which aren't created in GET function in controller).

```<code>@model WerehouseProject.ViewModels.PaintballWorkerCreateViewModel

@{
    ViewBag.Title = "Utwórz pracownika";
    Layout = "~/Views/Shared/_Layout_Paintball.cshtml";
}

<h2>Dodawanie pracownika</h2>

@using (Html.BeginForm("Create", "PaintballWorkers", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.PaintballWorker.Active)
        @Html.HiddenFor(model => model.PaintballWorker.MoneyGot)
        @Html.HiddenFor(model => model.PaintballWorker.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.Date)
        @Html.HiddenFor(model => model.HourlyRate.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.PWHourlyRateID)

        <div class="form-group">
            @Html.LabelFor(model => model.PaintballWorker.Imie, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PaintballWorker.Imie, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PaintballWorker.Imie, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PaintballWorker.Nazwisko, htmlAttributes: new { @class = "control-label col-md-2" })

(...)

        <div class="form-group">
            @Html.LabelFor(model => model.HourlyRate.HourlyRate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.HourlyRate.HourlyRate, new { htmlAttributes = new { @class = "form-control", @type = "number", @min = "0.1", @step = "0.1", @value = "10" } })
                @Html.ValidationMessageFor(model => model.HourlyRate.HourlyRate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Dodaj pracownika" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<div>
@Html.ActionLink("Powrót do listy", "Index", new object { }, new { @class = "btn btn-default" })
</div>
</code>```

答:
your problem may be because of naming conflict, that is the parameter name of the post action may not be the same as the property name in your viewmodel

Kindly follow the below link:

https://forums.asp.net/t/1670962.aspx?ViewModel+in+post+action+is+null

In that it specified solution and route cause for the problem clearly.

Note : I also had the same problem long back and solved it in the same way as mentioned. Hope it will be useful for you too

thanks

Karthik

Title: Posted ViewModel is always NULL

Body:
My ViewModel always returns null and don't know why. Can someone look at my code and check what is wrong here and why my filled model with data from view returns to controller as null?

public class PaintballWorkerCreateViewModel
{
    public PaintballWorker PaintballWorker { get; set; }
    public PaintballWorkerHourlyRate HourlyRate { get; set; }
}

Controller

public ActionResult Create()
{
    PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
    {
        PaintballWorker = new PaintballWorker(),
        HourlyRate = new PaintballWorkerHourlyRate()
        {
            Date = DateTime.Now
        }
    };
    return View(model);
}

[HttpPost]
[PreventSpam(DelayRequest = 20)]
[ValidateAntiForgeryToken]
public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
{
    (...)
}

View, even added HiddenFor IDs (which aren't created in GET function in controller).

@model WerehouseProject.ViewModels.PaintballWorkerCreateViewModel

@{
    ViewBag.Title = "Utwórz pracownika";
    Layout = "~/Views/Shared/_Layout_Paintball.cshtml";
}

Dodawanie pracownika

@using (Html.BeginForm("Create", "PaintballWorkers", FormMethod.Post))
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.PaintballWorker.Active)
        @Html.HiddenFor(model => model.PaintballWorker.MoneyGot)
        @Html.HiddenFor(model => model.PaintballWorker.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.Date)
        @Html.HiddenFor(model => model.HourlyRate.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.PWHourlyRateID)

            @Html.LabelFor(model => model.PaintballWorker.Imie, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.PaintballWorker.Imie, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PaintballWorker.Imie, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.PaintballWorker.Nazwisko, htmlAttributes: new { @class = "control-label col-md-2" })

(...)

            @Html.LabelFor(model => model.HourlyRate.HourlyRate, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.HourlyRate.HourlyRate, new { htmlAttributes = new { @class = "form-control", @type = "number", @min = "0.1", @step = "0.1", @value = "10" } })
                @Html.ValidationMessageFor(model => model.HourlyRate.HourlyRate, "", new { @class = "text-danger" })

                <input type="submit" value="Dodaj pracownika" class="btn btn-primary" />

}

@Html.ActionLink("Powrót do listy", "Index", new object { }, new { @class = "btn btn-default" })


来源: stackexchange

问:
How often do deadlocks occur(about to occur) in an operating system
We study a lot about deadlocks in operating system courses. How often do they really occur ?
or rather how often is there a chance for a deadlock(the OS actually doesn't let the dead lock to occur)?</p>

答:
Deadlocks occur as often as you program multi thread programs with synchronizers and you don't know what you're doing.

You always have to release a mutex, for example, before placing the thread on wait as long as you need that same mutex to awake that thread, and that's just a small example.

ContentLicense: CC BY-SA 2.5


问:
how to send a data between two android app one of them is unity game
I am trying to make an android game (using unity game engine) and I want this game to have a speech recognition feature.
I want to make speech recognition using android application which uses google API, but I want to send the result of recognition to another app which is the unity game.

How can I do it ? Is it valid ?
P.S.: I know that google provides a plugin for unity but I do not want to use it.

答: You can use Services.  Bounded services with a Messenger that will serve as the mediator between the remote and local process or with AIDL interface. You can also create a receiver on the remote process to receive the service obtained and a service(the sender).  Here is a good link for step by step: http://jeanmeyblum.weebly.com/scripts--tutorials/communication-between-an-android-app-and-unity</p>

ContentLicense: CC BY-SA 3.0


问:
Python: Printing out result from conditional for loop
I have a simple question. I have a small dataframe:

```<code>      Column1  Column2  Column3
Row1        0        4        6
Row2        1        3        5
Row3        0        4        2
</code>```

I need to only print out only Column1 and Column2 only if Column1 equals 1:

```<code>      Column1  Column2
Row2        1        3
</code>```

I have this piece of code that I am stuck at:

```<code>col=[col for col in df.columns if col=="Column1" or col=="Column2"]
print(loc[:,col])
</code>```

This is printing out the result such that we are having Column1 and Column2 with all the values.

```<code>      Column1  Column2
Row1        0        4
Row2        1        3
Row3        0        4
</code>```

How can I incorporate the condition such that Column1==1?

Thanks!

答:
You can use the namedtuple of python to do this. Namedtuple creates individual single classes to represent the values. It is worth remembering that classes have only values and no method.

would be like this:

```<code>from collections import namedtuple

Value = namedtuple('Value', ['column', 'line', 'value'])

examples = [Value(column, line, value) for column in range(3)
                                       for line in range(2)
                                       for value in range(2)]

>>> examples
[Value(column=0, line=0, value=0), Value(column=0, line=0, value=1), Value(column=0, line=1, value=0), Value(column=0, line=1, value=1), Value(column=1, line=0, value=0), Value(column=1, line=0, value=1), Value(column=1, line=1, value=0), Value(column=1, line=1, value=1), Value(column=2, line=0, value=0), Value(column=2, line=0, value=1), Value(column=2, line=1, value=0), Value(column=2, line=1, value=1)]

for _ in examples:
  if _.column == 1:
    print('Line: %s' % _.line, 'Value: %s' % _.value)

Line: 0 Value: 0
Line: 0 Value: 1
Line: 1 Value: 0
Line: 1 Value: 1
</code>```

Body:
I have a simple question. I have a small dataframe:

      Column1  Column2  Column3
Row1        0        4        6
Row2        1        3        5
Row3        0        4        2

I need to only print out only Column1 and Column2 only if Column1 equals 1:

      Column1  Column2
Row2        1        3

I have this piece of code that I am stuck at:

col=[col for col in df.columns if col=="Column1" or col=="Column2"]
print(loc[:,col])

This is printing out the result such that we are having Column1 and Column2 with all the values.

      Column1  Column2
Row1        0        4
Row2        1        3
Row3        0        4

How can I incorporate the condition such that Column1==1?

Thanks!

Body:
You can use the namedtuple of python to do this. Namedtuple creates individual single classes to represent the values. It is worth remembering that classes have only values and no method.

would be like this:

from collections import namedtuple

Value = namedtuple('Value', ['column', 'line', 'value'])

examples = [Value(column, line, value) for column in range(3)
                                       for line in range(2)
                                       for value in range(2)]

>>> examples
[Value(column=0, line=0, value=0), Value(column=0, line=0, value=1), Value(column=0, line=1, value=0), Value(column=0, line=1, value=1), Value(column=1, line=0, value=0), Value(column=1, line=0, value=1), Value(column=1, line=1, value=0), Value(column=1, line=1, value=1), Value(column=2, line=0, value=0), Value(column=2, line=0, value=1), Value(column=2, line=1, value=0), Value(column=2, line=1, value=1)]

for _ in examples:
  if _.column == 1:
    print('Line: %s' % _.line, 'Value: %s' % _.value)

Line: 0 Value: 0
Line: 0 Value: 1
Line: 1 Value: 0
Line: 1 Value: 1


问:
How to merge two stream using stream?
I have two stream, one contains object of A, one contains object of B, they are in same length. Now I have a class called C, it contains A and B as its fields.

```<code>class C {
    A a;
    B b;
}
</code>```

How can I merge the two stream into one stream using stream operation?

答:
If you have Guava in your classpath, take a look at the Streams.zip utility:

```<code>Stream<C> streamC = Streams.zip(streamA, streamB, C::new);
</code>```

This assumes C has a constructor that accepts A and B:

```<code>public C(A a, B b) {
    this.a = a;
    this.b = b;
}
</code>```

Title: How to merge two stream using stream?

Body:
I have two stream, one contains object of A, one contains object of B, they are in same length. Now I have a class called C, it contains A and B as its fields.

class C {
    A a;
    B b;
}

How can I merge the two stream into one stream using stream operation?

Body:
If you have Guava in your classpath, take a look at the Streams.zip utility:

Stream<C> streamC = Streams.zip(streamA, streamB, C::new);

This assumes C has a constructor that accepts A and B:

public C(A a, B b) {
    this.a = a;
    this.b = b;
}


问:
python conditional constructor for giving object or None
I receive UDP packets with GPS data, and construct Position objects with them.
Sometimes, GPS loss satellite signal, but still send UDP packets with no valuable data. I would like the Position constructor gives me a 'None' object in this failure cases. So, I could check if process the Position or not. Something like that:

```<code>frameGPS = giveMeTheFrame()
position1 = Position(frameGPS)
if (position1 is None): don't process position1
else: process position1
</code>```

Is this a right way to do it?
If so, how could I implement this init?

答:
As coldspeed said, you can't return from __init__. What you can do is initialize the object to an "empty" state. Make your Position object do something like this.

```<code>class Position:
    def __init__(self, frame):
        if some_condition:
            self.okay = True
            # Success; load the frame data into Position ...
        else:
            self.okay = False
    def __bool__(self):
        return self.okay
</code>```

Then you can use it in an if-statement like you wanted to.

```<code>frameGPS = giveMeTheFrame()
position1 = Position(frameGPS)
if position1:
    # Success; do some work ...
else:
    # Failure; GPS lost signal ...
</code>```

Note that in Python 2.x, the relevant method is called __nonzero__(), not __bool__(). So, use __nonzero__() if you are in Python 2.x, use __bool__() if you are in Python 3.x

Body:
I receive UDP packets with GPS data, and construct Position objects with them.
Sometimes, GPS loss satellite signal, but still send UDP packets with no valuable data. I would like the Position constructor gives me a 'None' object in this failure cases. So, I could check if process the Position or not. Something like that:

frameGPS = giveMeTheFrame()
position1 = Position(frameGPS)
if (position1 is None): don't process position1
else: process position1

Is this a right way to do it?
If so, how could I implement this init?

Body:
As coldspeed said, you can't return from __init__. What you can do is initialize the object to an "empty" state. Make your Position object do something like this.

class Position:
    def __init__(self, frame):
        if some_condition:
            self.okay = True
            # Success; load the frame data into Position ...
        else:
            self.okay = False
    def __bool__(self):
        return self.okay

Then you can use it in an if-statement like you wanted to.

frameGPS = giveMeTheFrame()
position1 = Position(frameGPS)
if position1:
    # Success; do some work ...
else:
    # Failure; GPS lost signal ...

Note that in Python 2.x, the relevant method is called __nonzero__(), not __bool__(). So, use __nonzero__() if you are in Python 2.x, use __bool__() if you are in Python 3.x


问:
JS Cannot read property "length" of undefined
I'm trying to create an object using a given string where each word has a property stating its length.

```<code>var strings = {};

function findLongestWord(str) {
  var splitStr = str.split(" ");
    for (var i = 0; i <= str.length; i++){
     strings[splitStr[i]] = splitStr[i].length;
  }

  return strings;
}

findLongestWord("The quick brown fox jumped over the lazy dog");
</code>```

I end up getting:

```<code>"TypeError": Cannot read property "length" of undefined.
</code>```

If I were to replace splitStr[i].length with splitStr[0].length, the code runs properly, but of course giving me the same number for each word in the object.

Any help is appreciated, thanks.

答:
you are looping over wrong array. you should use i < splitStr.length.

```<code>  var strings = {};
  function findLongestWord(str) {
  var splitStr = str.split(" ");
    for (var i = 0; i < splitStr.length; i++){
     strings[splitStr[i]] = splitStr[i].length;
  }

  return strings;
}
</code>```

Body:
I'm trying to create an object using a given string where each word has a property stating its length.

var strings = {};

function findLongestWord(str) {
  var splitStr = str.split(" ");
    for (var i = 0; i <= str.length; i++){
     strings[splitStr[i]] = splitStr[i].length;
  }

  return strings;
}

findLongestWord("The quick brown fox jumped over the lazy dog");

I end up getting:

"TypeError": Cannot read property "length" of undefined.

If I were to replace splitStr[i].length with splitStr[0].length, the code runs properly, but of course giving me the same number for each word in the object.

Any help is appreciated, thanks.

Body:
you are looping over wrong array. you should use i < splitStr.length.

  var strings = {};
  function findLongestWord(str) {
  var splitStr = str.split(" ");
    for (var i = 0; i < splitStr.length; i++){
     strings[splitStr[i]] = splitStr[i].length;
  }

  return strings;
}


问:
Access Database field query
I am currently making a very simply database but haven't made one in a while.
My issue is that I have one table, Drinks, which has a column (the technical terms slips my mind) that is called ingredients. This column will be populated from two other tables, volume and ingred.  I have split these tables up because there are many drinks that use the same ingredients but different volumes of them. So my question is what kind of query/relationship should I have to get the column to be correctly populated.

答:
In your main table (Drinks)  you need reference  to  splitted table. For example instead of ingredients field  you need  ingredients_id and the same for other splitted tables.

Then you  can use  one to many  query  to populate  your data  as you  wish.

Title: Access Database field query


问:
Can you auto hide frames/dialogs using wxPython?
I would like to create an application that has 3-4 frames (or windows) where each frame is attached/positioned to a side of the screen (like a task bar). When a frame is inactive I would like it to auto hide (just like the Windows task bar does; or the dock in OSX). When I move my mouse pointer to the position on the edge of the screen where the frame is hidden, I would like it to come back into focus.

The application is written in Python (using wxPython for the basic GUI aspects). Does anyone know how to do this in Python? I'm guessing it's probably OS dependent? If so, I'd like to focus on Windows first.

I don't do GUI programming very often so my apologies if this makes no sense at all.

答: I think you could easily just make a window that is the same size as the desktop then do some while looping for an inactivity variable based on mouse position, then thread off a timer for loop for the 4 inactivity variables. I'd personally design it so that when they reach 0 from 15, they change size and position to become tabular and create a button on them to reactivate. lots of technical work on this one, but easily done if you figure it out</p>


问:
Arduino millis() elapsed time with pause
I currently measure elapsed time in my sketch with a code to measure elapsed time like the one seen here. The code needs to be accurate to about 1 second, but I would like to program it to be as robust as possible.

```<code>unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval)
{foo;}
</code>```

I'm wondering what the best way to add a pause functionality so that if bool pause == true either previousMillis or interval adjusts to make sure that foo fires after pause==false for interval

Right now I'm thinking something along the lines of:

```<code>//global setup
bool pause=false;
unsigned long previousMillis = 0;
unsigned long interval = 1000;
_________
unsigned long currentMillis = millis();
RClock();
if ((unsigned long)(currentMillis - previousMillis) >= interval)
{
 interval=1000;
 foo;
}

void RClock()
{
  if(pause)
  {
     unsigned long runtime = millis()-previousMillis;
     unsigned long timeleft= interval-runtime;
     previousMillis=millis();
     interval=timeleft;
  }
}
</code>```

Is there a better way to do this? I feel like it should be a more simple operation.

Edit
To clear things up, my goal is for foo to trigger when pause==true for a total of interval so if interval=1000(ms) and, during that time, pause==true for 500(ms) foo would occour after 1500 ms

Edit 2

To clarify further, the time something runs before pause==true needs to be taken into acount lets say that:

interval = 1000(ms) when the program starts.

The program runs for 500(ms)

After 500(ms) pause == true

After 3hr Pause == false

foo will be triggered after 500(ms) more of Pause == false

答:
millis() goes back to zero for one millisecond every 50 days.  Hence the extra test.  PreviousMillis != 0 controls the triggering

```<code>void Loop()
{
   //...
   if (pause)
   {
      previousMillis = millis();
      if (previousMillis == 0)
        previousMillis = 1;   // avoid the one in a billion chance of missing a trigger
   }
   if (previousMillis && ((millis() - previousMillis) > interval))
   {
      previousMillis = 0;     // prevents retriggering
      foo();
   }
   //...
}
</code>```

The timer is set coninuously withe the current 'time' while pause == true.

When not in pause, the timer will pass the second test after interval ms.

The timer is set to zero when done; this avoids false triggers.

Body:
I currently measure elapsed time in my sketch with a code to measure elapsed time like the one seen here. The code needs to be accurate to about 1 second, but I would like to program it to be as robust as possible.

unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval)
{foo;}

I'm wondering what the best way to add a pause functionality so that if bool pause == true either previousMillis or interval adjusts to make sure that foo fires after pause==false for interval

Right now I'm thinking something along the lines of:

//global setup
bool pause=false;
unsigned long previousMillis = 0;
unsigned long interval = 1000;
_________
unsigned long currentMillis = millis();
RClock();
if ((unsigned long)(currentMillis - previousMillis) >= interval)
{
 interval=1000;
 foo;
}

void RClock()
{
  if(pause)
  {
     unsigned long runtime = millis()-previousMillis;
     unsigned long timeleft= interval-runtime;
     previousMillis=millis();
     interval=timeleft;
  }
}

Is there a better way to do this? I feel like it should be a more simple operation.

Edit
To clear things up, my goal is for foo to trigger when pause==true for a total of interval so if interval=1000(ms) and, during that time, pause==true for 500(ms) foo would occour after 1500 ms

Edit 2

To clarify further, the time something runs before pause==true needs to be taken into acount lets say that:

interval = 1000(ms) when the program starts.

The program runs for 500(ms)

After 500(ms) pause == true

After 3hr Pause == false

foo will be triggered after 500(ms) more of Pause == false

Body:
millis() goes back to zero for one millisecond every 50 days.  Hence the extra test.  PreviousMillis != 0 controls the triggering

void Loop()
{
   //...
   if (pause)
   {
      previousMillis = millis();
      if (previousMillis == 0)
        previousMillis = 1;   // avoid the one in a billion chance of missing a trigger
   }
   if (previousMillis && ((millis() - previousMillis) > interval))
   {
      previousMillis = 0;     // prevents retriggering
      foo();
   }
   //...
}

The timer is set coninuously withe the current 'time' while pause == true.

When not in pause, the timer will pass the second test after interval ms.

The timer is set to zero when done; this avoids false triggers.


问:
Android ADT error, dx.jar was not loaded from the SDK folder
I just downloaded Eclipse Galileo and installed ADT10 and tried to a phonegap app using this guide: http://www.phonegap.com/start
But each time i try to build im getting this error:
Unknown error: Unable to build: the file dx.jar was not loaded from the SDK folder!

I know that there are already some questions/answers about it in this forum but they didnt work for me.

答:
I just encountered the same problem yesterday, in Eclipse of Neon Release (4.6.0).

It's a compatible issue related to 26.0.0 of android-sdk "build-tools".

Simple Solution:

Delete "26.0.0" in "build-tools" directory

Use "25.0.2" instead

Restart eclipse

Other Solution:

add this in the project.properties of your project:

    sdk.buildtools=25.0.2

Good luck!


问:
Mousemove event blocked by occluding SVG elements
I have an SVG element with a mousemove event, showing the coordinate of the pointer. When the the mouse moves over an occluding element, the mousemove event is blocked. I need to make the event propagate to the original element.

I have tried changing the pointer-events attribute, but this effects all mouse events, and I need the occluding elements to respond other events. Any suggestions.

答:
Perhaps a method of addressing this would be to tie all your events to the container/parentNode in which your svg and the occluding elements reside - logging the mouse position within that 'outer' element against the 'bounding Client Rectangles' properties of the child elements within it.

Without a code sample in the question it is difficult know exactly what would be required, but the principle might follow along these lines...

```<code><!-- HTML sample -->
<div id="container">
    <div id="elem1" class="occluded">Element #1</div>
    <div id="elem2" class="occluded">Element #2</div>
    <div class="fullWidthHeightOverlay"></div>
</div>
<div id="eventLog"></div>
</code>```

Let's say the #container has a width and height, the .occluded elements float within that layer but underneath the .fullWidthHeightOverly element (which if I have understood your question correct plays the role of your SVG).  #eventLog is something to attach a behaviour to later.

Let's also assume that we want to log the mouse position relative to the outer #container layer to make 'click' behaviours available when the mouse is over either of the .occluded elements.  (I hope that's clear?)

First we need to attach some events to #container - in this case, one for mouse-positions and one for clicks.

```<code>/* SIMPLE SELECTOR - '#id' */
function $(a){
    $.b = $.b || {};
    if (void 0 === $.b[a]) $.b[a] = document.getElementById(a.slice(1));
    return $.b[a];
}

var elem1, elem2;

/* ! */
function addEvents() {
    $('#container').addEventListener('mousemove', logMousePos, false);
    $('#container').addEventListener('click', occludedClick, false);
}
</code>```

You'll see I've also created a couple of variables we can assign the .occluded element to.

Next we need the logMousePos() and occludedClick() functions in which to log the positional properties of the two .occluded elements relative to the mouse-position on the .fullWidthHeightOverly layer 'above' them, and then initiate some simple behaviours, E.G...

```<code>function logMousePos(e) {
    var e1 = elem1.getBoundingClientRect(),
        e2 = elem2.getBoundingClientRect(),
        e1CL = elem1.classList,
        e2CL = elem2.classList;

    /* is mouse inside #elem1 ? */
    if (check.X(e.clientX, e1) && check.Y(e.clientY, e1)) {
        /* if no 'over' class add it... */
        if (!e1CL.contains('over')) e1CL.add('over');
    } else {
        /* ...if 'over' class remove it */
        if (e1CL.contains('over')) e1CL.remove('over');
    }

    /* is mouse inside #elem2 ? */
    if (check.X(e.clientX, e2) && check.Y(e.clientY, e2)) {
        if (!e2CL.contains('over')) e2CL.add('over');
    } else {
        if (e2CL.contains('over')) e2CL.remove('over');
    }
}

function occludedClick(e) {
    var e1 = elem1.getBoundingClientRect(),
        e2 = elem2.getBoundingClientRect(),
        e1CL = elem1.classList,
        e2CL = elem2.classList;

    /* was mouse clicked inside #elem1 or #elem2 or not ? */
    if (check.X(e.clientX, e1) && check.Y(e.clientY, e1)) {
        $('#eventLog').textContent = 'Element #1 pseudo-Clicked';
    } else if (check.X(e.clientX, e2) && check.Y(e.clientY, e2)) {
        $('#eventLog').textContent = 'Element #2 pseudo-Clicked';
    } else {
        $('#eventLog').textContent = '';
    }
 }
</code>```

..and there you'll notice I'm referring to some check() Object methods to, erm, check if the mouse is within the 'boundingClientRect' of either .occluded element.

```<code>var check = {
    X: function(x, el) {
        return (x > el.left && x < el.right);
    },
    Y: function(y, el) {
        return (y > el.top && y < el.bottom);
    }
};
</code>```

Then it's just a matter of initialising the variables and adding the event listeners...

```<code>(function init() {
    addEvents();
    elem1 = $('#elem1');
    elem2 = $('#elem2');
}());
</code>```

You can find a JSFIDDLE of the whole thing  HERE.

I hope that gives you enough to be able to apply the principle in your particular case.

:)

Body:
Perhaps a method of addressing this would be to tie all your events to the container/parentNode in which your svg and the occluding elements reside - logging the mouse position within that 'outer' element against the 'bounding Client Rectangles' properties of the child elements within it.

Without a code sample in the question it is difficult know exactly what would be required, but the principle might follow along these lines...

<!-- HTML sample -->
<div id="container">
    <div id="elem1" class="occluded">Element #1</div>
    <div id="elem2" class="occluded">Element #2</div>
    <div class="fullWidthHeightOverlay"></div>
</div>
<div id="eventLog"></div>

Let's say the #container has a width and height, the .occluded elements float within that layer but underneath the .fullWidthHeightOverly element (which if I have understood your question correct plays the role of your SVG).  #eventLog is something to attach a behaviour to later.

Let's also assume that we want to log the mouse position relative to the outer #container layer to make 'click' behaviours available when the mouse is over either of the .occluded elements.  (I hope that's clear?)

First we need to attach some events to #container - in this case, one for mouse-positions and one for clicks.

/* SIMPLE SELECTOR - '#id' */
function $(a){
    $.b = $.b || {};
    if (void 0 === $.b[a]) $.b[a] = document.getElementById(a.slice(1));
    return $.b[a];
}

var elem1, elem2;

/* ! */
function addEvents() {
    $('#container').addEventListener('mousemove', logMousePos, false);
    $('#container').addEventListener('click', occludedClick, false);
}

You'll see I've also created a couple of variables we can assign the .occluded element to.

Next we need the logMousePos() and occludedClick() functions in which to log the positional properties of the two .occluded elements relative to the mouse-position on the .fullWidthHeightOverly layer 'above' them, and then initiate some simple behaviours, E.G...

function logMousePos(e) {
    var e1 = elem1.getBoundingClientRect(),
        e2 = elem2.getBoundingClientRect(),
        e1CL = elem1.classList,
        e2CL = elem2.classList;

    /* is mouse inside #elem1 ? */
    if (check.X(e.clientX, e1) && check.Y(e.clientY, e1)) {
        /* if no 'over' class add it... */
        if (!e1CL.contains('over')) e1CL.add('over');
    } else {
        /* ...if 'over' class remove it */
        if (e1CL.contains('over')) e1CL.remove('over');
    }

    /* is mouse inside #elem2 ? */
    if (check.X(e.clientX, e2) && check.Y(e.clientY, e2)) {
        if (!e2CL.contains('over')) e2CL.add('over');
    } else {
        if (e2CL.contains('over')) e2CL.remove('over');
    }
}

function occludedClick(e) {
    var e1 = elem1.getBoundingClientRect(),
        e2 = elem2.getBoundingClientRect(),
        e1CL = elem1.classList,
        e2CL = elem2.classList;

    /* was mouse clicked inside #elem1 or #elem2 or not ? */
    if (check.X(e.clientX, e1) && check.Y(e.clientY, e1)) {
        $('#eventLog').textContent = 'Element #1 pseudo-Clicked';
    } else if (check.X(e.clientX, e2) && check.Y(e.clientY, e2)) {
        $('#eventLog').textContent = 'Element #2 pseudo-Clicked';
    } else {
        $('#eventLog').textContent = '';
    }
 }

..and there you'll notice I'm referring to some check() Object methods to, erm, check if the mouse is within the 'boundingClientRect' of either .occluded element.

var check = {
    X: function(x, el) {
        return (x > el.left && x < el.right);
    },
    Y: function(y, el) {
        return (y > el.top && y < el.bottom);
    }
};

Then it's just a matter of initialising the variables and adding the event listeners...

(function init() {
    addEvents();
    elem1 = $('#elem1');
    elem2 = $('#elem2');
}());

You can find a JSFIDDLE of the whole thing  HERE.

I hope that gives you enough to be able to apply the principle in your particular case.

:)


问:
How can I avoid this strange "Could not fetch URL" error when doing any pip install
Using python 2.7. Was working fine for months but all of a sudden i start getting this weird error when i try and do pip installs outside of or within a virtualenv. If i do something like this:

```<code>pip install pandas
</code>```

I am told:

```<code>Could not fetch URL https://pypi.python.org/simple/pandas/: There was a problem confirming the ssl certificate: EOF occurred in violation of protocol (_ssl.c:590) - skipping
  Could not find a version that satisfies the requirement pandas (from versions: )
No matching distribution found for pandas
</code>```

This occurs for just about any pip library and it is infuriating. I tried updating my pip and it said it was up to date. I read somewhere i should try and update my virtualenv which I did with:

```<code>pip install --upgrade virtualenv
</code>```

But it gave the same error. So enraging haha.

答:
As a temporary fix, you could fetch the appropriate .whl for your system from
this link and install it using

pip install some-package.whl

Otherwise, you should check the top anwser from here which seems to have fixed the problem when having trouble with ssl.

Body:
Using python 2.7. Was working fine for months but all of a sudden i start getting this weird error when i try and do pip installs outside of or within a virtualenv. If i do something like this:

pip install pandas

I am told:

Could not fetch URL https://pypi.python.org/simple/pandas/: There was a problem confirming the ssl certificate: EOF occurred in violation of protocol (_ssl.c:590) - skipping
  Could not find a version that satisfies the requirement pandas (from versions: )
No matching distribution found for pandas

This occurs for just about any pip library and it is infuriating. I tried updating my pip and it said it was up to date. I read somewhere i should try and update my virtualenv which I did with:

pip install --upgrade virtualenv

But it gave the same error. So enraging haha.

ContentLicense: CC BY-SA 4.0


问:
firebase auth with email and password doesnt work with mobile data connection
I do firebase authentication with email and password work fine when i have wifi but i connected mobile data connection firebase authentication fail and get this message:

```<code>"a network error (such as timeout, interrupted connection or unreachable
host) has occurred."
</code>```

this is my gradle:

```<code>classpath 'com.google.gms:google-services:3.1.0'

compile 'com.google.firebase:firebase-auth:11.0.1'
</code>```

This is my manifest:

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

Only WiFi work fine. Mobile data connection doesn't work

答:
I think the problem is with permissions missing in the manifest</p>

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

Body:
I do firebase authentication with email and password work fine when i have wifi but i connected mobile data connection firebase authentication fail and get this message:

"a network error (such as timeout, interrupted connection or unreachable
host) has occurred."

this is my gradle:

classpath 'com.google.gms:google-services:3.1.0'

compile 'com.google.firebase:firebase-auth:11.0.1'

This is my manifest:

<uses-permission android:name="android.permission.INTERNET" />

Only WiFi work fine. Mobile data connection doesn't work

Body:
I think the problem is with permissions missing in the manifest

<uses-permission android:name="android.permission.INTERNET" />


问:
Laravel 5.4 - How to set PDO Fetch Mode?
The ability to customize the fetch mode was removed from L5.4 and is defaulted to PDO::FETCH_OBJ.

The upgrade guide states that you can override this by using an event listener:

```<code>Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(...);
});
</code>```

I can't for the life of me understand how to implement this:

1) Where should I place the code? Should I register it with the EventServiceProvider?

2) When does the StatementPrepared event fire? (I only need to change the Fetch Mode  for specific repository functions, not on a global scale).

3) Does the FetchMode revert itself automatically for subsequent queries?

Here's an example of my code:

```<code><?php

namespace App\Repositories\Backend;

use DB;
use PDO;

class SystemRepository
{
    /**
     * Get the connection status variables.
     *
     * @return array
     */
    public function getConnectionStatus()
    {
        DB::connection('backend')->setFetchMode(PDO::FETCH_ASSOC);

        $result = DB::connection('backend')
            ->select(DB::raw("
                SHOW STATUS
                WHERE Variable_name = 'Max_used_connections'
                OR Variable_name = 'Max_used_connections_time'
                OR Variable_name = 'Threads_connected'
            "))
        ;

        DB::connection('backend')->setFetchMode(PDO::FETCH_CLASS);

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

Thank you!

答:
Go to: app/Providers/EventServiceProvider.php

Add this to the top of the file:

```<code>use Illuminate\Database\Events\StatementPrepared;
</code>```

In the boot method add:

```<code>Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(\PDO::FETCH_ASSOC);
});
</code>```

Body:
The ability to customize the fetch mode was removed from L5.4 and is defaulted to PDO::FETCH_OBJ.

The upgrade guide states that you can override this by using an event listener:

Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(...);
});

I can't for the life of me understand how to implement this:

1) Where should I place the code? Should I register it with the EventServiceProvider?

2) When does the StatementPrepared event fire? (I only need to change the Fetch Mode  for specific repository functions, not on a global scale).

3) Does the FetchMode revert itself automatically for subsequent queries?

Here's an example of my code:

<?php

namespace App\Repositories\Backend;

use DB;
use PDO;

class SystemRepository
{
    /**
     * Get the connection status variables.
     *
     * @return array
     */
    public function getConnectionStatus()
    {
        DB::connection('backend')->setFetchMode(PDO::FETCH_ASSOC);

        $result = DB::connection('backend')
            ->select(DB::raw("
                SHOW STATUS
                WHERE Variable_name = 'Max_used_connections'
                OR Variable_name = 'Max_used_connections_time'
                OR Variable_name = 'Threads_connected'
            "))
        ;

        DB::connection('backend')->setFetchMode(PDO::FETCH_CLASS);

        return $result;
    }
}

Thank you!

Body:
Go to: app/Providers/EventServiceProvider.php

Add this to the top of the file:

use Illuminate\Database\Events\StatementPrepared;

In the boot method add:

Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(\PDO::FETCH_ASSOC);
});


问:
Filter words in a sentence that begin with a certain range of letters
My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.

This is my code so far, however it still prints words which begin with "g" and does not print the last word.

```<code>famous_quote = input("Enter a one sentence quote: ").lower()
word = ""

for ltr in famous_quote:
    if ltr.isalpha() == True:
        word = word + ltr
    else:
        if word > "g":
            print(word)
            word = ""
        else:
            word = ""
</code>```

I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.

Sample input:

```<code>Wheresoever you go, go with all your heart
</code>```

Sample output:

```<code>WHERESOEVER
YOU
WITH
YOUR
HEART
</code>```

Algorithm I've come up with:

 - split the words by building a placeholder variable: word
 - Loop each character in the input string
 - check if character is a letter
 - add a letter to word each loop until a non-alpha char is encountered
 - if character is alpha
 - add character to word
 - non-alpha detected (space, punctuation, digit,...) defines the end of a     word and goes to else
 - else
 - check if word is greater than "g" alphabetically
 - print word
 - set word = empty string
 - or else
 - set word = empty string and build the next word
 - Hint: use .lower()
```

答:
Assuming that the famous quote contains only spaces as word separator, this should do the job:

```<code>words = input("Enter a one sentence quote: ").lower().split()
for word in words:
 if word[0] > 'g':
  print("{w} ".format(w = word))
</code>```

split() transforms a string into a list (array). It takes, by default, the space character as parameter (hence I did not give the argument) and returns the list of words.

print() can be used in a lot of ways, due to python's history with this function.

You can .join() the list (getting a string as result) and print it:

```<code>print(" ".join(words))
</code>```

you can also print with concatenations (considered ugly):

```<code>print(word+" ")
</code>```

or you can use formatted printing, which I do use a lot for readibility:

```<code>print("{w} ".format(w = word))
</code>```

interprets "{w}" and replaces it with word wherever "{w}" appears.

Print formatting is rather CPU consuming (but it is still really fast). Usually any print operation slows your application, you want to minimize making outputs if you are making CPU intensive apps in your future (here I don't do that because CPU is not the main concern).

Body:
My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.

This is my code so far, however it still prints words which begin with "g" and does not print the last word.

famous_quote = input("Enter a one sentence quote: ").lower()
word = ""

for ltr in famous_quote:
    if ltr.isalpha() == True:
        word = word + ltr
    else:
        if word > "g":
            print(word)
            word = ""
        else:
            word = ""

I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.

Sample input:

Wheresoever you go, go with all your heart

Sample output:

WHERESOEVER
YOU
WITH
YOUR
HEART

Algorithm I've come up with:

 - split the words by building a placeholder variable: word
 - Loop each character in the input string
 - check if character is a letter
 - add a letter to word each loop until a non-alpha char is encountered
 - if character is alpha
 - add character to word
 - non-alpha detected (space, punctuation, digit,...) defines the end of a     word and goes to else
 - else
 - check if word is greater than "g" alphabetically
 - print word
 - set word = empty string
 - or else
 - set word = empty string and build the next word
 - Hint: use .lower()

Body:
Assuming that the famous quote contains only spaces as word separator, this should do the job:

words = input("Enter a one sentence quote: ").lower().split()
for word in words:
 if word[0] > 'g':
  print("{w} ".format(w = word))

split() transforms a string into a list (array). It takes, by default, the space character as parameter (hence I did not give the argument) and returns the list of words.

print() can be used in a lot of ways, due to python's history with this function.

You can .join() the list (getting a string as result) and print it:

print(" ".join(words))

you can also print with concatenations (considered ugly):

print(word+" ")

or you can use formatted printing, which I do use a lot for readibility:

print("{w} ".format(w = word))

interprets "{w}" and replaces it with word wherever "{w}" appears.

Print formatting is rather CPU consuming (but it is still really fast). Usually any print operation slows your application, you want to minimize making outputs if you are making CPU intensive apps in your future (here I don't do that because CPU is not the main concern).


问:
Convert dataset of .mat format to .csv octave/matlab
there are datasets in .mat format in the this site: http://www.cs.nyu.edu/~roweis/data.html

I want to change the format to .csv.
Can someone tell me how to change the format to create the .csv file.

Thanks!

答:
I do not have a Matlab license so I installed GNU Octave 4.2.1 (2017) on Windows 10 (thank you to John W. Eaton and others).  I was not fully successful using the csvwrite so I used the following workaround. (BTW, I am totally incompetent in the Octave world.  csvwrite worked for simple data structures).

In the Command Window I used the following two commands

load myfile.mat

save("-text","myfile.txt","variablename")

When the "myfile.mat" is loaded, the variable names for the data vectors loaded are displayed in the workspace window.  This is the name(s) to use in the save command.  Some .mat files will load several data structures.

The "-text" option is the default, so you may not need to include this option in the command.

The output file lists the .mat file contents in text format as single column (of potentially sequential variables).  It should be easy to use you text editor to massage this data into the original matrix structure for use in whatever app you are comfortable with.


问:
ng-click not firing even I registered the function in controller
Hi I am working on an app and get the problem. I checked console but no error messages.

I created a component and I insert it into other template. Template itself is working(button is rendered and I inspected the element ng-click attribute is there) but when I click on the button. the function is not fired.

The project is availiable here: https://github.com/Aozaki-Touko/webApplication-dota2hero/tree/master/app

navbar.component.js:

```<code>"use strict";

angular.module("navbar").component("navbar", {
  templateUrl: "/navbar/navbar.template.html",
  controller: [
    "$location",
    function($location) {
      var self=this;
      self.changeToHeroes = function(){
        alert("Button Pressed!");
        $location.path("/heroes");
      };
    }
  ]
});
</code>```

navbar.template.html:

```<code><button type="button" ng-click="$ctrl.changePathToHeroes()">Heroes</button>
</code>```

navbar.module.js:

```<code>"use strict";

angular.module("navbar",[]);
</code>```

答:
use controllerAs

```<code>angular.module("navbar").component("navbar", {
  templateUrl: "/navbar/navbar.template.html",
  controllerAs:"$ctrl",
  controller: [
    "$location",
    function($location) {
      var $ctrl = this;
      $ctrl .changeToHeroes = function(){
        alert("Button Pressed!");
        $location.path("/heroes");
      };
    }
  ]
});
</code>```

Body:
Hi I am working on an app and get the problem. I checked console but no error messages.

I created a component and I insert it into other template. Template itself is working(button is rendered and I inspected the element ng-click attribute is there) but when I click on the button. the function is not fired.

The project is availiable here: https://github.com/Aozaki-Touko/webApplication-dota2hero/tree/master/app

navbar.component.js:

"use strict";

angular.module("navbar").component("navbar", {
  templateUrl: "/navbar/navbar.template.html",
  controller: [
    "$location",
    function($location) {
      var self=this;
      self.changeToHeroes = function(){
        alert("Button Pressed!");
        $location.path("/heroes");
      };
    }
  ]
});

navbar.template.html:

<button type="button" ng-click="$ctrl.changePathToHeroes()">Heroes</button>

navbar.module.js:

"use strict";

angular.module("navbar",[]);

Body:
use controllerAs

angular.module("navbar").component("navbar", {
  templateUrl: "/navbar/navbar.template.html",
  controllerAs:"$ctrl",
  controller: [
    "$location",
    function($location) {
      var $ctrl = this;
      $ctrl .changeToHeroes = function(){
        alert("Button Pressed!");
        $location.path("/heroes");
      };
    }
  ]
});


问:
error of Auto-deploy war file to jenkins
I got this error while try to do auto-deploy to our tomcat server.

ERROR: Publisher hudson.plugins.deploy.DeployPublisher aborted due to
  exception org.codehaus.cargo.container.ContainerException: Failed to
  redeploy
  [/home/affiza/workspace/mimos-test-deploy/dist/met-server.war]    at
  org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.redeploy(AbstractTomcatManagerDeployer.java:195)
    at
  hudson.plugins.deploy.CargoContainerAdapter.deploy(CargoContainerAdapter.java:64)
    at
  hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:90)
    at
  hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:77)
    at hudson.FilePath$FileCallableWrapper.call(FilePath.java:2309)     at
  hudson.remoting.UserRequest.perform(UserRequest.java:118)     at
  hudson.remoting.UserRequest.perform(UserRequest.java:48)  at
  hudson.remoting.Request$2.run(Request.java:326)   at
  hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722) Caused by:
  java.io.IOException: Server returned HTTP response code: 403 for URL:
  http://test.mest.my:8080//manager/text/list   at
  sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
    at
  org.codehaus.cargo.container.tomcat.internal.TomcatManager.invoke(TomcatManager.java:504)
    at
  org.codehaus.cargo.container.tomcat.internal.TomcatManager.list(TomcatManager.java:622)
    at
  org.codehaus.cargo.container.tomcat.internal.TomcatManager.getStatus(TomcatManager.java:635)
    at
  org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.redeploy(AbstractTomcatManagerDeployer.java:176)
    ... 13 more

What i need to do?

答: You should restart tomcat after changing anything in conf folder</p>


问:
Split Characters in String With Defined Character Length
I have a constraint when creating a form to display values in a table column horizontally based on characters in php. Like the example below. How to separate each character according to column?

Name :

I

R

W

A

N

D

W

I

```

答:
if you mean to separate characters from a string and insert them horizontally into your table then this php function can solve the problem

```<code>function sep($str){
$leng = strlen($str);
echo '<div style="display:inline;">';
echo 'Name :'
echo '<table style="display:inline; position:absolute" width="400" border="1"><tr>';
for ($i=0;$i<= $leng-1;$i++){
    $chr = substr($srt,$i,1);
    echo '<td width="28"><div align="center">'.$chr.'</div></td>';
    }
    echo   '</tr></table></div>';
}
</code>```

you just call the function from your php

```<code>sep('IRWAN DWI');
</code>```

or if you dont want to call a function just add this code

```<code>    <?php
    $str = IRWAN DWI';
    $leng = strlen($str);
    echo '<div style="display:inline;">';
    echo 'Name :'
    echo '<table style="display:inline; position:absolute" width="400" border="1"><tr>';
    for ($i=0;$i<= $leng-1;$i++){
            $chr = substr($srt,$i,1);
            echo '<td width="28"><div align="center">'.$chr.'</div></td>';
    }
    echo   '</tr></table></div>';
?>
</code>```

Body:
if you mean to separate characters from a string and insert them horizontally into your table then this php function can solve the problem

function sep($str){
$leng = strlen($str);
echo '<div style="display:inline;">';
echo 'Name :'
echo '<table style="display:inline; position:absolute" width="400" border="1"><tr>';
for ($i=0;$i<= $leng-1;$i++){
    $chr = substr($srt,$i,1);
    echo '<td width="28"><div align="center">'.$chr.'</div></td>';
    }
    echo   '</tr></table></div>';
}

you just call the function from your php

sep('IRWAN DWI');

or if you dont want to call a function just add this code

    <?php
    $str = IRWAN DWI';
    $leng = strlen($str);
    echo '<div style="display:inline;">';
    echo 'Name :'
    echo '<table style="display:inline; position:absolute" width="400" border="1"><tr>';
    for ($i=0;$i<= $leng-1;$i++){
            $chr = substr($srt,$i,1);
            echo '<td width="28"><div align="center">'.$chr.'</div></td>';
    }
    echo   '</tr></table></div>';
?>


问:
Mongo DB collections are not found
I am using MongoDB as my data storage, version v3.4.1. I am using a docker image of mongo, running it like this:

```<code>docker run -d -p 27017:27017 -v /home/rancher/data:/data/db --name mongodb mongo:latest
</code>```

After that I created many databases and collections. It was fine for more than one month; but now I am not able to find any collections inside the data base. This command to list collections is showing an empty list: show dbs. Alternatively, if I do use mydb then show collections nothing is displayed.

These are the data in the /home/rancher/data folder:

collection-0--4220404477553112134.wt

  collection-0-1041804628168690390.wt

  collection-2--4220404477553112134.wt

  collection-2-1041804628168690390.wt

  diagnostic.data

  index-1--4220404477553112134.wt

  index-1-1041804628168690390.wt

  index-3--4220404477553112134.wt

  index-3-1041804628168690390.wt

  index-4-1041804628168690390.wt

  journal

  _mdb_catalog.wt

  mongod.lock

  sizeStorer.wt

  storage.bson

  WiredTiger

  WiredTiger.lock

  WiredTiger.turtle

  WiredTiger.wt

  WiredTigerLAS.wt

Can anyone tell me why the collections are not persistent in mongo DB?

答: I also faced the same issue. This is the solution I found. Please check your mongodb port is open to the internet. if so restrict it to the servers. </p>

Title: Mongo DB collections are not found

Body:
I am using MongoDB as my data storage, version v3.4.1. I am using a docker image of mongo, running it like this:

docker run -d -p 27017:27017 -v /home/rancher/data:/data/db --name mongodb mongo:latest

After that I created many databases and collections. It was fine for more than one month; but now I am not able to find any collections inside the data base. This command to list collections is showing an empty list: show dbs. Alternatively, if I do use mydb then show collections nothing is displayed.

These are the data in the /home/rancher/data folder:

collection-0--4220404477553112134.wt

  collection-0-1041804628168690390.wt

  collection-2--4220404477553112134.wt

  collection-2-1041804628168690390.wt

  diagnostic.data

  index-1--4220404477553112134.wt

  index-1-1041804628168690390.wt

  index-3--4220404477553112134.wt

  index-3-1041804628168690390.wt

  index-4-1041804628168690390.wt

  journal

  _mdb_catalog.wt

  mongod.lock

  sizeStorer.wt

  storage.bson

  WiredTiger

  WiredTiger.lock

  WiredTiger.turtle

  WiredTiger.wt

  WiredTigerLAS.wt

Can anyone tell me why the collections are not persistent in mongo DB?


问:
How to get column count in ms access database from c#
I am trying to get a sum with a column from a ms access database but so not nothing has worked this is what I have

```<code>      Conn.Open();
            Command.CommandText = "Select SUM(c_qty) from COLLVAULT_COINS WHERE c_type!='US Currency' AND c_type!='World Currency' AND c_type!='World Coins' AND c_listName = '" + activeCollection + "'";
            int total_1 = Convert.ToInt32(Command.ExecuteScalar());
            //total sum - get how many match the query
            lblcollectedcount.Text = Convert.ToString(total_1);
            Conn.Close();
</code>```

any help would be nice.

答:
You could try something like this, assuming you want the number of records that were matched with your query:

```<code>Conn.Open();
Command.CommandText = "Select SUM(c_qty) as sum, Count(*) as count from COLLVAULT_COINS WHERE c_type <> 'US Currency' AND c_type <> 'World Currency' AND c_type <> 'World Coins' AND c_listName = '" + activeCollection + "'";    //

int total_matches = 0;

using (MySqlDataReader dataReader = Command.ExecuteReader())
{
    if (dataReader.Read())
    {
        lblcollectedcount.Text = Convert.ToString(dataReader["sum"]);
        total_matches = Convert.ToInt32(dataReader["count"]);
    }
    else
    {
        //nothing was read, handle that case
    }
}

Conn.Close();
</code>```

EDIT:

Misunderstood what the OP was asking for, and I also didn't catch the '<>' error.

I'll still keep this answer here, just for reference code.

Body:
I am trying to get a sum with a column from a ms access database but so not nothing has worked this is what I have

      Conn.Open();
            Command.CommandText = "Select SUM(c_qty) from COLLVAULT_COINS WHERE c_type!='US Currency' AND c_type!='World Currency' AND c_type!='World Coins' AND c_listName = '" + activeCollection + "'";
            int total_1 = Convert.ToInt32(Command.ExecuteScalar());
            //total sum - get how many match the query
            lblcollectedcount.Text = Convert.ToString(total_1);
            Conn.Close();

any help would be nice.

Body:
You could try something like this, assuming you want the number of records that were matched with your query:

Conn.Open();
Command.CommandText = "Select SUM(c_qty) as sum, Count(*) as count from COLLVAULT_COINS WHERE c_type <> 'US Currency' AND c_type <> 'World Currency' AND c_type <> 'World Coins' AND c_listName = '" + activeCollection + "'";    //

int total_matches = 0;

using (MySqlDataReader dataReader = Command.ExecuteReader())
{
    if (dataReader.Read())
    {
        lblcollectedcount.Text = Convert.ToString(dataReader["sum"]);
        total_matches = Convert.ToInt32(dataReader["count"]);
    }
    else
    {
        //nothing was read, handle that case
    }
}

Conn.Close();

EDIT:

Misunderstood what the OP was asking for, and I also didn't catch the '<>' error.

I'll still keep this answer here, just for reference code.


问:
extra characters after \ at the end of a command
When I try to insert new line in OSX using sed I'm getting the below error

extra characters after \ at the end of a command

Current File content is

```<code>{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}
</code>```

Expected content is

```<code>{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
 'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}
</code>```

The command I'm using is

```<code>sed -i '' "/localhost/a\                        'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'web']," FILENAME
</code>```

答:
Use sed p command to copy line and then replace the

```<code>sed '/localhost/p; s/localhost/dev.ops/' FILENAME
</code>```

outputs

```<code>{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
'devops' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}
</code>```

or to edit in place on OSX without keeping a backup, use -i '':

```<code>sed -i '' -e '/localhost/p; s/localhost/dev.ops/' FILENAME
</code>```

Body:
When I try to insert new line in OSX using sed I'm getting the below error

extra characters after \ at the end of a command

Current File content is

{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}

Expected content is

{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
 'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}

The command I'm using is

sed -i '' "/localhost/a\                        'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'web']," FILENAME

Body:
Use sed p command to copy line and then replace the

sed '/localhost/p; s/localhost/dev.ops/' FILENAME

outputs

{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
'devops' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}

or to edit in place on OSX without keeping a backup, use -i '':

sed -i '' -e '/localhost/p; s/localhost/dev.ops/' FILENAME


问:
Python tkinter Button not responding

TKINTER GRAPHICS

```<code>from tkinter import *

tk = Tk()

btn = Button(tk, text="Click Me") #Makes a useless button

btn.pack() #Shows the button

import turtle #Makes the graphics work

t = turtle.Pen()

def hello(): #Makes button not
print('hello here')

btn = Button(tk, text="Click Me", command=hello)
</code>```

The program SHOULD say hello there when I click the button, but I can't click the button because it won't respond.

答:
As noted in the comments, you appear to create the same button twice, once where it's not connected to a function but packed, and once where it's connected to a function but not packed.  If you combine the two, you'll get a working button.

But let's jump in and fix another problem before it begins -- you invoked:

```<code>t = turtle.Pen()
</code>```

No, not when you're working within tkinter.  If you're working with turtle standalone, it's Turtle/Pen and Screen, but if you're working within tkinter, it's RawTurtle/RawPen and TurtleScreen.  Otherwise you end up with extra windows and potential root conflicts.

Combining all the above together, adding a scrolled canvas for the turtle to play on, and changing the print() to the console to be a turtle.write() to the scrolled canvas, we get:

```<code>import tkinter as tk
import turtle # Makes the graphics work

def hello():  # Makes button not
    turtle.write('hello there', align='center', font=('Arial', 18, 'normal'))

root = tk.Tk()

button = tk.Button(root, text="Click Me", command=hello)  # Makes a button
button.pack()  # Shows the button

canvas = turtle.ScrolledCanvas(root)
canvas.pack(side=tk.LEFT)

screen = turtle.TurtleScreen(canvas)

turtle = turtle.RawPen(screen, visible=False)

screen.mainloop()
</code>```

Title: Python tkinter Button not responding

Body:
TKINTER GRAPHICS

from tkinter import *

tk = Tk()

btn = Button(tk, text="Click Me") #Makes a useless button

btn.pack() #Shows the button

import turtle #Makes the graphics work

t = turtle.Pen()

def hello(): #Makes button not
print('hello here')

btn = Button(tk, text="Click Me", command=hello)

The program SHOULD say hello there when I click the button, but I can't click the button because it won't respond.

Body:
As noted in the comments, you appear to create the same button twice, once where it's not connected to a function but packed, and once where it's connected to a function but not packed.  If you combine the two, you'll get a working button.

But let's jump in and fix another problem before it begins -- you invoked:

t = turtle.Pen()

No, not when you're working within tkinter.  If you're working with turtle standalone, it's Turtle/Pen and Screen, but if you're working within tkinter, it's RawTurtle/RawPen and TurtleScreen.  Otherwise you end up with extra windows and potential root conflicts.

Combining all the above together, adding a scrolled canvas for the turtle to play on, and changing the print() to the console to be a turtle.write() to the scrolled canvas, we get:

import tkinter as tk
import turtle # Makes the graphics work

def hello():  # Makes button not
    turtle.write('hello there', align='center', font=('Arial', 18, 'normal'))

root = tk.Tk()

button = tk.Button(root, text="Click Me", command=hello)  # Makes a button
button.pack()  # Shows the button

canvas = turtle.ScrolledCanvas(root)
canvas.pack(side=tk.LEFT)

screen = turtle.TurtleScreen(canvas)

turtle = turtle.RawPen(screen, visible=False)

screen.mainloop()


问:
Files inside the assets folder are not being loaded in sub pages
I have a folder structure like below

assets

bootstrap

css

style.css

js

jquery.min.js

views

partials

head.ejs

header.ejs

scripts.ejs

home.ejs

user_registration.ejs

In my app.js file I have set this assets folder like:

```<code>var app = express();
app.use('/static', express.static('assets'));
var routes = require('./routes/routes');
</code>```

In my routes.js file

```<code>exports.userLogin = function(req, res){
    var userLogin = req.params.userId;
    var users = memberData.users;
    res.render('user_registration', {
        title : 'Welcome',
        users : users
    });
};
</code>```

In my head.ejs file

```<code><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/bootstrap/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="static/css/style.css" type="text/css">
</code>```

Now inside in user_registration file, I have following code

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <% include partials/head.ejs %>
</head>
<body>
    <% include partials/scripts.ejs %>
</body>
</html>
</code>```

By using this my jQuery, bootstrap files that are inside assets folder are not being loaded. But the home.ejs page is working normally.

When I check at the console, the home.ejs page is taking those files in following format
http://localhost:3000/static/bootstrap/css/bootstrap.min.css

whereas user_registration page is taking following format

http://localhost:3000/user_registration/static/bootstrap/css/bootstrap.min.css

I am very new in express.js framework, so I could not figure out how to solve this problem. Can anybody please help me. Thank you.

答:
Problem is here app.use('/static', express.static('assets')); in your code line.

Replace it with
app.use(express.static(path.join(__dirname, 'assets')));

And in your head.ejs file replace bootstrap css calling line

href="static/bootstrap/css/bootstrap.min.css" to href="/bootstrap/css/bootstrap.min.css"

Hop you understand.

Body:
I have a folder structure like below

assets

bootstrap

css

style.css

js

jquery.min.js

views

partials

head.ejs

header.ejs

scripts.ejs

home.ejs

user_registration.ejs

In my app.js file I have set this assets folder like:

var app = express();
app.use('/static', express.static('assets'));
var routes = require('./routes/routes');

In my routes.js file

exports.userLogin = function(req, res){
    var userLogin = req.params.userId;
    var users = memberData.users;
    res.render('user_registration', {
        title : 'Welcome',
        users : users
    });
};

In my head.ejs file

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/bootstrap/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="static/css/style.css" type="text/css">

Now inside in user_registration file, I have following code

<!DOCTYPE html>

    <% include partials/head.ejs %>

    <% include partials/scripts.ejs %>

By using this my jQuery, bootstrap files that are inside assets folder are not being loaded. But the home.ejs page is working normally.

When I check at the console, the home.ejs page is taking those files in following format
http://localhost:3000/static/bootstrap/css/bootstrap.min.css

whereas user_registration page is taking following format

http://localhost:3000/user_registration/static/bootstrap/css/bootstrap.min.css

I am very new in express.js framework, so I could not figure out how to solve this problem. Can anybody please help me. Thank you.


问:
An ASP.NET MVC validator to make sure at least one checkbox is checked
I have an ASP.NET MVC 2 project in which I've created a data transfer object to receive data from a web page form. The form has two groups of checkboxes on it. I want to validate the object to make sure that at least one of the checkboxes in each group is checked.

I'm doing the validation on the server side so that a user won't be able to hack around any client-side validation. (I will add client-side validation with jQuery later; that's easy.)

My understanding is that I have to create my own custom ValidationAttribute for my data transfer object class, but I don't understand how to create and use one that can accept an arbitrary list of checkbox properties to make sure that at least one of them is true. I am guessing I will have to call the attributes like this:

```<code>[AtLeastOneCheckbox("set1check1", "set1check2", "set1check3",
    ErrorMessage = "You must check at least one checkbox in set 1.")]
[AtLeastOneCheckbox("set2check1", "set2check2", "set2check3", "set2check4", "set2check5",
    ErrorMessage = "You must check at least one checkbox in set 2.")]
public class MyFormDTO
{
    ...
}
</code>```

What would the implementation of AtLeastOneCheckboxAttribute look like?

Or is there a different way that I should do this kind of validation?

答:
if you have several checkbox groups, you just need to deine the attribute several times.

```<code>[AttributeUsage( AttributeTargets.Class)]
public class AtLeastOneCheckboxAttribute : ValidationAttribute
{
    private string[] _checkboxNames;

    public AtLeastOneCheckboxAttribute(params string[] checkboxNames)
    {
        _checkboxNames = checkboxNames;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var propertyInfos = value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(x=>_checkboxNames.Contains(x.Name));

        var values = propertyInfos.Select(x => x.GetGetMethod().Invoke(value, null));
        if (values.Any(x => Convert.ToBoolean(x)))
            return ValidationResult.Success;
        else
        {
            ErrorMessage = "At least one checkbox must be selected";
            return new ValidationResult(ErrorMessage);
        }
    }
}
</code>```

UPDATE

as  you have found out, class-level validation is called only after all properties pass. In order to get the error, just use empty string as the key.

Body:
I have an ASP.NET MVC 2 project in which I've created a data transfer object to receive data from a web page form. The form has two groups of checkboxes on it. I want to validate the object to make sure that at least one of the checkboxes in each group is checked.

I'm doing the validation on the server side so that a user won't be able to hack around any client-side validation. (I will add client-side validation with jQuery later; that's easy.)

My understanding is that I have to create my own custom ValidationAttribute for my data transfer object class, but I don't understand how to create and use one that can accept an arbitrary list of checkbox properties to make sure that at least one of them is true. I am guessing I will have to call the attributes like this:

[AtLeastOneCheckbox("set1check1", "set1check2", "set1check3",
    ErrorMessage = "You must check at least one checkbox in set 1.")]
[AtLeastOneCheckbox("set2check1", "set2check2", "set2check3", "set2check4", "set2check5",
    ErrorMessage = "You must check at least one checkbox in set 2.")]
public class MyFormDTO
{
    ...
}

What would the implementation of AtLeastOneCheckboxAttribute look like?

Or is there a different way that I should do this kind of validation?

Body:
if you have several checkbox groups, you just need to deine the attribute several times.

[AttributeUsage( AttributeTargets.Class)]
public class AtLeastOneCheckboxAttribute : ValidationAttribute
{
    private string[] _checkboxNames;

    public AtLeastOneCheckboxAttribute(params string[] checkboxNames)
    {
        _checkboxNames = checkboxNames;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var propertyInfos = value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(x=>_checkboxNames.Contains(x.Name));

        var values = propertyInfos.Select(x => x.GetGetMethod().Invoke(value, null));
        if (values.Any(x => Convert.ToBoolean(x)))
            return ValidationResult.Success;
        else
        {
            ErrorMessage = "At least one checkbox must be selected";
            return new ValidationResult(ErrorMessage);
        }
    }
}

UPDATE

as  you have found out, class-level validation is called only after all properties pass. In order to get the error, just use empty string as the key.


问:
Put content in shaped divs
I'm trying to make divs that are shaped like slices of a circle, using this code (this is for the top section of the circle) in CSS:

```<code>width: 0;
height: 0;
border-left: 250px solid transparent;
border-right: 250px solid transparent;
border-top: 250px solid #FFA8A8;
border-bottom: 250px solid transparent;
position: fixed;
border-radius: 100%;
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -250px;
</code>```

and that makes the divs show up the way I want them to on the page, but when I try to put any text into them, it doesn't show up. I think I get why (because the actual height and width of the div are 0 and what shows up on the page is just the border), but how would I make divs that look the same but can contain text or images?

答:
Using the code you provided, and going off possibly incorrect assumptions, I have come up with some code that will work for you. You can add text inside the div using absolute positioning and the top and left values to get your text where you would like it.

Changes Made:
Added flex to the body to center the slice. Took out width, height, position, top, left, and margin. Reduced the border radius to 50% since that is all that is needed to create the rounded edge. Reduced the border by 100px purely so that the example slice was not so big.

body{
  display:flex;
  align-items: center;
  justify-content:center;
}

.slice{
  border-left: 150px solid transparent;
  border-right: 150px solid transparent;
  border-top: 150px solid #FFA8A8;
  border-bottom: 150px solid transparent;
  border-radius: 50%;
}

p{
  position: absolute;
  left:39%;;
  top: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slice">
  <p>Some Text That Fits</p>
</div></code>```

Title: Put content in shaped divs

Body:
I'm trying to make divs that are shaped like slices of a circle, using this code (this is for the top section of the circle) in CSS:

width: 0;
height: 0;
border-left: 250px solid transparent;
border-right: 250px solid transparent;
border-top: 250px solid #FFA8A8;
border-bottom: 250px solid transparent;
position: fixed;
border-radius: 100%;
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -250px;

and that makes the divs show up the way I want them to on the page, but when I try to put any text into them, it doesn't show up. I think I get why (because the actual height and width of the div are 0 and what shows up on the page is just the border), but how would I make divs that look the same but can contain text or images?

Body:
Using the code you provided, and going off possibly incorrect assumptions, I have come up with some code that will work for you. You can add text inside the div using absolute positioning and the top and left values to get your text where you would like it.

Changes Made:
Added flex to the body to center the slice. Took out width, height, position, top, left, and margin. Reduced the border radius to 50% since that is all that is needed to create the rounded edge. Reduced the border by 100px purely so that the example slice was not so big.

body{
  display:flex;
  align-items: center;
  justify-content:center;
}

.slice{
  border-left: 150px solid transparent;
  border-right: 150px solid transparent;
  border-top: 150px solid #FFA8A8;
  border-bottom: 150px solid transparent;
  border-radius: 50%;
}

p{
  position: absolute;
  left:39%;;
  top: 30px;
}

<div class="slice">
  <p>Some Text That Fits</p>
</div>


问:
How to use Two border color using CSS
Firstly, I'm not good at English. Sorry T.T;;

I want to make a box like this, which has a border with two colors. I've been trying to make it using CSS border-color, but I cannot implement it. I hope to know any idea for this.

I do not want to have a duplicated div.  I want to use CSS only.

How can I design this using CSS ? pls T.T;;

This is what I have so far:

#box{
 margin-top:10px;
 width: 950px;
 height:100px;
 border:5px solid #f3f3f3;
 padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">

</div></code>```

Regards,

答:
What you are looking for is the CSS3 box-shadow.

#box{
margin-top:10px;
width: 950px;
height:100px;
border:5px solid #f3f3f3;
padding: 5px;
box-shadow: 0px 0px 0px 2px #ddd;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">
</div></code>```

When you apply the box-shadow with a 0px value for the x-offset and y-offset, you get the shadow on all four sides.  Furthermore with a 0px value for the blur, it ultimately looks like a border with two colors.

Title: How to use Two border color using CSS

Body:
Firstly, I'm not good at English. Sorry T.T;;

I want to make a box like this, which has a border with two colors. I've been trying to make it using CSS border-color, but I cannot implement it. I hope to know any idea for this.

I do not want to have a duplicated div.  I want to use CSS only.

How can I design this using CSS ? pls T.T;;

This is what I have so far:

#box{
 margin-top:10px;
 width: 950px;
 height:100px;
 border:5px solid #f3f3f3;
 padding: 5px;
}

Regards,

Body:
What you are looking for is the CSS3 box-shadow.

#box{
margin-top:10px;
width: 950px;
height:100px;
border:5px solid #f3f3f3;
padding: 5px;
box-shadow: 0px 0px 0px 2px #ddd;
}

<div id="box">
</div>

When you apply the box-shadow with a 0px value for the x-offset and y-offset, you get the shadow on all four sides.  Furthermore with a 0px value for the blur, it ultimately looks like a border with two colors.


问:
Scrape Data from coinmarketcap.com in R
Im trying to build a database of historical performance of Bitcoin and a few other larger coins. To do this I want to extract the main table from this URL (with these particular dates) into r:

https://coinmarketcap.com/currencies/bitcoin/historical-data/?start=20130428&end=20170705

What would be the best package and method to do this in r?

Thanks

答:
The rvest package is helpful here:

```<code>library(rvest)

url <-read_html("https://coinmarketcap.com/currencies/bitcoin/historical-data/?start=20130428&end=20170705")

table <- url %>%
  html_table() %>%
  as.data.frame()
</code>```

Title: Scrape Data from coinmarketcap.com in R

Body:
The rvest package is helpful here:

library(rvest)

url <-read_html("https://coinmarketcap.com/currencies/bitcoin/historical-data/?start=20130428&end=20170705")

table <- url %>%
  html_table() %>%
  as.data.frame()


答:
I see you define 14 chars for the string. So, when string length lower than 14, it will be filled empty character. Please try this</p>

```<code><?php
define('TEXT_LENGTH', 14);
$string = 'IRAWAN DWI';
$formattedText = str_pad($string, TEXT_LENGTH, ' ', STR_PAD_RIGHT);
$arrayText =  str_split($formattedText);
?>

<div style="display:inline;">
Name :
<table style="display:inline; position:absolute" width="400" border="1">
  <tr>
    <?php foreach ($arrayText as $char): ?>
      <td width="28"><div align="center"><?php echo $char; ?></div></td>
    <?php endforeach ?>
  </tr>
</table>
</code>```

Title: Split Characters in String With Defined Character Length

Body:
I have a constraint when creating a form to display values in a table column horizontally based on characters in php. Like the example below. How to separate each character according to column?

Name :

I

R

W

A

N

D

W

I

Body:
I see you define 14 chars for the string. So, when string length lower than 14, it will be filled empty character. Please try this

<?php
define('TEXT_LENGTH', 14);
$string = 'IRAWAN DWI';
$formattedText = str_pad($string, TEXT_LENGTH, ' ', STR_PAD_RIGHT);
$arrayText =  str_split($formattedText);
?>

<div style="display:inline;">
Name :
<table style="display:inline; position:absolute" width="400" border="1">
  <tr>
    <?php foreach ($arrayText as $char): ?>
      <td width="28"><div align="center"><?php echo $char; ?></div></td>
    <?php endforeach ?>
  </tr>
</table>


问:
Does a class reinitialize even if I only call one of its methods?
Assume I have this class:

```<code>class myTestClass():
    def __init__(self):
        pass

    def method(self, arbitrary_value):
        return arbitrary_value
</code>```

And I would only need it's method to take on an arbitrary value, as per this:

```<code>object = myTestClass()

while n_count > 10:
    print object.method(n_count)
</code>```

Even though I initialize my class before the loop, does it go through the constructor init each time it calls 'method'?

答:
You are not creating a new object every time, so init is not being called more than once (which happens when you run object = myTestClass() )

You are calling the same instance method 10 times.

Body:
Assume I have this class:

class myTestClass():
    def __init__(self):
        pass

    def method(self, arbitrary_value):
        return arbitrary_value

And I would only need it's method to take on an arbitrary value, as per this:

object = myTestClass()

while n_count > 10:
    print object.method(n_count)

Even though I initialize my class before the loop, does it go through the constructor init each time it calls 'method'?


问:
matlab 'evidence removio': delete last shown command
I would like to remove whatever I just typed - and the last shown command - from the matlab console display. Needless to say, this would be ideal for pranksters (but this is of course strictly for academic purposes only). This is as far as I have gotten (based on this related answer):

```<code>hist = com.mathworks.mlservices.MLCommandHistoryServices.getSessionHistory; %get history
last = strjoin(cell(hist(end-2:end)),' '); %convert history to string
fprintf(repmat('\b',1,numel(last))); %replace characters of string with whitespace
</code>```

However I can only access the last typed command (through the command history) - not the last displayed command (which would be ideal). Any ideas how to solve this?

答:
Disclaimer: I don't advise doing this.

The MATLAB CommandWindow contents are stored as a CmdWinDocument, which is an extension of the Java PlainDocument type, and an interface of the Document type. The current window can be accessed using the command:

```<code>com.mathworks.mde.cmdwin.CmdWinDocument.getInstance
</code>```

In theory, you should be able to remove text from the command window using something like:

```<code>doc = com.mathworks.mde.cmdwin.CmdWinDocument.getInstance
endpos = doc.getEndPosition
doc.remove(endpos-10,10)
</code>```

which would, in theory, remove the last 10 character from the document. You may have to call the removeUpdate function as well. Obviously problems will be caused by the fact that these commands will be appended to the document during this process. I have not tested this, and you're likely to cause problems with internally stored offsets within the CmdWinDocument class, so use at your own risk.

Body:
I would like to remove whatever I just typed - and the last shown command - from the matlab console display. Needless to say, this would be ideal for pranksters (but this is of course strictly for academic purposes only). This is as far as I have gotten (based on this related answer):

hist = com.mathworks.mlservices.MLCommandHistoryServices.getSessionHistory; %get history
last = strjoin(cell(hist(end-2:end)),' '); %convert history to string
fprintf(repmat('\b',1,numel(last))); %replace characters of string with whitespace

However I can only access the last typed command (through the command history) - not the last displayed command (which would be ideal). Any ideas how to solve this?

Body:
Disclaimer: I don't advise doing this.

The MATLAB CommandWindow contents are stored as a CmdWinDocument, which is an extension of the Java PlainDocument type, and an interface of the Document type. The current window can be accessed using the command:

com.mathworks.mde.cmdwin.CmdWinDocument.getInstance

In theory, you should be able to remove text from the command window using something like:

doc = com.mathworks.mde.cmdwin.CmdWinDocument.getInstance
endpos = doc.getEndPosition
doc.remove(endpos-10,10)

which would, in theory, remove the last 10 character from the document. You may have to call the removeUpdate function as well. Obviously problems will be caused by the fact that these commands will be appended to the document during this process. I have not tested this, and you're likely to cause problems with internally stored offsets within the CmdWinDocument class, so use at your own risk.


答:
```<code>      Conn.Open();
            Command.CommandText = "Select SUM(c_qty) from COLLVAULT_COINS WHERE c_type <>'US Currency' AND c_type<>'World Currency' AND c_type<>'World Coins' AND c_listName = '" + activeCollection + "'";
            int total_1 = Convert.ToInt32(Command.ExecuteScalar());
            //total records
            lblcollectedcount.Text = Convert.ToString(total_1);
            Conn.Close();
</code>```

I had to use <> as not equals to instead of !=

Title: How to get column count in ms access database from c#

Body:
I am trying to get a sum with a column from a ms access database but so not nothing has worked this is what I have

      Conn.Open();
            Command.CommandText = "Select SUM(c_qty) from COLLVAULT_COINS WHERE c_type!='US Currency' AND c_type!='World Currency' AND c_type!='World Coins' AND c_listName = '" + activeCollection + "'";
            int total_1 = Convert.ToInt32(Command.ExecuteScalar());
            //total sum - get how many match the query
            lblcollectedcount.Text = Convert.ToString(total_1);
            Conn.Close();

any help would be nice.

Body:
      Conn.Open();
            Command.CommandText = "Select SUM(c_qty) from COLLVAULT_COINS WHERE c_type <>'US Currency' AND c_type<>'World Currency' AND c_type<>'World Coins' AND c_listName = '" + activeCollection + "'";
            int total_1 = Convert.ToInt32(Command.ExecuteScalar());
            //total records
            lblcollectedcount.Text = Convert.ToString(total_1);
            Conn.Close();

I had to use <> as not equals to instead of !=


问:
python conditional constructor for giving object or None
I receive UDP packets with GPS data, and construct Position objects with them.
Sometimes, GPS loss satellite signal, but still send UDP packets with no valuable data. I would like the Position constructor gives me a 'None' object in this failure cases. So, I could check if process the Position or not. Something like that:

```<code>frameGPS = giveMeTheFrame()
position1 = Position(frameGPS)
if (position1 is None): don't process position1
else: process position1
</code>```

Is this a right way to do it?
If so, how could I implement this init?

答:
There are different ways you can approach this. The answer just posted by implementing __bool__ is a very good option too!

To provide another approach as well:

Per your comment on what is considered garbage data, and what is considered valid data. Let us say you receive valid characters as coordinates. To keep it simple:

N, S, E, W

One way, is you can have your class raise if it is given invalid data to properly instantiate an instance of that class:

```<code>def Position:
    def __init__(self, position):
        if position.upper() not in {'N', 'S', 'E', 'W'}:
            raise InvalidPositionData('Received unexpected data {}'.format(position))
        self.position = position
</code>```

In your code, you can simply wrap to catch that exception:

```<code>frameGPS = giveMeTheFrame()
try:
    position1 = Position(frameGPS)
except InvalidPositionData as exc:
    # do things with your exception here
    log.error('something bad happened')
# continue with logic here
</code>```

Body:
I receive UDP packets with GPS data, and construct Position objects with them.
Sometimes, GPS loss satellite signal, but still send UDP packets with no valuable data. I would like the Position constructor gives me a 'None' object in this failure cases. So, I could check if process the Position or not. Something like that:

frameGPS = giveMeTheFrame()
position1 = Position(frameGPS)
if (position1 is None): don't process position1
else: process position1

Is this a right way to do it?
If so, how could I implement this init?

Body:
There are different ways you can approach this. The answer just posted by implementing __bool__ is a very good option too!

To provide another approach as well:

Per your comment on what is considered garbage data, and what is considered valid data. Let us say you receive valid characters as coordinates. To keep it simple:

N, S, E, W

One way, is you can have your class raise if it is given invalid data to properly instantiate an instance of that class:

def Position:
    def __init__(self, position):
        if position.upper() not in {'N', 'S', 'E', 'W'}:
            raise InvalidPositionData('Received unexpected data {}'.format(position))
        self.position = position

In your code, you can simply wrap to catch that exception:

frameGPS = giveMeTheFrame()
try:
    position1 = Position(frameGPS)
except InvalidPositionData as exc:
    # do things with your exception here
    log.error('something bad happened')
# continue with logic here


问:
Camera2 api with Preview
I am using the Camera2 api to show a preview form the camera. I also want to implement a ImageReader to process the images. I have a Start preview function. When I call it the preview is just black. If I remove "mimageReader.getSurface()" from Arrays.asList() I am able to see the camera preview. How can I have a camera preview show up and also use ImageReader?</p>

```<code> private void startPreview()
  {
        List<Surface> outputSurfaces = new ArrayList<>();
        List surfaces = new ArrayList<>();

        SurfaceTexture surfaceTexture =  textureView.getSurfaceTexture();
        surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        Surface previewSurface = new Surface(surfaceTexture);

        try {
            mCaptureRequestBuilder = _cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

           mCaptureRequestBuilder.addTarget(previewSurface);

            _cameraDevice.createCaptureSession(Arrays.asList(previewSurface,mimageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {
                        @Override
                        public void onConfigured(CameraCaptureSession session) {
                            Log.d("", "onConfigured: startPreview");

                            try {
                                session.setRepeatingRequest( mCaptureRequestBuilder.build(),null,mthreadhandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(CameraCaptureSession session) {
                            Log.d("", "onConfigureFailed: startPreview");

                        }
                    }, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
</code>```

答:
You have to create a new instance of ImageReader, set its onImageAvailableListener(you can process the preview frames here) and add it to PreviewRequestBuilder. For example:</p>

```<code>mImageReader = ImageReader.newInstance(
                mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.YUV_420_888, 2);

mImageReader.setOnImageAvailableListener(mOnGetPreviewListener, mBackgroundHandler);

mPreviewRequestBuilder.addTarget(mImageReader.getSurface());
</code>```

Title: Camera2 api with Preview

Body:
I am using the Camera2 api to show a preview form the camera. I also want to implement a ImageReader to process the images. I have a Start preview function. When I call it the preview is just black. If I remove "mimageReader.getSurface()" from Arrays.asList() I am able to see the camera preview. How can I have a camera preview show up and also use ImageReader?

 private void startPreview()
  {
        List<Surface> outputSurfaces = new ArrayList<>();
        List surfaces = new ArrayList<>();

        SurfaceTexture surfaceTexture =  textureView.getSurfaceTexture();
        surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        Surface previewSurface = new Surface(surfaceTexture);

        try {
            mCaptureRequestBuilder = _cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

           mCaptureRequestBuilder.addTarget(previewSurface);

            _cameraDevice.createCaptureSession(Arrays.asList(previewSurface,mimageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {
                        @Override
                        public void onConfigured(CameraCaptureSession session) {
                            Log.d("", "onConfigured: startPreview");

                            try {
                                session.setRepeatingRequest( mCaptureRequestBuilder.build(),null,mthreadhandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(CameraCaptureSession session) {
                            Log.d("", "onConfigureFailed: startPreview");

                        }
                    }, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

Body:
You have to create a new instance of ImageReader, set its onImageAvailableListener(you can process the preview frames here) and add it to PreviewRequestBuilder. For example:

mImageReader = ImageReader.newInstance(
                mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.YUV_420_888, 2);

mImageReader.setOnImageAvailableListener(mOnGetPreviewListener, mBackgroundHandler);

mPreviewRequestBuilder.addTarget(mImageReader.getSurface());


问:
Jquery Updating input field value [Replace the old value with the new value]
For the current code,when the button's clicked, it'll get the value from the done input and display them to the 3 input field respectively.

Let say i'd like to change the value in the done input field, and when the value is updated, the old values from the 3 input fields will be replaced by the new.
Now, the updated value just added after the original value instead of replacing it. What's wrong with my code guys?

$(".ok").on('click', function() {
var set = $(this).closest('tr').find('.done').val();
if ( set ){
    $(this).closest('tr').find('.text').each(function(){
        $(this).val( $(this).val() + set );
    })
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>

    <td>
      <input type="button"  value="ok" class="ok"></td>
    <td>done<input type="text" value="100" class="done" \> </td>
    <td>text1<textarea class="text">hi</textarea> </td>
    <td>text2<textarea class="text">hello</textarea> </td>
    <td>text3<textarea class="text">sup</textarea> </td>

  </tr>
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script></code>```

答:
Try this instead:</p>

```<code>$(this).val( $(this).val(set));
</code>```

Body:
For the current code,when the button's clicked, it'll get the value from the done input and display them to the 3 input field respectively.

Let say i'd like to change the value in the done input field, and when the value is updated, the old values from the 3 input fields will be replaced by the new.
Now, the updated value just added after the original value instead of replacing it. What's wrong with my code guys?

$(".ok").on('click', function() {
var set = $(this).closest('tr').find('.done').val();
if ( set ){
    $(this).closest('tr').find('.text').each(function(){
        $(this).val( $(this).val() + set );
    })
}
});

      <input type="button"  value="ok" class="ok">
    done<input type="text" value="100" class="done" \>
    text1<textarea class="text">hi</textarea>
    text2<textarea class="text">hello</textarea>
    text3<textarea class="text">sup</textarea>

Body:
Try this instead:

$(this).val( $(this).val(set));