问:
MySQL database with unique fields ignored ending spaces
My projects requires to start inputs from the user with the spacing on the left and spacing on the right of a word, for example 'apple'. If the user types in ' apple' or 'apple ', whether it is one space or multiple space on the left or right of the word, I need to store it that way.

This field has the Unique attribute, but I attempt to insert the word with spacing on the left, and it works fine. But when I attempt to insert the word with spacing on the right it trims off all the spacing from the right of the word.

So I am thinking of adding a special character to the right of the word after the spacing. But I am hoping there is a better solution for this issue.

```<code>CREATE TABLE strings
( id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
string varchar(255) COLLATE utf8_bin NOT NULL,
created_ts timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id), UNIQUE KEY string (string) )
ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
</code>```

答:
Thanks to @kennethc. His answer works for me.
Add a string length field to the table and to the unique key.

```<code>CREATE TABLE strings
( id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
string varchar(255) COLLATE utf8_bin NOT NULL,
created_ts timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
string_length int(3),
PRIMARY KEY (id), UNIQUE KEY string (string,string_length) )
ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
</code>```

In MySQL it's possible to update the string length field with couple of triggers like this:

```<code>CREATE TRIGGER `string_length_insert` BEFORE INSERT ON `strings` FOR EACH ROW SET NEW.string_length = char_length(NEW.string);
CREATE TRIGGER `string_length_update` BEFORE UPDATE ON `strings` FOR EACH ROW SET NEW.string_length = char_length(NEW.string);
</code>```

Body:
My projects requires to start inputs from the user with the spacing on the left and spacing on the right of a word, for example 'apple'. If the user types in ' apple' or 'apple ', whether it is one space or multiple space on the left or right of the word, I need to store it that way.

This field has the Unique attribute, but I attempt to insert the word with spacing on the left, and it works fine. But when I attempt to insert the word with spacing on the right it trims off all the spacing from the right of the word.

So I am thinking of adding a special character to the right of the word after the spacing. But I am hoping there is a better solution for this issue.

CREATE TABLE strings
( id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
string varchar(255) COLLATE utf8_bin NOT NULL,
created_ts timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id), UNIQUE KEY string (string) )
ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin

Body:
Thanks to @kennethc. His answer works for me.
Add a string length field to the table and to the unique key.

CREATE TABLE strings
( id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
string varchar(255) COLLATE utf8_bin NOT NULL,
created_ts timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
string_length int(3),
PRIMARY KEY (id), UNIQUE KEY string (string,string_length) )
ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin

In MySQL it's possible to update the string length field with couple of triggers like this:

CREATE TRIGGER `string_length_insert` BEFORE INSERT ON `strings` FOR EACH ROW SET NEW.string_length = char_length(NEW.string);
CREATE TRIGGER `string_length_update` BEFORE UPDATE ON `strings` FOR EACH ROW SET NEW.string_length = char_length(NEW.string);


来源: stackexchange

问:
What is the difference between an Azure tenant and Azure subscription?
I am struggling to distinguish how an Azure Subscription and an Azure tenant are different? I have tried figuring it out using examples but each time I come to the conclusion that they are the same thing in a way? If a tenant is a dedicated instance of the Azure AD service that an organization receives and owns when it signs up for a Microsoft cloud service, then is that not what a subscription is too?</p>

答:
Azure tenant is a directory. Azure subscription is an object that represents a "folder" that you can put resources in. Subscriptions are tied to tenants. so 1 tenant can have many subscriptions, but not vice versa.

Link:

https://learn.microsoft.com/en-us/azure/azure-subscription-service-limits

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Two libraries bring in different version of the same dependency. How to import them both?
I have the following situation:

```<code>+ DentistApp
   L TreatsLibrary
     L IceCream 1.0
   L CavityCausesLib
     L IceCream 2.0
</code>```

Now I get a VerifyError because TreatsLibrary is using IceCream.giveToKidAfterDrill() which was removed in version 2.0 because of legal reasons.

How do I import both versions and make sure that each uses its own?

答:
This answer assumes you're talking about how to load these libraries from a packaged uber JAR at runtime.

You need to shade your dependencies using sbt-assembly.
This can be done as follows:

```<code>assemblyShadeRules in assembly ++= Seq(
  ShadeRule.rename("IceCream.**" -> "my_icecream.@1")
    .inLibrary("com.library.treats" % "TreatsLibrary" % "1.0.0")
    .inProject
)
</code>```

This will shade the IceCream dependency in your com.library.treats and change every package name to begin with my_icecream.

Body:
I have the following situation:

+ DentistApp
   L TreatsLibrary
     L IceCream 1.0
   L CavityCausesLib
     L IceCream 2.0

Now I get a VerifyError because TreatsLibrary is using IceCream.giveToKidAfterDrill() which was removed in version 2.0 because of legal reasons.

How do I import both versions and make sure that each uses its own?

Body:
This answer assumes you're talking about how to load these libraries from a packaged uber JAR at runtime.

You need to shade your dependencies using sbt-assembly.
This can be done as follows:

assemblyShadeRules in assembly ++= Seq(
  ShadeRule.rename("IceCream.**" -> "my_icecream.@1")
    .inLibrary("com.library.treats" % "TreatsLibrary" % "1.0.0")
    .inProject
)

This will shade the IceCream dependency in your com.library.treats and change every package name to begin with my_icecream.


问:
Eclipse: key binding for getting a list of attributes of a class
In Eclipse, Ctrl + O gives a list of all methods available in the class. Do you know any key binding that gives a list of all attributes of a certain class? </p>

答:
The contents of the Outline view are editor specific. When viewing Java classes, the Outline view of Eclipse shows the attributes of the class, too.

Maybe you've just hidden your fields. This can be done by the following icon:


问:
Apply different style to last x characters of input field
I am faced with a task as of current I am not sure on how to complete. Essentially, is there any way I could go about getting the last x characters of an  field to display differently from the rest of the field?

Something to the effect of this, assuming this was a typed input into an <input> field:
"TheLast6LettersOfThisShouldBeBigger"

That would be the intended effect. The only potential approach I could think of for completing this is to use two separate input fields and always have the last x characters in the second input styled differently. This would, however, provide problems with user interaction (backspacing at the front of the second input field would result in no previous character being deleted).

Any ideas or thoughts?

Update: I forget to mention before, this is intended to be a dynamic thing as the user is typing.

答:
On buttonClick; what u typed in input box is tweaked such that last 6 strings are in bold fonts.

document.getElementById("boldStringButton").onclick = function() {
  let thestring = document.getElementById("inputBox").value;
  var backslice = thestring.slice(thestring.length - 6);
  var frontslice = thestring.substr(0, thestring.length - 6)
  var newBoldedString = frontslice + "" + backslice + "";

  document.getElementById("boldedString").innerHTML = newBoldedString;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="inputBox">
<button id="boldStringButton">
Embolden string
</button>
<div id="boldedString">

</div>
<div>
  Enter text and hit button to embolden last 6 strings
</div></code>```

Body:
On buttonClick; what u typed in input box is tweaked such that last 6 strings are in bold fonts.

document.getElementById("boldStringButton").onclick = function() {
  let thestring = document.getElementById("inputBox").value;
  var backslice = thestring.slice(thestring.length - 6);
  var frontslice = thestring.substr(0, thestring.length - 6)
  var newBoldedString = frontslice + "<b>" + backslice + "</b>";

  document.getElementById("boldedString").innerHTML = newBoldedString;
}

<input id="inputBox">
<button id="boldStringButton">
Embolden string
</button>
<div id="boldedString">

</div>
<div>
  Enter text and hit button to embolden last 6 strings
</div>


问:
Why Icon element require Id attribute to end with '.exe' or '.ico'
Why Icon for Shortcut element should have Id attribute ending with '.ico' or '.exe'?

So this code

```<code><Icon Id="ProgramIcon" SourceFile="Images\MyAppIcon.ico"/>

<Component Guid="MY_GUID" Id="MyAppComponent">
    <File Source="MyApp.exe" Name="MyApp.exe" Id="MyApp.exe">
        <Shortcut Id="MyApp.Shortcut" Directory="ApplicationProgramMenuDir" WorkingDirectory="INSTALLDIR" Name="MyApp" Icon="ProgramIcon" Advertise="yes" />
    </File>
</Component>
</code>```

generates compile error:

```<code>error LGHT0204: ICE50: The extension of Icon 'ProgramIcon' for Shortcut 'MyApp.Shortcut' does not match the extension of the Key File for component 'MyAppComponent'. [D:\APPS\MyProject.wixproj]
</code>```

but this code

```<code><Icon Id="ProgramIcon.ico" SourceFile="Images\MyAppIcon.ico"/>

<Component Guid="MY_GUID" Id="MyAppComponent">
    <File Source="MyApp.exe" Name="MyApp.exe" Id="MyApp.exe">
        <Shortcut Id="MyApp.Shortcut" Directory="ApplicationProgramMenuDir" WorkingDirectory="INSTALLDIR" Name="MyApp" Icon="ProgramIcon.ico" Advertise="yes" />
    </File>
</Component>
</code>```

compiles fine.

It's first time I see such limitations for Id attribute of any element and it looks very strange. I don't see any reason for this even to be a warning. So I don't understand some basics of this functionality. Please help me understand the reasons of described behavior.

答:
I think I may be able to shed some light on this.

It likely has to do with the fact that id ends up being the name of the file containing the icon. It would hazard a guess that it uses the file extension to determine which parser to use.

How I stumbled upon this?

Seemingly unrelated, I am investigating an issue where the Windows Event logs is filled with SxS errors originating from our application. But the path is all wrong:

C:\Windows\Installer\{Guid}\ProductIcon.exe

Incidentally, ProductIcon.exe this is the icon id we use.

Upon closer inspection, I see that this file is a copy of our product's executable. The reason we  get the SxS errors is that it only copies the executable and none of the referenced dll-s.

Body:
Why Icon for Shortcut element should have Id attribute ending with '.ico' or '.exe'?

So this code

<Icon Id="ProgramIcon" SourceFile="Images\MyAppIcon.ico"/>

<Component Guid="MY_GUID" Id="MyAppComponent">
    <File Source="MyApp.exe" Name="MyApp.exe" Id="MyApp.exe">
        <Shortcut Id="MyApp.Shortcut" Directory="ApplicationProgramMenuDir" WorkingDirectory="INSTALLDIR" Name="MyApp" Icon="ProgramIcon" Advertise="yes" />
    </File>
</Component>

generates compile error:

error LGHT0204: ICE50: The extension of Icon 'ProgramIcon' for Shortcut 'MyApp.Shortcut' does not match the extension of the Key File for component 'MyAppComponent'. [D:\APPS\MyProject.wixproj]

but this code

<Icon Id="ProgramIcon.ico" SourceFile="Images\MyAppIcon.ico"/>

<Component Guid="MY_GUID" Id="MyAppComponent">
    <File Source="MyApp.exe" Name="MyApp.exe" Id="MyApp.exe">
        <Shortcut Id="MyApp.Shortcut" Directory="ApplicationProgramMenuDir" WorkingDirectory="INSTALLDIR" Name="MyApp" Icon="ProgramIcon.ico" Advertise="yes" />
    </File>
</Component>

compiles fine.

It's first time I see such limitations for Id attribute of any element and it looks very strange. I don't see any reason for this even to be a warning. So I don't understand some basics of this functionality. Please help me understand the reasons of described behavior.


问:
Destroy previous setInterval
I want a function to set an Ajax and a reload timer.  The code below doesn't destroy the previous function call timer, so each time I invoke it I get another timer.  How can I destroy the previous timer?</p>

```<code>function initNowPlayingMeta(station) {
    $('#cancion').children().remove();
    $('#cancion').load('sonando.php?emisora=' + station);
    var prevNowPlaying = setInterval(function () {
        $('#cancion').load('sonando.php?emisora=' + station);
    }, 5000);
}
</code>```

答:
You need to store your timer reference somewhere outside of local scope (this essentially means declaring it with var outside of the function).  Then, clear it with clearInterval:

```<code>var prevNowPlaying = null;

function initNowPlayingMeta(station) {
    if(prevNowPlaying) {
        clearInterval(prevNowPlaying);
    }
    $('#cancion').children().remove();
    $('#cancion').load('sonando.php?emisora=' + station);
    prevNowPlaying = setInterval(function () {
        $('#cancion').load('sonando.php?emisora=' + station);
    }, 5000);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Destroy previous setInterval

Body:
I want a function to set an Ajax and a reload timer.  The code below doesn't destroy the previous function call timer, so each time I invoke it I get another timer.  How can I destroy the previous timer?

function initNowPlayingMeta(station) {
    $('#cancion').children().remove();
    $('#cancion').load('sonando.php?emisora=' + station);
    var prevNowPlaying = setInterval(function () {
        $('#cancion').load('sonando.php?emisora=' + station);
    }, 5000);
}

Body:
You need to store your timer reference somewhere outside of local scope (this essentially means declaring it with var outside of the function).  Then, clear it with clearInterval:

var prevNowPlaying = null;

function initNowPlayingMeta(station) {
    if(prevNowPlaying) {
        clearInterval(prevNowPlaying);
    }
    $('#cancion').children().remove();
    $('#cancion').load('sonando.php?emisora=' + station);
    prevNowPlaying = setInterval(function () {
        $('#cancion').load('sonando.php?emisora=' + station);
    }, 5000);
}


问:
QBChatDialog is not work this dependency on:
1:-this dependency is not work on QBChatDialog but QBSettings is work:

```<code>compile "com.quickblox:quickblox-android-sdk-core:2.5.1@aar"
compile("com.quickblox:quickblox-android-sdk-chat:2.5.1@aar") {
    transitive=true
}
</code>```

2:-this dependency is not work on QBSettings but QBChatDialog  is working, so how can i solve this issues in android quickblox:

```<code>compile 'com.quickblox:quickblox-android-sdk-core:3.3.0@aar'
    compile("com.quickblox:quickblox-android-sdk-chat:3.3.0@aar") {
        transitive = true
    }
</code>```

答:
Use the dependencies listed below :</p>

```<code>compile 'com.quickblox:quickblox-android-sdk-videochat-webrtc:3.3.3@aar'
compile 'com.quickblox:quickblox-android-sdk-content:3.3.3@aar'
compile('com.quickblox:quickblox-android-sdk-chat:3.3.3@aar') {
    transitive = true
}
</code>```

Body:
1:-this dependency is not work on QBChatDialog but QBSettings is work:

compile "com.quickblox:quickblox-android-sdk-core:2.5.1@aar"
compile("com.quickblox:quickblox-android-sdk-chat:2.5.1@aar") {
    transitive=true
}

2:-this dependency is not work on QBSettings but QBChatDialog  is working, so how can i solve this issues in android quickblox:

compile 'com.quickblox:quickblox-android-sdk-core:3.3.0@aar'
    compile("com.quickblox:quickblox-android-sdk-chat:3.3.0@aar") {
        transitive = true
    }

Body:
Use the dependencies listed below :

compile 'com.quickblox:quickblox-android-sdk-videochat-webrtc:3.3.3@aar'
compile 'com.quickblox:quickblox-android-sdk-content:3.3.3@aar'
compile('com.quickblox:quickblox-android-sdk-chat:3.3.3@aar') {
    transitive = true
}


问:
Error exporting rep checkout in script
I get this error when trying to export a rep checkout to a folder using a bash script:

```<code>svn: E125001: Couldn't determine absolute path of '.'
svn: E000002: No such file or directory
</code>```

Performing the same export command in Terminal works.

答:
it seems you deleted the directory
so check if the directory exists
to solve it</p>

```<code>cd ..
mkdir <your_direvtory_again>
cd <your_direvtory_again>
</code>```

Title: Error exporting rep checkout in script

Body:
I get this error when trying to export a rep checkout to a folder using a bash script:

svn: E125001: Couldn't determine absolute path of '.'
svn: E000002: No such file or directory

Performing the same export command in Terminal works.

Body:
it seems you deleted the directory
so check if the directory exists
to solve it

cd ..
mkdir <your_direvtory_again>
cd <your_direvtory_again>


问:
Sass error : Invalid CSS after "typography-config" angular 4.x
I want to integrate my custom fonts for my angular 4.x project which are in assets folder. and I am using angular material. so for material I am setting custom typography in my styles.sass

Here's the code:

```<code>@import '~@angular/material/theming'

$used-fonts : 'Avenir', arial

$general-typography : mat-typography-config(
  $font-family: quote($used-fonts)
)

@include mat-core($general-typography)
</code>```

The error which I got:

```<code>Invalid CSS after "...ography-config(": expected expression (e.g. 1px, bold), was "{"
</code>```

giving me an error at :

any idea?

答:
I suggest You should try within one line. it will consider it as nested value</p>

```<code>$general-typography : mat-typography-config($font-family: quote($used-fonts))
</code>```

Body:
I want to integrate my custom fonts for my angular 4.x project which are in assets folder. and I am using angular material. so for material I am setting custom typography in my styles.sass

Here's the code:

@import '~@angular/material/theming'

$used-fonts : 'Avenir', arial

$general-typography : mat-typography-config(
  $font-family: quote($used-fonts)
)

@include mat-core($general-typography)

The error which I got:

Invalid CSS after "...ography-config(": expected expression (e.g. 1px, bold), was "{"

giving me an error at :

any idea?

Body:
I suggest You should try within one line. it will consider it as nested value

$general-typography : mat-typography-config($font-family: quote($used-fonts))


问:
can someone please explain how this jquery code works
i picked this code online but i'm unable to understand how it works. without understanding i cannot edit it for my use. it is for closing a panel by up-slide when i click on "x" button. i want to know how is the effect created in the script?
here is the html:

```<code><div class="col-md-3 col-sm-6 col-xs-6">
    <div class="panel panel-info">
        <div class="panel-heading">
            <h3 class="panel-title">Using Slide Up</h3>
            <span class="pull-right clickable" data-effect="slideUp">x</span>
        </div>
        <div class="panel-body">Panel content</div>
        <div class="panel-footer">Panel footer</div>
    </div>
</div>
</code>```

the script working on this is:

```<code>    $(function() {
        $('.clickable').on('click', function() {
            var effect = $(this).data('effect');
            $(this).closest('.panel')[effect]();
        });
    });
</code>```

答:
```<code>$('.clickable')
</code>```

This is your jquery selector. It grabs all elements with the class "clickable" (the dot represents class. if it had been "#clickable" it would look for any element with the id of clickable)

```<code>.on('click', function() {
}
</code>```

Now for all your selected elements, we're wiring up a click event. When the element selected is clicked, then the function will run.

```<code>var effect = $(this).data('effect');
</code>```

In this line, we're setting the variable "effect" to have the value of the data property "data-effect" from the clicked element (which can be referenced in the function using the keyword "this"). The ".data" method returns all properties that are prefixed "data-".

```<code>$(this).closest('.panel')[effect]();
</code>```

Here we're now searching for the closest element with the class "panel" to our clicked element (which, remember, can be referenced in the function using "this").

As "effect" is a variable, the code

```<code>.[effect]()
</code>```

is identical (in your example) to coding (as your data-effect="slideUp" in the html)

```<code>.slideUp()
</code>```

In JavaScript, you can use either dot notation or bracket notation interchangeably.

Hope this helps

Body:
i picked this code online but i'm unable to understand how it works. without understanding i cannot edit it for my use. it is for closing a panel by up-slide when i click on "x" button. i want to know how is the effect created in the script?
here is the html:

Using Slide Up

            x

Panel content

Panel footer

the script working on this is:

    $(function() {
        $('.clickable').on('click', function() {
            var effect = $(this).data('effect');
            $(this).closest('.panel')[effect]();
        });
    });

Body:
$('.clickable')

This is your jquery selector. It grabs all elements with the class "clickable" (the dot represents class. if it had been "#clickable" it would look for any element with the id of clickable)

.on('click', function() {
}

Now for all your selected elements, we're wiring up a click event. When the element selected is clicked, then the function will run.

var effect = $(this).data('effect');

In this line, we're setting the variable "effect" to have the value of the data property "data-effect" from the clicked element (which can be referenced in the function using the keyword "this"). The ".data" method returns all properties that are prefixed "data-".

$(this).closest('.panel')[effect]();

Here we're now searching for the closest element with the class "panel" to our clicked element (which, remember, can be referenced in the function using "this").

As "effect" is a variable, the code

.[effect]()

is identical (in your example) to coding (as your data-effect="slideUp" in the html)

.slideUp()

In JavaScript, you can use either dot notation or bracket notation interchangeably.

Hope this helps


问:
Sql Design Question
I have a table with 25 columns where 20 columns can have null values for some (30-40%) rows.
Now what is the cost of having rows with 20 null columns? Is this OK?

Or

is it a good design to have another table to store those 20 columns and add a ref to the first table?
This way I will only write to the second table only when there is are values.

I am using SQL server 2005. Will migrate to 2008 in future.

Only 20 columns are varchar, rest smallint, smalldate

What I am storing:
  These columns store different attributes of the row it belongs to. These attributes can be null sometimes.

The table will hold ~billion of rows

Please comment.

答: Are there some circumstances where some of those columns are required? If so, then perhaps you should use some form of inheritance. For instance, if this were information about patients in a hospital, and there was some data that only made sense for female patients, then you could create a FemalePatients table with those columns. Those columns that must always be collected for female patients could then be declared NOT NULL in that separate table.

Title: Sql Design Question


问:
How can I stub a constructor in node.js using sinon in a Cloud Functions for Firebase project?
I'm using GeoFire in a Cloud Functions for Firebase project I want to unit test.

In my original code GeoFire is used like this:

```<code>GeoFire = request('geofire');

...

var catGeoFire = new GeoFire(catGeofireRef);
return catGeoFire.set(storeId, [lat, lon]).then( () => {
    console.log("Added store " + storeId + " to GeoFire" );
        return Promise.resolve();
    });
</code>```

I need to stub both the call to the GeoFire constructor and the GeoFire().set() method.

I tried:

```<code>const geofireStub = sinon.stub(GeoFire, 'set').resolves();
</code>```

But I received the error:

```<code>TypeError: Cannot stub non-existent own property set
</code>```

I also tried:

```<code>const setStub = sinon.stub().resolves();
const geofireStub = sinon.stub(GeoFire).returns({set: setStub});
</code>```

And I receive the error:

```<code>TypeError: Cannot stub non-existent own property set
</code>```

Both errors happen at the geofireStub line.

Reading the sinon documentation I understood that I can stub an object's methods. However in this case GeoFire isn't an object; it is a constructor function. So I don't really know how can I stub it without having an associated object.

Thanks!

答:
GeoFire is the constructor, but set is an instance method.
You should stub GeoFire.prototype I believe.

sinon.stub(GeoFire.prototype, 'set').resolves();
```

Body:
I'm using GeoFire in a Cloud Functions for Firebase project I want to unit test.

In my original code GeoFire is used like this:

GeoFire = request('geofire');

...

var catGeoFire = new GeoFire(catGeofireRef);
return catGeoFire.set(storeId, [lat, lon]).then( () => {
    console.log("Added store " + storeId + " to GeoFire" );
        return Promise.resolve();
    });

I need to stub both the call to the GeoFire constructor and the GeoFire().set() method.

I tried:

const geofireStub = sinon.stub(GeoFire, 'set').resolves();

But I received the error:

TypeError: Cannot stub non-existent own property set

I also tried:

const setStub = sinon.stub().resolves();
const geofireStub = sinon.stub(GeoFire).returns({set: setStub});

And I receive the error:

TypeError: Cannot stub non-existent own property set

Both errors happen at the geofireStub line.

Reading the sinon documentation I understood that I can stub an object's methods. However in this case GeoFire isn't an object; it is a constructor function. So I don't really know how can I stub it without having an associated object.

Thanks!


问:
Formula for first day of next quarter excel
Could you please help construct a formula to pull the first day of next quarter from today date in Excel? I tried this one

```<code>=DATE(YEAR(D1),3*INT((MONTH(D1)-1)/3)+1,1)
</code>```

but it actually pulls the first day of the current quarter instead.

Thanks

答:
You need to ceil the month (as number) to significance of 3, and then deduct 2 from the result. So, you will always catch the first month number from any date.</p>

```<code>=DATE(YEAR(C10),CEILING(MONTH(C10),3)-2,1)
</code>```

Body:
Could you please help construct a formula to pull the first day of next quarter from today date in Excel? I tried this one

=DATE(YEAR(D1),3*INT((MONTH(D1)-1)/3)+1,1)

but it actually pulls the first day of the current quarter instead.

Thanks

Body:
You need to ceil the month (as number) to significance of 3, and then deduct 2 from the result. So, you will always catch the first month number from any date.

=DATE(YEAR(C10),CEILING(MONTH(C10),3)-2,1)


问:
Run Asp Website On IIS or Asp Developement Server
I have created a full website and everything ok in my laptop at home
and I can run it from visual studio and when I run it this notification shows on my taskbar like image below

the problem is my website is ok in my home but when I copy it on flash and put in the University PC its not running well because its run on IIS localhost and i want to run on Asp development server like in home
I tried to creat a empety website on university pc and copy my website in there but its not working
i get this error over and over when i run

this application defines configuration in the system.web/httpmodules section

I hope you understand me!

答: Development server as name suggests is only for development purpose and will only be accessed by you. If you want it to be accessible over internet then need to deploy on web server, IIS. In such case it will not use the local port anymore and rather use port 80 (http) or 443(https)</p>


问:
Can I pickle Python objects in memory instead of a physical file?
I have seen and written code to pickle objects in Python. But they all create physical file to contain data. I want that I write the data in memory and read it and pickle it and transfer it.

Is it even possible ?

```<code>from PIL import ImageGrab
import io
import codecs
import pickle

# Model class to send Process Data to the server
class ProcessData:
 process_id = 0
 project_id = 0
 task_id = 0
 start_time = 0
 end_time = 0
 user_id = 0
 weekend_id = 0

# Model class to send image data to the server
class ProcessScreen:
 process_id = 0
 image_data = bytearray()

image_name = "Dharmindar_screen.jpg"
ImageGrab.grab().save(image_name,"JPEG")

image_data = None
with codecs.open(image_name,'rb') as image_file:
 image_data = image_file.read()

serialized_process_data = io.BytesIO()

process_data = ProcessData()
process_data.process_id = 1
process_data.project_id = 2
process_data.task_id = 3
process_data.user_id = 4
process_data.weekend_id = 5
process_data.start_time = 676876
process_data.end_time = 787987

process_screen = ProcessScreen()
process_screen.process_id = process_data.process_id
process_screen.image_data = image_data

prepared_process_data = (process_data, process_screen)

process_data_serializer = pickle.Pickler()
process_data_serializer(serialized_process_data).dump(prepared_process_data)

print('Data serialized.')

if process_data_serializer is not None:
    d = process_data_serializer.getvalue()
    deserialized_data = None
    with open(d, 'rb') as serialized_data_file:
        process_deserializer = pickle.Unpickler(serialized_data_file)
        deserialized_data = process_deserializer.load()
else:
    print('Empty')
</code>```

The above code throws the TypeError: Required argument 'file' (pos 1) not found

答:
The File object you pass to pickle.dump just needs a write method, see https://docs.python.org/2/library/pickle.html#pickle.dump

file must have a write() method that accepts a single string argument. It can thus be a file object opened for writing, a StringIO object, or any other custom object that meets this interface.

Instead of using a StringIO object, you could even create your own class to store the pickled data, for example

```<code>class MyFile(object):
    def __init__(self):
        self.data = []
    def write(self, stuff):
        self.data.append(stuff)
</code>```

and then just pickle to an instance of this class:

```<code>class ExampleClass(object):
    def __init__(self, x):
        self.data = x
a = ExampleClass(123)
f = MyFile()
pickle.dump(a, f)
</code>```

Another option is, as proposed by @rawing, is to use pickle.dumps which will directly return a string that you can use, compare here.

Body:
I have seen and written code to pickle objects in Python. But they all create physical file to contain data. I want that I write the data in memory and read it and pickle it and transfer it.

Is it even possible ?

from PIL import ImageGrab
import io
import codecs
import pickle

# Model class to send Process Data to the server
class ProcessData:
 process_id = 0
 project_id = 0
 task_id = 0
 start_time = 0
 end_time = 0
 user_id = 0
 weekend_id = 0

# Model class to send image data to the server
class ProcessScreen:
 process_id = 0
 image_data = bytearray()

image_name = "Dharmindar_screen.jpg"
ImageGrab.grab().save(image_name,"JPEG")

image_data = None
with codecs.open(image_name,'rb') as image_file:
 image_data = image_file.read()

serialized_process_data = io.BytesIO()

process_data = ProcessData()
process_data.process_id = 1
process_data.project_id = 2
process_data.task_id = 3
process_data.user_id = 4
process_data.weekend_id = 5
process_data.start_time = 676876
process_data.end_time = 787987

process_screen = ProcessScreen()
process_screen.process_id = process_data.process_id
process_screen.image_data = image_data

prepared_process_data = (process_data, process_screen)

process_data_serializer = pickle.Pickler()
process_data_serializer(serialized_process_data).dump(prepared_process_data)

print('Data serialized.')

if process_data_serializer is not None:
    d = process_data_serializer.getvalue()
    deserialized_data = None
    with open(d, 'rb') as serialized_data_file:
        process_deserializer = pickle.Unpickler(serialized_data_file)
        deserialized_data = process_deserializer.load()
else:
    print('Empty')

The above code throws the TypeError: Required argument 'file' (pos 1) not found

Body:
The File object you pass to pickle.dump just needs a write method, see https://docs.python.org/2/library/pickle.html#pickle.dump

file must have a write() method that accepts a single string argument. It can thus be a file object opened for writing, a StringIO object, or any other custom object that meets this interface.

Instead of using a StringIO object, you could even create your own class to store the pickled data, for example

class MyFile(object):
    def __init__(self):
        self.data = []
    def write(self, stuff):
        self.data.append(stuff)

and then just pickle to an instance of this class:

class ExampleClass(object):
    def __init__(self, x):
        self.data = x
a = ExampleClass(123)
f = MyFile()
pickle.dump(a, f)

Another option is, as proposed by @rawing, is to use pickle.dumps which will directly return a string that you can use, compare here.


问:
xsl replace source xml by second xml with untouched element that not exist at second xml
I have xsl transformation that copy element from source XML and replace elements from second xml that match and generate finaly XML. It working, but when a element not exist at a second xml than copy element empty ().
I need copy untouched elements from source that not exist at second xml.

For example: First XML contained

```<code><SHOP>
 <SHOPITEM>
  <CATEGORYTEXT>some ways</CATEGORYTEXT>
  <PRODUKT_ID>80002158</PRODUKT_ID>
  <PRODUCT>Zvedák 5t</PRODUCT>
  <PRODUCTNAME>Zvedák 5t</PRODUCTNAME>
  <ZBOZI_PRODUCTNO>t2</ZBOZI_PRODUCTNO>
  <OZNACENO>0</OZNACENO>
 </SHOPITEM>
 <SHOPITEM>
  <CATEGORYTEXT>VÝPRODEJ</CATEGORYTEXT>
  <PRODUKT_ID>80002419</PRODUKT_ID>
  <PRODUCT>3d Dochucovací sada Renga</ZPRODUCT>
  <PRODUCTNAME>3d Dochucovací sada Renga</PRODUCTNAME>
  <ZBOZI_PRODUCTNO>vv61</ZBOZI_PRODUCTNO>
  <OZNACENO>0</OZNACENO>
 </SHOPITEM>
</SHOP>
</code>```

Second xml contain ...

```<code><dataroot>
 <zbozi_FEED_DATA>
  <ZBOZI_CELA_CESTA>Heureka.cz | Auto-moto | Autodíly | Ramena řízení</ZBOZI_CELA_CESTA>
  <PRODUKT_ID>80002158</PRODUKT_ID>
  <ZBOZI_PRODUCT>Zvedák - panenka 5t</ZBOZI_PRODUCT>
  <ZBOZI_PRODUCTNAME>Zvedák - panenka 5t</ZBOZI_PRODUCTNAME>
  <ZBOZI_PRODUCTNO>t2</ZBOZI_PRODUCTNO>
  <OZNACENO>0</OZNACENO>
 </zbozi_FEED_DATA>
</dataroot>
</code>```

And desire output xml:

```<code> <SHOP>
  <SHOPITEM>
   <zbozi_FEED_DATA>
   <CATEGORYTEXT>Heureka.cz | Auto-moto | Autodíly | Ramena řízení</CATEGORYTEXT>
   <PRODUKT_ID>80002158</PRODUKT_ID>
   <PRODUCT>Zvedák - panenka 5t</PRODUCT>
   <PRODUCTNAME>Zvedák - panenka 5t</PRODUCTNAME>
   <ZBOZI_PRODUCTNO>t2</ZBOZI_PRODUCTNO>
   <OZNACENO>0</OZNACENO>
  </SHOPITEM>
  <SHOPITEM>
   <CATEGORYTEXT>VÝPRODEJ</CATEGORYTEXT>
   <PRODUKT_ID>80002419</PRODUKT_ID>
   <PRODUCT>3d Dochucovací sada Renga</PRODUCT>
   <PRODUCTNAME>3d Dochucovací sada Renga</PRODUCTNAME>
   <ZBOZI_PRODUCTNO>vv61</ZBOZI_PRODUCTNO>
   <OZNACENO>0</OZNACENO>
  </SHOPITEM>
</SHOP>
</code>```

But now is wrong output:

```<code> <SHOP>
  <SHOPITEM>
   <zbozi_FEED_DATA>
    <CATEGORYTEXT>Heureka.cz | Auto-moto | Autodíly | Ramena řízení</CATEGORYTEXT>
    <ITEM_IDD>80002158</ITEM_ID>
    <PRODUCT>Zvedák - panenka 5t</PRODUCT>
    <PRODUCTNAME>Zvedák - panenka 5t</PRODUCTNAME>
    <ZBOZI_PRODUCTNO>t2</ZBOZI_PRODUCTNO>
    <OZNACENO>0</OZNACENO>
   </SHOPITEM>
   <SHOPITEM>
  **<CATEGORYTEXT/>**
    <ITEM_ID>80002419</ITEM_ID>
  **<PRODUCT/>**
  **<PRODUCTNAME/>**
    <ZBOZI_PRODUCTNO>vv61</ZBOZI_PRODUCTNO>
    <OZNACENO>0</OZNACENO>
  </SHOPITEM>
 </SHOP>
</code>```

And my XSL tranformation is there :

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xhtml">
 <xsl:output method="xml" indent="yes" encoding="utf-8" />
 <xsl:strip-space elements="ZBOZI_CELA_CESTA" />
 <xsl:param name="clientXml" select="'FEED_DATA.xml'" />
 <xsl:variable name="client" select="document(`$`clientXml)//zbozi_FEED_DATA" />
 <xsl:template match="SHOPITEM/CATEGORYTEXT">
  <CATEGORYTEXT>
   <xsl:value-of select="$client[PRODUKT_ID=current()/../ITEM_ID]/ZBOZI_CELA_CESTA" />
  </CATEGORYTEXT>
 </xsl:template>
<xsl:template match="SHOPITEM/PRODUCT">
 <PRODUCT>
<xsl:value-of select="$client[PRODUKT_ID=current()/../ITEM_ID]/ZBOZI_PRODUCT" />
 </PRODUCT>
</xsl:template>
<xsl:template match="SHOPITEM/PRODUCTNAME">
<PRODUCTNAME>
<xsl:value-of select="$client[PRODUKT_ID=current()/../ITEM_ID]/ZBOZI_PRODUCTNAME" />
</PRODUCTNAME>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
</code>```

Please, can anyone help ?

答:
Im not comepletely sure what you are looking for, but it seems ot me like you want to get either the ZBOZI_CELA_CESTA or the CATEGORYTEXT into your node. That is accomplished like this:</p>

```<code> <xsl:template match="SHOPITEM/CATEGORYTEXT">
  <CATEGORYTEXT>
   <xsl:value-of select="$client[PRODUKT_ID=current()/../ITEM_ID]/ZBOZI_CELA_CESTA | $client[PRODUKT_ID=current()/../ITEM_ID]/CATEGORYTEXT"/>
  </CATEGORYTEXT>
 </xsl:template>
</code>```

Body:
I have xsl transformation that copy element from source XML and replace elements from second xml that match and generate finaly XML. It working, but when a element not exist at a second xml than copy element empty ().
I need copy untouched elements from source that not exist at second xml.

For example: First XML contained

<SHOP>
 <SHOPITEM>
  <CATEGORYTEXT>some ways</CATEGORYTEXT>
  <PRODUKT_ID>80002158</PRODUKT_ID>
  <PRODUCT>Zvedák 5t</PRODUCT>
  <PRODUCTNAME>Zvedák 5t</PRODUCTNAME>
  <ZBOZI_PRODUCTNO>t2</ZBOZI_PRODUCTNO>
  <OZNACENO>0</OZNACENO>
 </SHOPITEM>
 <SHOPITEM>
  <CATEGORYTEXT>VÝPRODEJ</CATEGORYTEXT>
  <PRODUKT_ID>80002419</PRODUKT_ID>
  <PRODUCT>3d Dochucovací sada Renga</ZPRODUCT>
  <PRODUCTNAME>3d Dochucovací sada Renga</PRODUCTNAME>
  <ZBOZI_PRODUCTNO>vv61</ZBOZI_PRODUCTNO>
  <OZNACENO>0</OZNACENO>
 </SHOPITEM>
</SHOP>

Second xml contain ...

<dataroot>
 <zbozi_FEED_DATA>
  <ZBOZI_CELA_CESTA>Heureka.cz | Auto-moto | Autodíly | Ramena řízení</ZBOZI_CELA_CESTA>
  <PRODUKT_ID>80002158</PRODUKT_ID>
  <ZBOZI_PRODUCT>Zvedák - panenka 5t</ZBOZI_PRODUCT>
  <ZBOZI_PRODUCTNAME>Zvedák - panenka 5t</ZBOZI_PRODUCTNAME>
  <ZBOZI_PRODUCTNO>t2</ZBOZI_PRODUCTNO>
  <OZNACENO>0</OZNACENO>
 </zbozi_FEED_DATA>
</dataroot>

And desire output xml:

 <SHOP>
  <SHOPITEM>
   <zbozi_FEED_DATA>
   <CATEGORYTEXT>Heureka.cz | Auto-moto | Autodíly | Ramena řízení</CATEGORYTEXT>
   <PRODUKT_ID>80002158</PRODUKT_ID>
   <PRODUCT>Zvedák - panenka 5t</PRODUCT>
   <PRODUCTNAME>Zvedák - panenka 5t</PRODUCTNAME>
   <ZBOZI_PRODUCTNO>t2</ZBOZI_PRODUCTNO>
   <OZNACENO>0</OZNACENO>
  </SHOPITEM>
  <SHOPITEM>
   <CATEGORYTEXT>VÝPRODEJ</CATEGORYTEXT>
   <PRODUKT_ID>80002419</PRODUKT_ID>
   <PRODUCT>3d Dochucovací sada Renga</PRODUCT>
   <PRODUCTNAME>3d Dochucovací sada Renga</PRODUCTNAME>
   <ZBOZI_PRODUCTNO>vv61</ZBOZI_PRODUCTNO>
   <OZNACENO>0</OZNACENO>
  </SHOPITEM>
</SHOP>

But now is wrong output:

 <SHOP>
  <SHOPITEM>
   <zbozi_FEED_DATA>
    <CATEGORYTEXT>Heureka.cz | Auto-moto | Autodíly | Ramena řízení</CATEGORYTEXT>
    <ITEM_IDD>80002158</ITEM_ID>
    <PRODUCT>Zvedák - panenka 5t</PRODUCT>
    <PRODUCTNAME>Zvedák - panenka 5t</PRODUCTNAME>
    <ZBOZI_PRODUCTNO>t2</ZBOZI_PRODUCTNO>
    <OZNACENO>0</OZNACENO>
   </SHOPITEM>
   <SHOPITEM>
  **<CATEGORYTEXT/>**
    <ITEM_ID>80002419</ITEM_ID>
  **<PRODUCT/>**
  **<PRODUCTNAME/>**
    <ZBOZI_PRODUCTNO>vv61</ZBOZI_PRODUCTNO>
    <OZNACENO>0</OZNACENO>
  </SHOPITEM>
 </SHOP>

And my XSL tranformation is there :

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xhtml">
 <xsl:output method="xml" indent="yes" encoding="utf-8" />
 <xsl:strip-space elements="ZBOZI_CELA_CESTA" />
 <xsl:param name="clientXml" select="'FEED_DATA.xml'" />
 <xsl:variable name="client" select="document(`$`clientXml)//zbozi_FEED_DATA" />
 <xsl:template match="SHOPITEM/CATEGORYTEXT">
  <CATEGORYTEXT>
   <xsl:value-of select="$client[PRODUKT_ID=current()/../ITEM_ID]/ZBOZI_CELA_CESTA" />
  </CATEGORYTEXT>
 </xsl:template>
<xsl:template match="SHOPITEM/PRODUCT">
 <PRODUCT>
<xsl:value-of select="$client[PRODUKT_ID=current()/../ITEM_ID]/ZBOZI_PRODUCT" />
 </PRODUCT>
</xsl:template>
<xsl:template match="SHOPITEM/PRODUCTNAME">
<PRODUCTNAME>
<xsl:value-of select="$client[PRODUKT_ID=current()/../ITEM_ID]/ZBOZI_PRODUCTNAME" />
</PRODUCTNAME>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

Please, can anyone help ?

Body:
Im not comepletely sure what you are looking for, but it seems ot me like you want to get either the ZBOZI_CELA_CESTA or the CATEGORYTEXT into your node. That is accomplished like this:

 <xsl:template match="SHOPITEM/CATEGORYTEXT">
  <CATEGORYTEXT>
   <xsl:value-of select="$client[PRODUKT_ID=current()/../ITEM_ID]/ZBOZI_CELA_CESTA | $client[PRODUKT_ID=current()/../ITEM_ID]/CATEGORYTEXT"/>
  </CATEGORYTEXT>
 </xsl:template>


问:
Go-Ethereum: Android Smart Contract Interaction Issue
I am attempting to interact with a smart contract via mobile (android) using the go-ethereum library.

Android

```<code>final String address_string = "0x8607e627604495ae9812c22bb1c98bdcba581978";
String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"get_s\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"new_s\",\"type\":\"string\"}],\"name\":\"set_s\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"d_s\",\"type\":\"string\"}],\"payable\":false,\"type\":\"constructor\"}]";
Address address = Geth.newAddressFromHex(address_string);
BoundContract contract = Geth.bindContract(address, abi, ec);
CallOpts callOpts = Geth.newCallOpts();
callOpts.setContext(ctx);
callOpts.setGasLimit(31500);
System.out.println("OUTPUT: " + getString(contract, callOpts));

//Setter String to Test Contract
Interfaces params = Geth.newInterfaces(1);
Interface anInterface = Geth.newInterface();
anInterface.setString(teststring);
params.set(0,anInterface);
return contract.transact(opts, "set_s", params);

//Getter String from Test Contract
Interfaces args = Geth.newInterfaces(0);
Interfaces results = Geth.newInterfaces(1);
Interface result = Geth.newInterface();
result.setDefaultString();
results.set(0, result);
contract.call(opts, results, "get_s", args);
String string = results.get(0).getString();
return string;
</code>```

Contract

```<code>pragma solidity ^0.4.9;

contract echo {
   string s;

   function echo(string d_s) {
           s = d_s;
   }

   function set_s(string new_s) {
           s = new_s;
   }

   function get_s() returns (string) {
           return s;
    }
}
</code>```

Expected behaviour

Successful interaction with a deployed smart contract on the Rinkeby blockchain.

Actual behaviour

For setter (on contract):
'abi: cannot use slice as type string as argument'

For getter (on contract):
'abi: cannot unmarshal string in to []interface {}'

Steps to reproduce the behaviour

1.) Connect to Rinkeby Testnet via mobile

2.) Create an account via mobile

3.) Deploy a smart contract via desktop

4.) Try to interact w/ the smart contract via mobile

Bottom Line

If anyone has been able to interact with smart contracts through go-ethereum android,
I would appreciate some assistance.

答:
fix for that issue.
https://github.com/ethereum/go-ethereum/pull/15402

I'm waiting for feedback.

Body:
I am attempting to interact with a smart contract via mobile (android) using the go-ethereum library.

Android

final String address_string = "0x8607e627604495ae9812c22bb1c98bdcba581978";
String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"get_s\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"new_s\",\"type\":\"string\"}],\"name\":\"set_s\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"d_s\",\"type\":\"string\"}],\"payable\":false,\"type\":\"constructor\"}]";
Address address = Geth.newAddressFromHex(address_string);
BoundContract contract = Geth.bindContract(address, abi, ec);
CallOpts callOpts = Geth.newCallOpts();
callOpts.setContext(ctx);
callOpts.setGasLimit(31500);
System.out.println("OUTPUT: " + getString(contract, callOpts));

//Setter String to Test Contract
Interfaces params = Geth.newInterfaces(1);
Interface anInterface = Geth.newInterface();
anInterface.setString(teststring);
params.set(0,anInterface);
return contract.transact(opts, "set_s", params);

//Getter String from Test Contract
Interfaces args = Geth.newInterfaces(0);
Interfaces results = Geth.newInterfaces(1);
Interface result = Geth.newInterface();
result.setDefaultString();
results.set(0, result);
contract.call(opts, results, "get_s", args);
String string = results.get(0).getString();
return string;

Contract

pragma solidity ^0.4.9;

contract echo {
   string s;

   function echo(string d_s) {
           s = d_s;
   }

   function set_s(string new_s) {
           s = new_s;
   }

   function get_s() returns (string) {
           return s;
    }
}

Expected behaviour

Successful interaction with a deployed smart contract on the Rinkeby blockchain.

Actual behaviour

For setter (on contract):
'abi: cannot use slice as type string as argument'

For getter (on contract):
'abi: cannot unmarshal string in to []interface {}'

Steps to reproduce the behaviour

1.) Connect to Rinkeby Testnet via mobile

2.) Create an account via mobile

3.) Deploy a smart contract via desktop

4.) Try to interact w/ the smart contract via mobile

Bottom Line

If anyone has been able to interact with smart contracts through go-ethereum android,
I would appreciate some assistance.


问:
Exclude weekend days when adding to current date VBA
I have the following piece of code, which is excluding all results in excel sheet that have date different than today + 6 days.
The problem is that when I execute that on Monday I hit Sunday.
I need to change it in a way that it will add always 6 days to my current date unless the result is Saturday or Sunday, then I would like to take the first working day after that, meaning - Monday. </p>

```<code>    Public Sub GRP_SC_Filter1()
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim DelDate As Long

    DelDate = DateSerial(Year(Date), Month(Date), Day(Date) + 6)

    LR = Sheets("Goods Receivable Planning").Range("A" & Rows.Count).End(xlUp).Row
    Cells.AutoFilter Field:=13, Criteria1:="<>" & DelDate

    ALR = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
    If ALR > 2 Then
        Range("A2:A" & LR).SpecialCells(xlCellTypeVisible).Select
        Range("A2:A" & LR).Delete
        Range("A1").Activate
    End If
    Cells.AutoFilter
 '  MsgBox "Finished deleting rows"
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub
</code>```

<p>I would be really thankful if somebody could help me transforming this into what I need. I am honestly stuck. Thank you in advance! </p>

答:
This function should do what you want:</p>

```<code>Function GetNextWorkingDay(dt As Date) As Date
  Select Case Weekday(dt)
    Case 1
      GetNextWorkingDay = DateAdd("d", 1, dt)
    Case 7
      GetNextWorkingDay = DateAdd("d", 2, dt)
    Case Else
      GetNextWorkingDay = dt
  End Select
End Function
</code>```

Body:
I have the following piece of code, which is excluding all results in excel sheet that have date different than today + 6 days.
The problem is that when I execute that on Monday I hit Sunday.
I need to change it in a way that it will add always 6 days to my current date unless the result is Saturday or Sunday, then I would like to take the first working day after that, meaning - Monday.

    Public Sub GRP_SC_Filter1()
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim DelDate As Long

    DelDate = DateSerial(Year(Date), Month(Date), Day(Date) + 6)

    LR = Sheets("Goods Receivable Planning").Range("A" & Rows.Count).End(xlUp).Row
    Cells.AutoFilter Field:=13, Criteria1:="<>" & DelDate

    ALR = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
    If ALR > 2 Then
        Range("A2:A" & LR).SpecialCells(xlCellTypeVisible).Select
        Range("A2:A" & LR).Delete
        Range("A1").Activate
    End If
    Cells.AutoFilter
 '  MsgBox "Finished deleting rows"
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

I would be really thankful if somebody could help me transforming this into what I need. I am honestly stuck. Thank you in advance!

Body:
This function should do what you want:

Function GetNextWorkingDay(dt As Date) As Date
  Select Case Weekday(dt)
    Case 1
      GetNextWorkingDay = DateAdd("d", 1, dt)
    Case 7
      GetNextWorkingDay = DateAdd("d", 2, dt)
    Case Else
      GetNextWorkingDay = dt
  End Select
End Function


问:
Can't run facebook login in localhost use Laravel
I want to login to facebook with localhost use laravel for testing my app.
But facebook api does not know my local domain.

I start my app on local use php artisan serve. When I enter in the browser http://127.0.0.1:8000 or http://localhost:8000/login - my application run successfully.

On facebook admin page my app i fill in the required fields.

But when I logging, I get responce on facebook page Unable to load URL: The domain of this URL is not part of the application's domain.

Please tell me what I do wrong! Thank you!

答:
In Facebook Login Settings, enter URL http://127.0.0.1:8000 in Valid OAuth redirect URIs field as shown below.

Hope it will work fine then!


问:
c# bot is responding differently on one or more channel
i have deployed my bot on azure,which is running on two channel "Skype" and "Web chat " for testing purpose i have integrated both channel in sample html file screen shot with problem description
i have used this code in ConservationUpdate , my problem domain is that webchat greet the user "welcome" whenever user has fresh start of conservation while skype bot does not greet the user

```<code> if (message.MembersAdded.Any(o => o.Id == message.Recipient.Id))
            {
               // var reply = message.CreateReply(Resources.RootDialog_Welcome_Message);
                var reply = message.CreateReply("hello welcome to zygote");

                ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));

                await connector.Conversations.ReplyToActivityAsync(reply);
            }
</code>```

can anyone explain me two different behavior on same action of bot
....suggestion and advice will be appreciated thanks ......

答: In web chat whenever you refresh page its create new Userid and not storing any session for user,that's why its showing welcome message. while in skype channel session store for user so its not showing welcome message, and you have to give welcome message at a time of bot registration. As per my knowledge.</p>

Body:
i have deployed my bot on azure,which is running on two channel "Skype" and "Web chat " for testing purpose i have integrated both channel in sample html file screen shot with problem description
i have used this code in ConservationUpdate , my problem domain is that webchat greet the user "welcome" whenever user has fresh start of conservation while skype bot does not greet the user

 if (message.MembersAdded.Any(o => o.Id == message.Recipient.Id))
            {
               // var reply = message.CreateReply(Resources.RootDialog_Welcome_Message);
                var reply = message.CreateReply("hello welcome to zygote");

                ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));

                await connector.Conversations.ReplyToActivityAsync(reply);
            }

can anyone explain me two different behavior on same action of bot
....suggestion and advice will be appreciated thanks ......


问:
Eclipse: key binding for getting a list of attributes of a class
In Eclipse, Ctrl + O gives a list of all methods available in the class. Do you know any key binding that gives a list of all attributes of a certain class? </p>

答:
You can use the view Outline goto Window -> Show View -> Outline Key binding for this view is ALT + SHIFT + Q, O

and also make sure not to filter fields in this view


答:
The function weekDay can hep you. The second parameter defines what day return 1, vbMonday would say that Mondays are 1, Saturday = 6, Sunday = 7

So, one way would be:

```<code>deldate = DateSerial(Year(Date + 3), Month(Date + 3), Day(Date + 3) + 6)
Do While (Weekday(deldate, vbMonday) >= 6)
    deldate = deldate + 1
Loop
</code>```

Title: Exclude weekend days when adding to current date VBA

Body:
The function weekDay can hep you. The second parameter defines what day return 1, vbMonday would say that Mondays are 1, Saturday = 6, Sunday = 7

So, one way would be:

deldate = DateSerial(Year(Date + 3), Month(Date + 3), Day(Date + 3) + 6)
Do While (Weekday(deldate, vbMonday) >= 6)
    deldate = deldate + 1
Loop


问:
java codility Max-Counters
I have been trying to solve the below task:

You are given N counters, initially set to 0, and you have two possible operations on them:

```<code>    increase(X) − counter X is increased by 1,
    max_counter − all counters are set to the maximum value of any counter.
</code>```

A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:

```<code>    if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
    if A[K] = N + 1 then operation K is max_counter.
</code>```

For example, given integer N = 5 and array A such that:

```<code>A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
</code>```

the values of the counters after each consecutive operation will be:

```<code>(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)
</code>```

The goal is to calculate the value of every counter after all operations.

```<code>struct Results {
  int * C;
  int L;
};
</code>```

Write a function:

```<code>struct Results solution(int N, int A[], int M);
</code>```

that, given an integer N and a non-empty zero-indexed array A consisting of M integers, returns a sequence of integers representing the values of the counters.

The sequence should be returned as:

```<code>    a structure Results (in C), or
    a vector of integers (in C++), or
    a record Results (in Pascal), or
    an array of integers (in any other programming language).
</code>```

For example, given:

```<code>A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
</code>```

the function should return [3, 2, 2, 4, 2], as explained above.

Assume that:

```<code>    N and M are integers within the range [1..100,000];
    each element of array A is an integer within the range [1..N + 1].
</code>```

Complexity:

```<code>    expected worst-case time complexity is O(N+M);
    expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
</code>```

Elements of input arrays can be modified.

Here is my solution:

```<code>    if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
    if A[K] = N + 1 then operation K is max_counter.
</code>```0

Here is the code valuation:
https://codility.com/demo/results/demo6AKE5C-EJQ/

Can you give me a hint what is wrong with this solution?

答:
```<code>vector<int> solution(int N, vector<int> &A)
{
    std::vector<int> counters(N);
    auto max = 0;
    auto current = 0;

    for (auto& counter : A)
    {
        if (counter >= 1 && counter <= N)
        {
            if (counters[counter-1] < max)
                counters[counter - 1] = max;

            counters[counter - 1] += 1;

            if (counters[counter - 1] > current)
                current = counters[counter - 1];
        }
        else if (counter > N)
            max = current;

    }

    for (auto&& counter : counters)
        if (counter < max)
            counter = max;

    return counters;
}
</code>```

Title: java codility Max-Counters

Body:
I have been trying to solve the below task:

You are given N counters, initially set to 0, and you have two possible operations on them:

    increase(X) − counter X is increased by 1,
    max_counter − all counters are set to the maximum value of any counter.

A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:

    if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
    if A[K] = N + 1 then operation K is max_counter.

For example, given integer N = 5 and array A such that:

A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4

the values of the counters after each consecutive operation will be:

(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)

The goal is to calculate the value of every counter after all operations.

struct Results {
  int * C;
  int L;
};

Write a function:

struct Results solution(int N, int A[], int M);

that, given an integer N and a non-empty zero-indexed array A consisting of M integers, returns a sequence of integers representing the values of the counters.

The sequence should be returned as:

    a structure Results (in C), or
    a vector of integers (in C++), or
    a record Results (in Pascal), or
    an array of integers (in any other programming language).

For example, given:

A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4

the function should return [3, 2, 2, 4, 2], as explained above.

Assume that:

    N and M are integers within the range [1..100,000];
    each element of array A is an integer within the range [1..N + 1].

Complexity:

    expected worst-case time complexity is O(N+M);
    expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

Here is my solution:

import java.util.Arrays;

class Solution {
    public int[] solution(int N, int[] A) {

        final int condition = N + 1;
        int currentMax = 0;
        int countersArray[] = new int[N];

        for (int iii = 0; iii  currentMax) {
                    currentMax = localValue;
                }
            }

        }

        return countersArray;
    }
}

Here is the code valuation:
https://codility.com/demo/results/demo6AKE5C-EJQ/

Can you give me a hint what is wrong with this solution?


问:
Chrome Extension: How to create?
I am experienced in HTML and JavaScript but have never made a (real) Chrome Extension (other than the "Hello World' tutorial).

What I want to do is make an extension that adds functionality to viewing images. Basically I want a pieice of JavaScript to load when you go to a .jpg, .png, ect. page.

I couldn't get much out of the "Hello World" tutorial or the Docs and I've looked at code from XML Tree, but I'm having trouble understanding it.

I don't know where to go from here.

答:
Since you're experienced in JavaScript and HTML, tell you what the best source is?

http://developer.chrome.com/extensions/getstarted.html

Documentation

The above link (Chrome Extension Documentation) is so simple to read once you get a hang of it. For example, I didn't know JavaScript when I created my first Chrome Extension (Reload all tabs). I recommend you to read the docs (will only take you an hour), and follow the steps that you need.

Make sure you understand the different UI's you can tap to

Browser Actions: You use browser actions to put icons in the main Chrome toolbar.

Context Menus: You use context menus to add items to Chromes context menu.

Desktop Notifications: Use desktop notifications to notify users that something is important.

Option Pages: If you want an options page, this is your guy!

Page Actions: If you want to override certain pages (New Tab, History, Bookmark Manager)

Make sure you realize there are many browser interactions that you can tap into:

Bookmarks: Access to your bookmarks

Cookies: Access to Cookies

History: Access to History

Management: Access to Extension Management

Tabs: Access to your Tabs

Windows: Access to your Windows (which has Tabs).

Make sure you understand the difference between Background Pages and Content Scripts, and their limitations.

Make sure you realize there are some neat functions in the Chrome.* API.

Make sure you understand permissions.

Many more

145 Chrome Questions I answered on Stackoverflow

If you want more examples, I have answered many questions regarding Chrome Extensions that might help you get started (145+ Questions Answered), for example, here are some of the more recent ones:

Content Script Skeleton

Send data from Background Page to Content Script

Communication with the embedding page, Simple fetching of the pages JS variable

Taking Screenshots in Chrome

Walkthrough building an extension

Executing JavaScript when a user clicks on a browser action.

How to capture selected text and send it to a web service

Walkthrough how to create an extension to access Disqus Comment Box

Walkthrough how to highlight the DIV that the mouse if hovering over

Walkthrough how to move to the top of the page extension

Walkthrough how to create a bubble overlay when you select text.

etc and 120 more answers for Chrome Extensions, the above is what I copied from the results on the first page. So a search in Google will get you many results.

Real open source extension I created

If you want to see real source code of the extensions I have written (some are super small, some are super big):

Reload all tabs extension

Open link in a foreground tab extension

HTML5 Haptics Chrome extension

Set Wallpaper extension

Prayer times extension

Facebook friend exporter extension

Proxy Anywhere extension

Resources

If you still want more resources, you can:

Read the documentation.

Read the Official Chromium Extension Mailing list

The unofficial Internet Relay Chatroom #chromium-extensions on irc.freenode.net

Google (Will bring you to Stackoverflow, or Quora)

I hope this helped!

Title: Chrome Extension: How to create?


问:
$.parseJSON(data).shift is not a function
i have to parsing json data get from $post method

```<code>$.post( "vehicle_route_qry.php",function(data) {

    siteshistory = $.parseJSON(data);
    siteshistory.shift();
    draw_route(siteshistory);
    $("#dev_det_spin").hide();

});
</code>```

my php file

```<code>$myJSON = '{ "name":"John", "age":31, "city":"New York" }';
echo json_encode($myJSON);
</code>```

i am getting json properly in my response
but getting this issue

```<code>siteshistory.shift is not a function
</code>```

i have loaded following js files

```<code><script src="js/function.js"></script>
<script src="js/jquery.min.js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDaL0ieAkLhzy1rDoLifajeowdXPwTvzmI"></script>
<!-- <script type="text/javascript" src="js/date.js"></script> -->
<script type="text/javascript" src="js/loader.js"></script>
<script type="text/javascript" src="js/header_function.js"></script>
</code>```

but shift function for  $.parseJSON(data).shift() is not working
i am not able to find any reference regarding shift function

suggestion would be helpful

答:
//what your trying to shift() is not an array
 try below code

```<code> var siteshistory = [];

    siteshistoryObj = $.parseJSON('{ "name":"John", "age":31, "city":"New York" }');//add here your ajax response

   //converting to array
    $.each(siteshistoryObj, function (index, order) {
      siteshistory.push({index : index});
    });
    siteshistory.shift();

console.log(siteshistory);// check array values
</code>```

Body:
i have to parsing json data get from $post method

$.post( "vehicle_route_qry.php",function(data) {

    siteshistory = $.parseJSON(data);
    siteshistory.shift();
    draw_route(siteshistory);
    $("#dev_det_spin").hide();

});

my php file

$myJSON = '{ "name":"John", "age":31, "city":"New York" }';
echo json_encode($myJSON);

i am getting json properly in my response
but getting this issue

siteshistory.shift is not a function

i have loaded following js files

but shift function for  $.parseJSON(data).shift() is not working
i am not able to find any reference regarding shift function

suggestion would be helpful

Body:
//what your trying to shift() is not an array
 try below code

 var siteshistory = [];

    siteshistoryObj = $.parseJSON('{ "name":"John", "age":31, "city":"New York" }');//add here your ajax response

   //converting to array
    $.each(siteshistoryObj, function (index, order) {
      siteshistory.push({index : index});
    });
    siteshistory.shift();

console.log(siteshistory);// check array values


问:
Javascript function with dynamic parameters list and parameters array
I need to call a function in javaScript

```<code>service.call(row.operation, args.arg1, args.arg2, args.arg3,...,argN )
</code>```

And I have array of the parameters of random length. How to pass this array to a function as a parameter list?

UPDATE

I can't change call method signature. 'Call' method is custom, not standard.

答:
Use apply instead of call. It expects the parameters in the form of an array.

```<code>var args = [ args.arg1, args.arg2, args.arg3 ];
service.apply(row.operation, args);
</code>```

Re edit:

I can't change call method signature. 'Call' method is custom, not standard.

First: Buy a copy of JavaScript: The Definitive Guide (it is a very thick book) and use it to beat some sense into whoever named the call method on your service object.

Then … use apply to call the call method.

```<code>var args = [row.operation, args.arg1, args.arg2, args.arg3 ];
service.call.apply(service.call, args);
</code>```

Body:
I need to call a function in javaScript

service.call(row.operation, args.arg1, args.arg2, args.arg3,...,argN )

And I have array of the parameters of random length. How to pass this array to a function as a parameter list?

UPDATE

I can't change call method signature. 'Call' method is custom, not standard.

Body:
Use apply instead of call. It expects the parameters in the form of an array.

var args = [ args.arg1, args.arg2, args.arg3 ];
service.apply(row.operation, args);

Re edit:

I can't change call method signature. 'Call' method is custom, not standard.

First: Buy a copy of JavaScript: The Definitive Guide (it is a very thick book) and use it to beat some sense into whoever named the call method on your service object.

Then … use apply to call the call method.

var args = [row.operation, args.arg1, args.arg2, args.arg3 ];
service.call.apply(service.call, args);


问:
Async/Await in a Class : unexpected token `this`
I am experimenting with async/await, I can't understand why this line :

```<code>resolvedValue = await this.tryToSolve()
</code>```

gives me this error :

Unexpected token this

class Test {

 constructor() {
  this.method = 0
  this.checkLink()
 }

 async checkLink() {
  return new Promise((resolve, reject) => {

   let resolvedValue

   for (let i = 0; i < 3; i++) {
    this.method = i
    resolvedValue = await this.tryToSolve()
    if (resolvedValue) break
   }
   console.log(`Method ${this.method} did the trick.`);
   resolve(resolvedValue)
  })
 }

 tryToSolve() {
  return new Promise((resolve, reject) => { // Resolves if this.method==1
   console.log(`Trying to solve with method ${this.method}...`);
   setTimeout(() => {
    resolve(!!this.method ? `http://www${this.method}.someurl.com` : false)
   }, 1000)
  })
 }
}

const test = new Test()```

Does anyone know the correct syntax to store the result of an async method in a variable?

Thanks in advance.

答:
Drop the new Promise around the await! You want only

```<code>async checkLink() {
    let resolvedValue
    for (let i = 0; i < 3; i++) {
        this.method = i
        resolvedValue = await this.tryToSolve()
        if (resolvedValue) break
    }
    console.log(`Method ${this.method} did the trick.`);
    return resolvedValue;
}
</code>```

or much simpler

```<code>async checkLink() {
    for (let i = 0; i < 3; i++) {
        const value = await this.tryToSolve()
        if (value) {
            console.log(`Method ${i} did the trick.`);
            return value;
        }
    }
}
</code>```

Body:
I am experimenting with async/await, I can't understand why this line :

resolvedValue = await this.tryToSolve()

gives me this error :

Unexpected token this

class Test {

 constructor() {
  this.method = 0
  this.checkLink()
 }

 async checkLink() {
  return new Promise((resolve, reject) => {

   let resolvedValue

   for (let i = 0; i < 3; i++) {
    this.method = i
    resolvedValue = await this.tryToSolve()
    if (resolvedValue) break
   }
   console.log(`Method ${this.method} did the trick.`);
   resolve(resolvedValue)
  })
 }

 tryToSolve() {
  return new Promise((resolve, reject) => { // Resolves if this.method==1
   console.log(`Trying to solve with method ${this.method}...`);
   setTimeout(() => {
    resolve(!!this.method ? `http://www${this.method}.someurl.com` : false)
   }, 1000)
  })
 }
}

const test = new Test()

Does anyone know the correct syntax to store the result of an async method in a variable?

Thanks in advance.

Body:
Drop the new Promise around the await! You want only

async checkLink() {
    let resolvedValue
    for (let i = 0; i < 3; i++) {
        this.method = i
        resolvedValue = await this.tryToSolve()
        if (resolvedValue) break
    }
    console.log(`Method ${this.method} did the trick.`);
    return resolvedValue;
}

or much simpler

async checkLink() {
    for (let i = 0; i < 3; i++) {
        const value = await this.tryToSolve()
        if (value) {
            console.log(`Method ${i} did the trick.`);
            return value;
        }
    }
}


问:
How to upload empty file with Retrofit 2?
I successfully set up an uploading images to my REST API via retrofit with this code:

```<code>        File imageFile = ImagePicker.getFileFromResult(this, resultCode, data);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("userpic", imageFile.getName(), requestFile);

        RetrofitClient.compositeSubscription.add(RetrofitClient.getService().updateProfileUserpic("Token " + RevolutionApp.getInstance().getUserToken(), body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Profile>() {
                    @Override
                    public void onCompleted() { }

                    @Override
                    public void onError(Throwable e) { }

                    @Override
                    public void onNext(Profile profile) {
                        mProfileFragment.fetchProfileData();
                    }
                }));
</code>```

Now I need to send empty file (null) to my my API. How to implement it?

```<code>MultipartBody.Part.createFormData("userpic", imageFile.getName(), requestFile)
</code>```

does not work

答:
i don't Know this is the right way to do this,i tried like this.its working

```<code>MultipartBody.Part fileToUpload = null;
        if (realPath != null) {
            try {
                File file = new File(realPath);
                if (file.exists()) {
                    RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
                    fileToUpload = MultipartBody.Part.createFormData("attachment", file.getName(), requestBody);
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }else{
            RequestBody attachmentEmpty = RequestBody.create(MediaType.parse("text/plain"), "");

            fileToUpload = MultipartBody.Part.createFormData("attachment", "", attachmentEmpty);
        }
</code>```

Note: File Name should not be null ,in place of null use empty("").

Body:
I successfully set up an uploading images to my REST API via retrofit with this code:

        File imageFile = ImagePicker.getFileFromResult(this, resultCode, data);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("userpic", imageFile.getName(), requestFile);

        RetrofitClient.compositeSubscription.add(RetrofitClient.getService().updateProfileUserpic("Token " + RevolutionApp.getInstance().getUserToken(), body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Profile>() {
                    @Override
                    public void onCompleted() { }

                    @Override
                    public void onError(Throwable e) { }

                    @Override
                    public void onNext(Profile profile) {
                        mProfileFragment.fetchProfileData();
                    }
                }));

Now I need to send empty file (null) to my my API. How to implement it?

MultipartBody.Part.createFormData("userpic", imageFile.getName(), requestFile)

does not work

Body:
i don't Know this is the right way to do this,i tried like this.its working

MultipartBody.Part fileToUpload = null;
        if (realPath != null) {
            try {
                File file = new File(realPath);
                if (file.exists()) {
                    RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
                    fileToUpload = MultipartBody.Part.createFormData("attachment", file.getName(), requestBody);
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }else{
            RequestBody attachmentEmpty = RequestBody.create(MediaType.parse("text/plain"), "");

            fileToUpload = MultipartBody.Part.createFormData("attachment", "", attachmentEmpty);
        }

Note: File Name should not be null ,in place of null use empty("").


问:
Modal jQuery doesn't work (bootstrap 4)
I have a problem with jQuery. When I click on the link the modal opens and I want to pass the value of data-href to the button inside the modal.

Nothing happens when I click the button. Could you please help me?

Link

```<code><a href="#" data-href="stackoverflow.com" data-toggle="modal" data-target="#openModal">Link</a>
</code>```

Modal

```<code><div class="modal fade" id="openModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-danger btn-ok" href="">Go</button>
                    </div>
                </div>
            </div>
        </div>
</code>```

JQuery

```<code>    <script>
        $('#openModal').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
            $('.debug-url').html('Delete URL: <strong>' + $(this).find('.btn-ok').attr('href') + '</strong>');
        });
    </script>
</code>```

jQuery/Popper/JS

```<code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.2/umd/popper.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</code>```

Error

```<code>Uncaught ReferenceError: $ is not defined
</code>```

答: I put the jQuery file on the head instead of the bottom of the body and it works. Thank you.</p>

Title: Modal jQuery doesn't work (bootstrap 4)

Body:
I have a problem with jQuery. When I click on the link the modal opens and I want to pass the value of data-href to the button inside the modal.

Nothing happens when I click the button. Could you please help me?

Link

Link

Modal

                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-danger btn-ok" href="">Go</button>

JQuery

jQuery/Popper/JS

Error

Uncaught ReferenceError: $ is not defined


问:
AND within OR within AND in Excel function?
I need to check if a A is over 200, and if B is over 150, if that's the case, the result should be true.

However, if A is exactly 200, it still has to result in true is B is over 100.

In short

```<code>A>200 AND B>150 = True
</code>```

But if

```<code>A=200 AND B>100 = True
A=200 AND B<=100 = False
</code>```

I tried it myself, but I'm stuck, my brain can't handle all the nesting, and I think I'm missing something easy, I also think the syntax I'm using is not correct, but what I came up with so far is:

```<code>=IF(AND(A>200;B>150;OR(AND(A=200;B>100);"True";"False")
</code>```

答:
This is mainly a math-logic question, but anyway, this should help with more complex scenarios as well, especially if you are having difficulty grasping the different outcomes.

I would draw a probability tree, similar to the below, showing all the different outcomes for each:

```<code>         A              B
                ----  > 150  -- True
                |
 ----  > 200  --|
 |              |
 |              ----  <=150  -- False
 |
 |              ----  > 100  -- True
 |              |
-|---  = 200  --|
 |              |
 |              ----  <= 100 -- False
 |
 |
 ----  < 200  ----- Anything -- False
</code>```

Once this is correct, gather the ones we need. In this case, we need to separate the True from the False. The simplest way would be to work on the True (2 out of the 5 outcomes are True, so less work!)

Follow each 'True' branch, and AND them:

```<code>AND(A>200;B>150)
AND(A=200;B>100)
</code>```

Once you got everything, OR them together:

```<code>OR(AND(A>200;B>150);AND(A=200;B>100))
</code>```

So final result:

```<code>IF(OR(AND(A>200;B>150);AND(A=200;B>100)); "True"; "False")
</code>```

Extra: if you wanted to get the "False" instead:

Follow each 'False' branch, and AND them (note since the last one is alone, we can drop the AND):

```<code>AND(A>200;B<=150)
AND(A=200;B<=100)
A<200
</code>```

Once you got everything, OR them together:

```<code>OR(AND(A>200;B<=150);AND(A=200;B<=100);A<200)
</code>```

So final result:

```<code>IF(OR(AND(A>200;B<=150);AND(A=200;B<=100);A<200); "False"; "True")
</code>```

Body:
I need to check if a A is over 200, and if B is over 150, if that's the case, the result should be true.

However, if A is exactly 200, it still has to result in true is B is over 100.

In short

A>200 AND B>150 = True

But if

A=200 AND B>100 = True
A=200 AND B<=100 = False

I tried it myself, but I'm stuck, my brain can't handle all the nesting, and I think I'm missing something easy, I also think the syntax I'm using is not correct, but what I came up with so far is:

=IF(AND(A>200;B>150;OR(AND(A=200;B>100);"True";"False")

Body:
This is mainly a math-logic question, but anyway, this should help with more complex scenarios as well, especially if you are having difficulty grasping the different outcomes.

I would draw a probability tree, similar to the below, showing all the different outcomes for each:

         A              B
                ----  > 150  -- True
                |
 ----  > 200  --|
 |              |
 |              ----  <=150  -- False
 |
 |              ----  > 100  -- True
 |              |
-|---  = 200  --|
 |              |
 |              ----  <= 100 -- False
 |
 |
 ----  < 200  ----- Anything -- False

Once this is correct, gather the ones we need. In this case, we need to separate the True from the False. The simplest way would be to work on the True (2 out of the 5 outcomes are True, so less work!)

Follow each 'True' branch, and AND them:

AND(A>200;B>150)
AND(A=200;B>100)

Once you got everything, OR them together:

OR(AND(A>200;B>150);AND(A=200;B>100))

So final result:

IF(OR(AND(A>200;B>150);AND(A=200;B>100)); "True"; "False")

Extra: if you wanted to get the "False" instead:

Follow each 'False' branch, and AND them (note since the last one is alone, we can drop the AND):

AND(A>200;B<=150)
AND(A=200;B<=100)
A<200

Once you got everything, OR them together:

OR(AND(A>200;B<=150);AND(A=200;B<=100);A<200)

So final result:

IF(OR(AND(A>200;B<=150);AND(A=200;B<=100);A<200); "False"; "True")


问:
Java - Do object references get destroyed when the creating class is closed?
Say i have a class, which loads a file and then calls another method to do something to that file. For example, counting the words in the file.

Within class CountWords, a number of objects/collections are created in order to get the number of words. The method runs, the number of words is found, and then this is returned to the calling class.

My question is, do all the objects/collection created in the CountWords class get "destroyed" when control is returned to the calling class or do they remain in the memory? If the latter, would i have to set each object to null before exiting the class to mark them for collection?

答:
Java is a programming language that has memory management aka garbage collection. The basic answer is, the garbage collector will take care of reclaiming the memory of unused objects.

But since you have tagged the question with [garbage-collection], you should already know this. So it’s not clear what additional detail you want to know or why you think your scenario is special in any way, to deserve an additional answer beyond “there is a garbage collector”.

You question is full of phrases that are wrong or misguiding.

“do object references get destroyed”—the storage of objects is reclaimed, there is no such thing as “destruction of references”

“when the creating class is closed”—there is no such thing as “closing of classes”

“do all the objects/collection created in the CountWords class get ‘destroyed’ when control is returned to the calling class or do they remain in the memory?”—in this form, not simple to answer

there is no such thing as “destruction”. The whole purpose of garbage collection is to permit the reuse of the memory. This implies recording somewhere that the memory is free. But the memory itself does not need to be touched.

when your method returns, these objects are eligible for garbage collection. The garbage collection itself does not have to run immediately. It may happen when there is need for free memory or when the CPU load is low.

As said, even if the garbage collector ran, the result is that the memory is now considered to be free, not necessarily to “scrub” the memory. So the objects may “remain in the memory” until actually being overwritten by other objects. So that’s simply the wrong question. You actually want to know whether the memory will be reusable.

“If the latter, would i have to set each object to null before exiting the class to mark them for collection?”—“the latter” still implies that the memory is free, semantically. But what do you want to “set to null”? The references do not exist anymore. The objects are unreachable.

The answer is there is nothing you can do and there is nothing you should do. That’s the whole point of garbage collection, no need for you to do anything.


问:
razor page redirect after some time
I have a task running i the background generating and image.
When i have the image placed on the server, I want to go to a page that shows the image.

I am having trouble doing that, I expect due to lack of knowledge of razor pages in asp.net core v. 2.0

Basically I have my page:

```<code><div>
    <img src="images/IAmGeneratingAnImage.png"/>
</div>
</code>```

And my model:

```<code>class xx:PageModel ...

    public void OnGet() {
      Task.Factory.StartNew(() => { CheckForImageAndRedirect(); });
    }

    private void CheckForImageAndRedirect() {
        string fileNameFull = "";
        do
        {
            var file = new FileInfo("C:\...\imageName.png");
            if (file.Exists ))
                fileNameFull = file.FullName;

            Thread.Sleep(1000);
        }
        while (String.IsNullOrEmpty(fileNameFull));

        RedirectToPage("OtherPageThatDisplaysImage"); // razorpage also.
    }
</code>```

I would really like to pass the path to the new page as well, that can probably also be done...

So those are my two questions:

 a) how do I redirect to a page after a task is completed ?

 b) how do I pass the new imagepath to the new page ?

Or am I attaching the problem completely wrong?

答:
I think your main problem is in the use of Task.Factory.StartNew. Not only is that a bad thing to do, in general, in a web application, but when you do that, the code that's being run is taken off to a new thread. That's sort of the point, but the result of that is that your application moves on, and when your method finally wants to redirect, there's nothing left to redirect: the response has either already been returned or is too far along to change it. More to the point, the code running here now doesn't even have access to the response to change it if it could, because it's not running in the same thread context.

If you want to do something "in the background", you need to offload it to an actual background process, not a new thread. You can use HangFire or similar tools to accomplish this. You then move on and return the response to the user, and either use SignalR or long-poll via AJAX to check on the status of your background job. Once your job is completed, then you can redirect the user appropriately, but that will need to happen client-side, not server-side. Once the server has returned a response, it's done. It has no ability to issue a redirect without first receiving a new request from the client.

Lastly, while not pertinent to the issue at hand here, be advised that Thread.Sleep is blocking. You should use Task.Sleep instead.

Title: razor page redirect after some time

Body:
I have a task running i the background generating and image.
When i have the image placed on the server, I want to go to a page that shows the image.

I am having trouble doing that, I expect due to lack of knowledge of razor pages in asp.net core v. 2.0

Basically I have my page:

And my model:

class xx:PageModel ...

    public void OnGet() {
      Task.Factory.StartNew(() => { CheckForImageAndRedirect(); });
    }

    private void CheckForImageAndRedirect() {
        string fileNameFull = "";
        do
        {
            var file = new FileInfo("C:\...\imageName.png");
            if (file.Exists ))
                fileNameFull = file.FullName;

            Thread.Sleep(1000);
        }
        while (String.IsNullOrEmpty(fileNameFull));

        RedirectToPage("OtherPageThatDisplaysImage"); // razorpage also.
    }

I would really like to pass the path to the new page as well, that can probably also be done...

So those are my two questions:

 a) how do I redirect to a page after a task is completed ?

 b) how do I pass the new imagepath to the new page ?

Or am I attaching the problem completely wrong?


问:
Android Studio : display date got from another activity
In an activity, I ask my user about a date using a datepicker.
As far as I found, the best way to pass this date to a subsequent activity is to send separately yea, month and day.

In my subsequent activity, I want to display this date, but also this date+ 1 day, + 2 days and so on.

To do it, I taught I can do :

```<code>int mDay = origine.getIntExtra("mDay", 0);
int mMonth= origine.getIntExtra("mMonth", 0);
int mYear = origine.getIntExtra("mYear", 0);
calendrier = new GregorianCalendar(mYear,mMonth,mDay);
</code>```

and then put it in a string using something like

```<code>String strcal01 = sdf.format(new calendrier);
</code>```

This line don't work but it works if I replace "calendrier" by "Date()" (of course with current date and not the date get from the other activity...

What can I do to make it working ?

Thank's a lot for your help.

答:
Use this method for getting date input from user

```<code>Calendar myCalendar = Calendar.getInstance();
dateValue.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new DatePickerDialog(DailySalesView.this, datePicker, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });
</code>```

Put this inside Activity class

```<code>String date;
DatePickerDialog.OnDateSetListener datePicker = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

String myFormat = "dd/MM/yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat);
        date= sdf.format(myCalendar.getTime());
            }

        };
</code>```

By this way you'll get formatted date in the String date
You can then pass it to another Activity with Intent.
If you need clarification, feel free to ask!
Hope it helps!

Body:
In an activity, I ask my user about a date using a datepicker.
As far as I found, the best way to pass this date to a subsequent activity is to send separately yea, month and day.

In my subsequent activity, I want to display this date, but also this date+ 1 day, + 2 days and so on.

To do it, I taught I can do :

int mDay = origine.getIntExtra("mDay", 0);
int mMonth= origine.getIntExtra("mMonth", 0);
int mYear = origine.getIntExtra("mYear", 0);
calendrier = new GregorianCalendar(mYear,mMonth,mDay);

and then put it in a string using something like

String strcal01 = sdf.format(new calendrier);

This line don't work but it works if I replace "calendrier" by "Date()" (of course with current date and not the date get from the other activity...

What can I do to make it working ?

Thank's a lot for your help.

Body:
Use this method for getting date input from user

Calendar myCalendar = Calendar.getInstance();
dateValue.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new DatePickerDialog(DailySalesView.this, datePicker, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

Put this inside Activity class

String date;
DatePickerDialog.OnDateSetListener datePicker = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

String myFormat = "dd/MM/yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat);
        date= sdf.format(myCalendar.getTime());
            }

        };

By this way you'll get formatted date in the String date
You can then pass it to another Activity with Intent.
If you need clarification, feel free to ask!
Hope it helps!


问:
Cannot point to webroot directory in plugin folder in Cakephp 3
I want to point javascript and css file to webroot directory in plugin folder.
This is my code of the view in the plugin directory

echo
  $this->Html->css('/PanelAdmin/bower_components/bootstrap/dist/css/bootstrap.min.css');

but this code points to webroot of my parent application. Here PanelAdmin is
the plugin name.
Please help to sort out my issue. Thanks

答:
To include CSS assets from a plugin you need to use the plugin dot notation. For example, if you wanted to include the file css/styles.css from your PanelAdmin plugin you would use:-

```<code>echo $this->Html->css('PanelAdmin.styles');
</code>```

See the official docs for details.

Cake uses cssBaseUrl to determine the folder name for the css folder, but I believe you can navigate out of this by using ../ in the file path:-

```<code>echo $this->Html->css('PanelAdmin.../bower_components/bootstrap/dist/css/bootstrap.min.css');
</code>```

Body:
To include CSS assets from a plugin you need to use the plugin dot notation. For example, if you wanted to include the file css/styles.css from your PanelAdmin plugin you would use:-

echo $this->Html->css('PanelAdmin.styles');

See the official docs for details.

Cake uses cssBaseUrl to determine the folder name for the css folder, but I believe you can navigate out of this by using ../ in the file path:-

echo $this->Html->css('PanelAdmin.../bower_components/bootstrap/dist/css/bootstrap.min.css');


问:
How to access Class member variables from SpringApplication in Spring Boot
How do you access a member variable when starting the application using SpringApplication in SpringBoot ?

In the below code I am getting compilation errors on the assignment to Environment and BuildProperties. I think there must be a way to reference these properties via the SpringApplication or ConfigurableApplicationContext but I don't know how.

The compile error I am getting is,
non-static variable environment cannot be referenced from a static context
which I understand its just how to get around it.

I think my question really is - does SpringApplication return a Class level reference in the same way as doing a normal java MyClass myClass = new MyClass() does ?

```<code>@Slf4j
@EnableIntegration
@EnableLoaderApplication
@SpringBootApplication
@EnableDiscoveryClient
public class ExampleApplication {

    private Environment environment;
    private BuildProperties buildProperties;

    public ExampleApplication(Environment env, BuildProperties buildProp) {
        environment = env;
        buildProperties = buildProp;
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(ExampleApplication.class);
        ConfigurableApplicationContext context = app.run(args);

        environment = context.getEnvironment();  //compile error
        buildProperties = context.getBean(BuildProperties.class); //compile error

    DisplaySysInfo displaySysInfo = new DisplaySysInfo(environment, buildProperties, log);
    displaySysInfo.splash();

    }

}
</code>```

答:
Having this kind of logic inside your main class is never a good practice, instead of this, you can use @PostConstruct to initiate a new Bean just after finish the initial bean injections and configurations of your program.
So, you can move this logic to another class with @PostConstruct:

```<code>environment = context.getEnvironment();  //compile error
buildProperties = context.getBean(BuildProperties.class); //compile error
</code>```

this way, you are not getting any static context error and your code will be cleaner.

Body:
How do you access a member variable when starting the application using SpringApplication in SpringBoot ?

In the below code I am getting compilation errors on the assignment to Environment and BuildProperties. I think there must be a way to reference these properties via the SpringApplication or ConfigurableApplicationContext but I don't know how.

The compile error I am getting is,
non-static variable environment cannot be referenced from a static context
which I understand its just how to get around it.

I think my question really is - does SpringApplication return a Class level reference in the same way as doing a normal java MyClass myClass = new MyClass() does ?

@Slf4j
@EnableIntegration
@EnableLoaderApplication
@SpringBootApplication
@EnableDiscoveryClient
public class ExampleApplication {

    private Environment environment;
    private BuildProperties buildProperties;

    public ExampleApplication(Environment env, BuildProperties buildProp) {
        environment = env;
        buildProperties = buildProp;
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(ExampleApplication.class);
        ConfigurableApplicationContext context = app.run(args);

        environment = context.getEnvironment();  //compile error
        buildProperties = context.getBean(BuildProperties.class); //compile error

    DisplaySysInfo displaySysInfo = new DisplaySysInfo(environment, buildProperties, log);
    displaySysInfo.splash();

    }

}

Body:
Having this kind of logic inside your main class is never a good practice, instead of this, you can use @PostConstruct to initiate a new Bean just after finish the initial bean injections and configurations of your program.
So, you can move this logic to another class with @PostConstruct:

environment = context.getEnvironment();  //compile error
buildProperties = context.getBean(BuildProperties.class); //compile error

this way, you are not getting any static context error and your code will be cleaner.