问:
how to animate bar chart from bottom to top?
I am trying to make a bar chart and the bar animates from top to bottom right now, but I want it to animate from bottom to top. How do I get it go from bottom to top?

CSS

```<code>.bar {
width:50px;
height:250px;
list-style-type:none;
}
.bar p {
background-color:#63F;
}
.bar span {
padding-left:15px;
left:100%;
}
#content ul {
list-style-type:none;
}
#content ul li {
float:left;
margin:50px;
}
</code>```

HTML

```<code><div id="content">
<ul>
  <li>
    <div class="bar">
      <p><span>50%</span></p>
    </div><br>
    Freshmen
  </li>
</ul>
</content>
</code>```

Javascript

```<code><script src="../../jquery-1.6.4.min.js"></script>
$(document).ready(function(){
    $(".bar").each(function(){
        var length = $(this).find("span").html();
        $(this).find("p").delay(500).animate({'height':length},3500,function(){$(this).find("span").fadeIn(1000);
        });
    });
});
</code>```

"click here to see it in jsfiddle"

答:
Use keyframes to animate the css property, e.g. width
Once you set the width of your element (e.g. div) the animation will kick in

```<code>.animated-bar {
  animation: animateBar 0.25s ease-in;
  @keyframes animateBar {
    0% {
      width: 0;
    }
  }
}
</code>```

```

Body:
I am trying to make a bar chart and the bar animates from top to bottom right now, but I want it to animate from bottom to top. How do I get it go from bottom to top?

CSS

.bar {
width:50px;
height:250px;
list-style-type:none;
}
.bar p {
background-color:#63F;
}
.bar span {
padding-left:15px;
left:100%;
}
#content ul {
list-style-type:none;
}
#content ul li {
float:left;
margin:50px;
}

HTML

50%

    Freshmen

</content>

Javascript

$(document).ready(function(){
    $(".bar").each(function(){
        var length = $(this).find("span").html();
        $(this).find("p").delay(500).animate({'height':length},3500,function(){$(this).find("span").fadeIn(1000);
        });
    });
});

"click here to see it in jsfiddle"

Body:
Use keyframes to animate the css property, e.g. width
Once you set the width of your element (e.g. div) the animation will kick in

.animated-bar {
  animation: animateBar 0.25s ease-in;
  @keyframes animateBar {
    0% {
      width: 0;
    }
  }
}

<div class="animated-bar" style="width: 200px"><div>


来源: stackexchange

问:
-eq and -ne give me the same results
Why do the following two command, with the only difference the -eq and -ne operator give me my list of DCs?

```<code>Get-ADComputer -Filter {(operatingsystem -like "*server*") -AND
(PrimaryGroup -eq "CN=Domain Controllers,CN=Users,DC=domain,DC=com") }
-Property Name,PrimaryGroup
</code>```

I'd expect this one to have everything, but domain controllers.

```<code>Get-ADComputer -Filter {(operatingsystem -like "*server*") -AND
(PrimaryGroup -ne "CN=Domain Controllers,CN=Users,DC=domain,DC=com") }
-Property Name,PrimaryGroup
</code>```

If I run the equivalent against PrimaryGroupID instead of PrimaryGroup, it works as expected.

答:
If you want to put one statement on separate lines, you need to put the backtick (`) at the end of the line to tell PowerShell that the statement continues on the next line. However, even then, you cannot split the filter on two different lines. So it should look something like this:

```<code>Get-ADComputer -Filter {(operatingsystem -like "*server*") -AND (PrimaryGroup -eq "CN=Domain Controllers,CN=Users,DC=example,DC=com") } `
    -Property Name,PrimaryGroup
</code>```

As you've found, AD doesn't actually have an attribute called PrimaryGroup. That is a property that PowerShell exposes to you, which interprets the value in the primaryGroupId attribute for you.

The primaryGroupId attribute of any object has the Relative Identifier (RID) of the group. The RID is the last section of number in the SID, but the group also stores this value in its primaryGroupToken atrribute. So you can get this value like this:

```<code>$primaryGroupToken = (Get-ADGroup "Domain Controllers" -Properties primaryGroupToken).primaryGroupToken
</code>```

PowerShell has to convert what you pass into the -Filter parameter into a proper LDAP query, so when you use PrimaryGroup in the filter, PowerShell is doing that for you.

However, doing that lookup is not really necessary in this case, because the Domain Controllers group is a built-in group and always has an RID of 516. So you can do what you're trying to do like this:

```<code>Get-ADComputer -Filter "operatingsystem -like '*server*' -AND PrimaryGroupId -eq 516" `
    -Property Name,PrimaryGroup
</code>```

ContentLicense: CC BY-SA 3.0

Title: -eq and -ne give me the same results

Body:
Why do the following two command, with the only difference the -eq and -ne operator give me my list of DCs?

Get-ADComputer -Filter {(operatingsystem -like "*server*") -AND
(PrimaryGroup -eq "CN=Domain Controllers,CN=Users,DC=domain,DC=com") }
-Property Name,PrimaryGroup

I'd expect this one to have everything, but domain controllers.

Get-ADComputer -Filter {(operatingsystem -like "*server*") -AND
(PrimaryGroup -ne "CN=Domain Controllers,CN=Users,DC=domain,DC=com") }
-Property Name,PrimaryGroup

If I run the equivalent against PrimaryGroupID instead of PrimaryGroup, it works as expected.

Body:
If you want to put one statement on separate lines, you need to put the backtick (`) at the end of the line to tell PowerShell that the statement continues on the next line. However, even then, you cannot split the filter on two different lines. So it should look something like this:

Get-ADComputer -Filter {(operatingsystem -like "*server*") -AND (PrimaryGroup -eq "CN=Domain Controllers,CN=Users,DC=example,DC=com") } `
    -Property Name,PrimaryGroup

As you've found, AD doesn't actually have an attribute called PrimaryGroup. That is a property that PowerShell exposes to you, which interprets the value in the primaryGroupId attribute for you.

The primaryGroupId attribute of any object has the Relative Identifier (RID) of the group. The RID is the last section of number in the SID, but the group also stores this value in its primaryGroupToken atrribute. So you can get this value like this:

$primaryGroupToken = (Get-ADGroup "Domain Controllers" -Properties primaryGroupToken).primaryGroupToken

PowerShell has to convert what you pass into the -Filter parameter into a proper LDAP query, so when you use PrimaryGroup in the filter, PowerShell is doing that for you.

However, doing that lookup is not really necessary in this case, because the Domain Controllers group is a built-in group and always has an RID of 516. So you can do what you're trying to do like this:

Get-ADComputer -Filter "operatingsystem -like '*server*' -AND PrimaryGroupId -eq 516" `
    -Property Name,PrimaryGroup

ContentLicense: CC BY-SA 4.0


问:
Meaning of R command system("touch AAA")
I am watching a Machine Learning Distributed in R and this lines of code appear:

For what the teacher says, system("touch fin1") will save the document in fin1 when the process has finished.

Does anyone know where I can find documentation about such function?

答:
Think of system as an easy way to send commands to a terminal.  The touch command (at least on *unix systems) creates a file.  That's all it does really.

So the individual slave sessions create a file on the system.  Why would they do that? So that the master session can easily detect when the slave sessions have gotten past a certain point in their scripts.  The master session is constantly looping looking to see if all of the slave sessions have successfully gotten past that first actual line in their code.

So the answer your question of "Does anyone know where I can find documentation about such function?" is to look at the documentation provided by your system.  For most *unix systems you can go to a command line and enter the command man touch or man {command you're interested in} to bring up the man pages for the given command.


问:
Electron with Touchbar: TouchBarLabel is not a constructor
I'm using axios in my electron app to get data from an API. This data should be displayed on the touchbar once it's received. To manage the touchbar I added a new .ts file:

import electron, {
    BrowserWindow,
    TouchBar,
    TouchBarLabel,
    TouchBarButton,
    TouchBarSpacer
} from "electron";
import { IProject } from './types';

export function updateTouchBar(data: IProject[]) {
    let arr = [];
    data.forEach(ele => {
        arr.push(new electron.TouchBarLabel({ label: ele.name }));
    });

    publish(new TouchBar({ items: arr }));
}

export function publish(tb: TouchBar) {
    electron.remote.BrowserWindow.getFocusedWindow().setTouchBar(tb);
}
```

Displaying data in the window works, but the touchbar is not working: TouchBarLabel is not a constructor.

What does this mean and how can I fix it?

Thanks,
Lukas

答:
I had the issue TouchBarLabel is not a constructor. and if your problem is anything like mine, the solution will be to rearrange the import statement like

```<code>import electron, { BrowserWindow, TouchBar } from "electron";
const { TouchBarLabel, TouchBarButton, TouchBarSpacer } = TouchBar;
</code>```

Body:
I'm using axios in my electron app to get data from an API. This data should be displayed on the touchbar once it's received. To manage the touchbar I added a new .ts file:

import electron, {
    BrowserWindow,
    TouchBar,
    TouchBarLabel,
    TouchBarButton,
    TouchBarSpacer
} from "electron";
import { IProject } from './types';

export function updateTouchBar(data: IProject[]) {
    let arr = [];
    data.forEach(ele => {
        arr.push(new electron.TouchBarLabel({ label: ele.name }));
    });

    publish(new TouchBar({ items: arr }));
}

export function publish(tb: TouchBar) {
    electron.remote.BrowserWindow.getFocusedWindow().setTouchBar(tb);
}

Displaying data in the window works, but the touchbar is not working: TouchBarLabel is not a constructor.

What does this mean and how can I fix it?

Thanks,
Lukas

Body:
I had the issue TouchBarLabel is not a constructor. and if your problem is anything like mine, the solution will be to rearrange the import statement like

import electron, { BrowserWindow, TouchBar } from "electron";
const { TouchBarLabel, TouchBarButton, TouchBarSpacer } = TouchBar;


问:
Two data should output unique values in csv using python
I'm a new python student and having issues in my csv output, it has duplicates of the matched condition I've searched it all over the internet already and found none.

How do i make this output, any method will do fine.

```<code>Data 1:
sitename,
www.google.com,
www.facebook.com,
www.twitter.com,
www.amazon.com

Data 2
sitename, founding date
www.google.com, 09/14/1998
www.amazon.com, 07/05/1994

if data 1 == data2['founding date']:
    writer.writerow([Data1, Founding Date])
else:
    writer.writerow([Data1, ''])
</code>```

the Output should be:

```<code>sitename, Founding date
www.google.com, 09/14/1998
www.facebook.com,
www.twitter.com,
www.amazon.com, 07/05/1994
</code>```

My Output:

```<code>sitename, Founding date,
www.google.com
www.google.com, 09/14/1998
www.facebook.com,
www.twitter.com,
www.amazon.com
www.amazon.com, 07/05/1994
</code>```

Thanks in advance!

答:
Trying out pandas...</p>

```<code>import pandas as pd
import io

Data1 = '''\
sitename,
www.google.com,
www.facebook.com,
www.twitter.com,
www.amazon.com
'''

Data2 = '''\
sitename, founding date
www.google.com, 09/14/1998
www.amazon.com, 07/05/1994
'''

d1 = pd.read_csv(io.StringIO(Data1), skipinitialspace=True)
d2 = pd.read_csv(io.StringIO(Data2), skipinitialspace=True, parse_dates=[1])

d3 = pd.merge(d1, d2, on='sitename', how='left')

print(d3[['sitename', 'founding date']])

</code>```

Body:
I'm a new python student and having issues in my csv output, it has duplicates of the matched condition I've searched it all over the internet already and found none.

How do i make this output, any method will do fine.

Data 1:
sitename,
www.google.com,
www.facebook.com,
www.twitter.com,
www.amazon.com

Data 2
sitename, founding date
www.google.com, 09/14/1998
www.amazon.com, 07/05/1994

if data 1 == data2['founding date']:
    writer.writerow([Data1, Founding Date])
else:
    writer.writerow([Data1, ''])

the Output should be:

sitename, Founding date
www.google.com, 09/14/1998
www.facebook.com,
www.twitter.com,
www.amazon.com, 07/05/1994

My Output:

sitename, Founding date,
www.google.com
www.google.com, 09/14/1998
www.facebook.com,
www.twitter.com,
www.amazon.com
www.amazon.com, 07/05/1994

Thanks in advance!

Body:
Trying out pandas...

import pandas as pd
import io

Data1 = '''\
sitename,
www.google.com,
www.facebook.com,
www.twitter.com,
www.amazon.com
'''

Data2 = '''\
sitename, founding date
www.google.com, 09/14/1998
www.amazon.com, 07/05/1994
'''

d1 = pd.read_csv(io.StringIO(Data1), skipinitialspace=True)
d2 = pd.read_csv(io.StringIO(Data2), skipinitialspace=True, parse_dates=[1])

d3 = pd.merge(d1, d2, on='sitename', how='left')

print(d3[['sitename', 'founding date']])


问:
How to consolidate / eliminate PHP includes for class files
I have multiple files that I keep including individually.  I want to just put them all in one file to decrease file I/O and just have one include.

Update

Ended up using an auto-loader here is the php.net reference.  Now I don't have to explicitly include each file and according to the reference the files are lazy loaded.

答:
You should absolutely not put all your classes in one file if you're developing them.  It makes things very difficult to maintain.  A separate file for each class means you know exactly where to go to change something.  And yes, PHP will spend time parsing classes you don't use.  Why don't you want to use an autoloader?  They make things so much easier, and it's not like they're a lot of overhead or anything.

If you're worried about IO efficiency, then cache your code.

Addressing naming conventions, I suggest you look at a pretty widely accepted standard here:

http://groups.google.com/group/php-standards/web/psr-0-final-proposal?pli=1


问:
Can not save pyplot histogram
I am trying to save a pyplot generated histogram . But when i try to save this it gives me an error savefig() takes 2 positional arguments but 3 were given. How to overcome this error?

Here is my code:

```<code>dir1=r"C:\Users\USER\Handcrafted dataset\histogram"
for i,img in enumerate(images1):
    plt.figure(figsize=(5,5))
    plt.hist(img.ravel(),256,[0,256])
    plt.savefig(dir1+"\\"+str(i)+".jpg",img)
    plt.show()
</code>```

答:
Just remove img and try using and also comment out plt.show(). Since you are creating a new figure every time, I do not see why you need img

```<code>plt.savefig(dir1+"\\"+str(i)+".jpg")
# plt.show()
</code>```

Title: Can not save pyplot histogram

Body:
I am trying to save a pyplot generated histogram . But when i try to save this it gives me an error savefig() takes 2 positional arguments but 3 were given. How to overcome this error?

Here is my code:

dir1=r"C:\Users\USER\Handcrafted dataset\histogram"
for i,img in enumerate(images1):
    plt.figure(figsize=(5,5))
    plt.hist(img.ravel(),256,[0,256])
    plt.savefig(dir1+"\\"+str(i)+".jpg",img)
    plt.show()

Body:
Just remove img and try using and also comment out plt.show(). Since you are creating a new figure every time, I do not see why you need img

plt.savefig(dir1+"\\"+str(i)+".jpg")
# plt.show()


问:
javascript map and join on an array
```<code>d = [
    ["a", "Adobe"]
    ["b", "Boston"]
    ["c", "Cars"]
    ["d", "Dominos"]
    ["e", "Microsoft"]
]
const asString = d.map(function(x){
        x[0],'=',x[1]
    }).join('&');
  console.log(asString);
</code>```

I'm trying to generate a query string from the above array, but seem to be getting only &&&&. The original solution used Template Literals and was like this:

```<code>const asString = d
      .map(x => `${encodeURIComponent(x[0])}=${encodeURIComponent(x[1])}`)
      .join('&');
  console.log(asString);
</code>```

This works fine, but I don't want to use Template Literals.

The end result is a querystring like this: a=Adobe&b=Boston&c=Cars&d=Dominos&e=Microsoft

答:
Using reduce

d = [
    ["a", "Adobe"],
    ["b", "Boston"],
    ["c", "Cars"],
    ["d", "Dominos"],
    ["e", "Microsoft"]
]
 let join = d.reduce((acc, elem)=>{
    return acc + elem.join("=") + '&'
 },"");

 console.log(join.slice(0, -1))```

Title: javascript map and join on an array

Body:
d = [
    ["a", "Adobe"]
    ["b", "Boston"]
    ["c", "Cars"]
    ["d", "Dominos"]
    ["e", "Microsoft"]
]
const asString = d.map(function(x){
        x[0],'=',x[1]
    }).join('&');
  console.log(asString);

I'm trying to generate a query string from the above array, but seem to be getting only &&&&. The original solution used Template Literals and was like this:

const asString = d
      .map(x => `${encodeURIComponent(x[0])}=${encodeURIComponent(x[1])}`)
      .join('&');
  console.log(asString);

This works fine, but I don't want to use Template Literals.

The end result is a querystring like this: a=Adobe&b=Boston&c=Cars&d=Dominos&e=Microsoft


问:
How can I automatically suggest the language for my Wordpress website based on the location?
I want my Site to be available in different languages, so when a visitor stops by, he automatically reads his language. </p>

<p>The Plugin should be free and easy to install :) </p>

答: Polylang is a great free and open-source WordPress plugin which allows you to create a bilingual or multilingual WordPress site. It detects the system language and will automatically switch to that language.

Body:
I want my Site to be available in different languages, so when a visitor stops by, he automatically reads his language.

The Plugin should be free and easy to install :)


问:
How to move the scaled point and keep the shape of the curve?
For a curve, I wanna move the start and end point to new position, and then how to keep the shape of the curve ?

From the points which circulated on the yellow curve, move them to red curve position which circulated on the red curve, how to keep the shape of the curve on the red curve ?

答:
So, let me summarize what you want to do here: given a Bezier curve or a B-spline curve and two new locations for the start point and end point, find a new Bezier/B-spline curve that more or less keeps the same shape as original curve.

One way to achieve this is to find a transformation that would transform the start/end points to their new locations, then you can apply the same transformation to all the other control points for the curve. Basically, this is the same as finding the transformation between a line defined by the curve's start point P and end point Q and another line defined by the new point locations P* and Q*. From P and P*, we can find a translation vector. From line PQ and line PQ, we can find a rotation angle. From length |PO| and length |PQ| we can find a scale factor.  So, combining the translation vector, rotation angle and the scale factor, we will be able to find the transformation matrix. Apply the transformation matrix onto all the other control points, then you should be able to get the new curve that more or less maintain the same shape as original curve.

If what you really wan to do is to offset the curves, then this is a totally different story. Offset curves are achieved by a far-more complex algorithm (which I will not elaborate here) and we will specify offset distance (could be positive or negative to imply outwards/inwards offset) instead of new locations for the start/end points.


问:
Add a dimension to a nifti file
I have nifti file (.nii) with a shape of (112, 176, 112). I want to add another dimension to it so that it becomes (112, 176, 112, 3). When I try img2 = np.arange(img).reshape(112,176,112,3) I get an error.
Is it possible to do this with np.reshape or np.arange or any other way?

Code:

```<code>import numpy as np
import nibabel as nib

filepath = 'test.nii'
img = nib.load(filepath)
img = img.get_fdata()

img = np.arange(img).reshape(112,176,112,3)

img = nib.Nifti1Image(img, np.eye(4))
img.get_data_dtype() == np.dtype(np.int16)
img.header.get_xyzt_units()
nib.save(img, 'test_add_channel.nii')
</code>```

Error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-f6f2a2d91a5d> in <module>
      8 print(img.shape)
      9
---> 10 img2 = np.arange(img).reshape(112,176,112,3)
     11
     12 img = nib.Nifti1Image(img, np.eye(4))

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

答:
You can do'it this way:

import numpy as np

img = np.random.rand(112, 176, 112)  # Your image
new_img = img.reshape((112, 176, 112, -1))  # Shape: (112, 176, 112, 1)
new_img = np.concatenate([new_img, new_img, new_img], axis=3)  # Shape: (112, 176, 112, 3)
```

Probably that is other better way to do'it, but the code above give you the output you want.

Title: Add a dimension to a nifti file

Body:
I have nifti file (.nii) with a shape of (112, 176, 112). I want to add another dimension to it so that it becomes (112, 176, 112, 3). When I try img2 = np.arange(img).reshape(112,176,112,3) I get an error.
Is it possible to do this with np.reshape or np.arange or any other way?

Code:

import numpy as np
import nibabel as nib

filepath = 'test.nii'
img = nib.load(filepath)
img = img.get_fdata()

img = np.arange(img).reshape(112,176,112,3)

img = nib.Nifti1Image(img, np.eye(4))
img.get_data_dtype() == np.dtype(np.int16)
img.header.get_xyzt_units()
nib.save(img, 'test_add_channel.nii')

Error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-f6f2a2d91a5d> in <module>
      8 print(img.shape)
      9
---> 10 img2 = np.arange(img).reshape(112,176,112,3)
     11
     12 img = nib.Nifti1Image(img, np.eye(4))

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Body:
You can do'it this way:

import numpy as np

img = np.random.rand(112, 176, 112)  # Your image
new_img = img.reshape((112, 176, 112, -1))  # Shape: (112, 176, 112, 1)
new_img = np.concatenate([new_img, new_img, new_img], axis=3)  # Shape: (112, 176, 112, 3)

Probably that is other better way to do'it, but the code above give you the output you want.


问:
RecyclerView cannot be found
I just started to try to use the RecyclerView. I added some lines into the build.grandle but I always get many error messages telling me:
' error: cannot find symbol'
' error: package androidx.recyclerview.widget does not exist'
and I do not understand why I am getting these error messages. Here you see the code of my grandle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.td.barapp"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        viewBinding {
            enabled = true
        }

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.0.0'
    implementation 'com.android.support:cardview-v7:27.0.0'
}
</code>```

I'd appreciate every comment and would be quite thankful.

Update: I think I have a problem with AndroidX. I migrated to it by using Refactor-->Migrate to AndroidX in Android studio but I do not know how I should change my posted grandle.build file. At the moment in my grandle file I have some libararies like " implementation 'com.android.support:design:27.1.1' and I get the warning and error message: "This support library should not use a different version (27) than the compileSdkVersion (28) " But when I use " implementation 'com.android.support:appcompat-v7:28.0'" I also get an error message :"All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.1.1, 27.0.0. Examples include com.android.support:animated-vector-drawable..

Here you see a screenshot of the marked lines in the Build grandle file: How do I have to change these lines in order to use AndroidX? I'd be happy for your help because I am stuck on that problem.

答:
Add this line to gradle dependencies

```<code>implementation "androidx.recyclerview:recyclerview:1.1.0"
</code>```

Also make sure these lines are present in your gradle.properties file:

```<code>android.enableJetifier=true
android.useAndroidX=true
</code>```

Title: RecyclerView cannot be found

Body:
I just started to try to use the RecyclerView. I added some lines into the build.grandle but I always get many error messages telling me:
' error: cannot find symbol'
' error: package androidx.recyclerview.widget does not exist'
and I do not understand why I am getting these error messages. Here you see the code of my grandle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.td.barapp"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        viewBinding {
            enabled = true
        }

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.0.0'
    implementation 'com.android.support:cardview-v7:27.0.0'
}

I'd appreciate every comment and would be quite thankful.

Update: I think I have a problem with AndroidX. I migrated to it by using Refactor-->Migrate to AndroidX in Android studio but I do not know how I should change my posted grandle.build file. At the moment in my grandle file I have some libararies like " implementation 'com.android.support:design:27.1.1' and I get the warning and error message: "This support library should not use a different version (27) than the compileSdkVersion (28) " But when I use " implementation 'com.android.support:appcompat-v7:28.0'" I also get an error message :"All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.1.1, 27.0.0. Examples include com.android.support:animated-vector-drawable..

Here you see a screenshot of the marked lines in the Build grandle file: How do I have to change these lines in order to use AndroidX? I'd be happy for your help because I am stuck on that problem.

Body:
Add this line to gradle dependencies

implementation "androidx.recyclerview:recyclerview:1.1.0"

Also make sure these lines are present in your gradle.properties file:

android.enableJetifier=true
android.useAndroidX=true


问:
Chrome Devtools opens as a search rather then the dev tools themselves
Trying to run a Nativescript debug session and every time I enter

chrome-devtools://devtools/bundled/inspector.html?experiments=true&ws=localhost:41000

it opens a google search rather than the debug session.

https://www.google.com/search?q=chrome-devtools%3A%2F%2Fdevtools%2Fbundled%2Finspector.html%3Fexperiments%3Dtrue%26ws%3Dlocalhost%3A41000&oq=chrome-devtools%3A%2F%2Fdevtools%2Fbundled%2Finspector.html%3Fexperiments%3Dtrue%26ws%3Dlocalhost%3A41000&aqs=chrome.0.69i59j69i60j69i61.1074j0j7&sourceid=chrome&ie=UTF-8

Any ideas how to fix this please.

答:
I was faced with the ERR_INVALID_URL when i tried with @IanMacDonalds answer.

For some reason navigating to the URL without parameters first, loaded devtools properly.

```<code>devtools://devtools/bundled/inspector.html
</code>```

Then adding the params on afterwards got the debugging session working again.

```<code>?experiments=true&ws=localhost:40000
</code>```

Hope that helps @Przemo

Body:
I was faced with the ERR_INVALID_URL when i tried with @IanMacDonalds answer.

For some reason navigating to the URL without parameters first, loaded devtools properly.

devtools://devtools/bundled/inspector.html

Then adding the params on afterwards got the debugging session working again.

?experiments=true&ws=localhost:40000

Hope that helps @Przemo


问:
Finding if a value does not exist in SQL
My data is structured with 5 columns (let's call them a, b, c, d, e) and 1,000,000+ rows. Each value in b has the potential for ~50 possibilities in e - so there could be up to 50 lines for each unique b value. Every b should have a '-27' among their e values. I would like to query all UNIQUE b where it doesn't have the -27 e value, ignoring all other possibilities for e.

Code so far:

```<code>select a, b, c, d, e
from TestDB
where not exists (select count(distinct b) from TestDB where e = '-27')
</code>```

Would this code be sufficient? In initial tests I've done it appears to be either a) working or b) returning nothing. I'm new to SQL so I appreciate any help or being pointed in the right direction!

**edited to make it clearer I was looking for unique 'b' values.

答:
This query:

```<code>select b from TestDB where e = '-27'
</code>```

returns all the bs that you want filtered out.

Use it with the operator NOT IN:

```<code>select a, b, c, d, e
from TestDB
where b not in (select b from TestDB where e = '-27')
</code>```

Body:
My data is structured with 5 columns (let's call them a, b, c, d, e) and 1,000,000+ rows. Each value in b has the potential for ~50 possibilities in e - so there could be up to 50 lines for each unique b value. Every b should have a '-27' among their e values. I would like to query all UNIQUE b where it doesn't have the -27 e value, ignoring all other possibilities for e.

Code so far:

select a, b, c, d, e
from TestDB
where not exists (select count(distinct b) from TestDB where e = '-27')

Would this code be sufficient? In initial tests I've done it appears to be either a) working or b) returning nothing. I'm new to SQL so I appreciate any help or being pointed in the right direction!

**edited to make it clearer I was looking for unique 'b' values.

Body:
This query:

select b from TestDB where e = '-27'

returns all the bs that you want filtered out.

Use it with the operator NOT IN:

select a, b, c, d, e
from TestDB
where b not in (select b from TestDB where e = '-27')


问:
Iterate by forEach loop in vanillaJS do not work for keyup event, but works fine for click event
I'm emitting by socket.IO poke-message to the user and on below code I achieved only (onclick parts) and it worked as it should but doesn't have idea what's wrong on keyup part... Also, tried on keydown event but didn't work. I don't want to do it by passing function declaration to the event as arg, but like anonymous function and better understand what's going on behind a scene. I'll appreciate any help or tip.

```<code>["keyup", "click"].forEach(
  (evt) =>
    document
      .getElementById(eachUser.buttonElement)
      .addEventListener(evt, () => {
        if ((evt === "keyup" && evt.keyCode === 13) || evt === "click") {
          const pokeMessage = document.getElementById(eachUser.inputElement)
            .value;
          private_socket.emit("poke message", {
            username: user.name,
            sessionID: user.sessionID,
            pokeMessage: pokeMessage,
          });
          pokeUser.parentNode.removeChild(pokeUser);
        } else {
          return;
        }
      }),
  false
);
</code>```

答:
The problem is that you confused the evt variable coming from your forEach loop with the Event object that your code got as an argument, but didn't take.

In your code, evt is the name of the event for which the currently called listener was added (either "keyup" or "click").

When you evaluate evt.keyCode, it returns undefined (neither of the event name strings have keyCode property), and your code stops working.

You probably wanted to access the keyCode property of the current event instead, which you can access as a parameter in the event listener:

["keyup", "click"].forEach(
  (eventName) =>
// ^^^^^^^^^--- Renamed for clarity
    document
      .getElementById(eachUser.buttonElement)
      .addEventListener(eventName, eventObj => {
                          // ^^^^^^^^--- take argument (and name it whatever you want)
        if ((eventName === "keyup" && eventObj.keyCode === 13) || eventName === "click") {
          const pokeMessage = document.getElementById(eachUser.inputElement)
            .value;
          private_socket.emit("poke message", {
            username: user.name,
            sessionID: user.sessionID,
            pokeMessage: pokeMessage,
          });
          pokeUser.parentNode.removeChild(pokeUser);
        } else {
          return;
        }
      }),
  false
);
```

Body:
I'm emitting by socket.IO poke-message to the user and on below code I achieved only (onclick parts) and it worked as it should but doesn't have idea what's wrong on keyup part... Also, tried on keydown event but didn't work. I don't want to do it by passing function declaration to the event as arg, but like anonymous function and better understand what's going on behind a scene. I'll appreciate any help or tip.

["keyup", "click"].forEach(
  (evt) =>
    document
      .getElementById(eachUser.buttonElement)
      .addEventListener(evt, () => {
        if ((evt === "keyup" && evt.keyCode === 13) || evt === "click") {
          const pokeMessage = document.getElementById(eachUser.inputElement)
            .value;
          private_socket.emit("poke message", {
            username: user.name,
            sessionID: user.sessionID,
            pokeMessage: pokeMessage,
          });
          pokeUser.parentNode.removeChild(pokeUser);
        } else {
          return;
        }
      }),
  false
);


问:
What is preferred implementation of Chrome extension that catches and reads newly added list values on one specific web page?
I need to create a Chrome extension that will work only for one webpage with specific URL. It will monitor changes to list of items (orders) located on page and if new order appears, it will read some values from order and do something with them. It also may be neccessary to refresh the page from time to time (using timer, maybe).

What architechture will be suitable to accomplish such a task?

Now - to thoughts I have so far. I think now of using only one content script bound to page URL. Will it be enough? Or should I introduce some background script also? Or anything else?

答: As @wOxxOm said in the comments, creating one content script must be sufficient for reading the values and page refreshing.</p>


问:
How to sculpt with odd linear artefacts
I am currently learning how to sculpt in Blender; working on my own projects after completing BlenderGuru's Beginner & Intermediate classes, and some of Grant Abbitts videos with pleasing results. I am trying to sculpt a plasmapistol with a skull on it, which can be seen in the reference photo that I have provided.

However, when I sculpt, I get these really odd linear artefacts (See picture below, circled in black). I added a Subsurf Modifier to the primitive UV Sphere, with the Viewport and Render Values set to 4, so it is a fairly fine mesh. However, these still artefacts occur.

I assume it is due to the stretching of the polygons when I grab the sphere with the Snake Hook tool and deform it to encompass the frontal part of the skull.

EDIT: Whilst writing this comment I went back, and switched on Dynamic Topology with Relative Detail selected.

It appears that I am no longer getting the issues that I was getting last night with the linear artefacts.

Can I confirm that these problems are a result of having the incorrect Dynamic Topology settings for using the Snake Hook Tool; I was using Constant Detail instead of Relative Detail, or is this being caused by another issue?

Also, any advice on avoiding common pitfalls when choosing the settings in sculpting would be most appreciated.

I will continue to ask this question incase anyone has a similar problem and it can be resolved by reading this.

Sculpt, showing lineations

Experimenting with Dynamic Topology

答:
In Object Mode, does the object have uniform X, Y, & Z scaling? If not, you can apply the scale from the object menu.

Object ‣ Apply ‣ Scale / Rotation & Scale

Title: How to sculpt with odd linear artefacts


问:
AWS IoT - SQL Question - Create JSON from '*'
I am trying to find out whether it's possible to create JSON (to forward to a Kinesis stream) based on a combination of a non-JSON input string and some IoT functions

More specifically, something like

```<code>SELECT topic() as topic, clientid() as device, * as msg FROM 'sometopic'
</code>```

Where the message could be anything (in my case a CSV payload/string)

While the rule as such does not trigger any error when entering and updating, it does not seem to forward anything to the Kinesis stream. I also cannot find any trace in any cloudwatch log I looked.

A slightly adapted rule

```<code>SELECT topic() as topic, clientid() as device,* FROM 'sometopic'
</code>```

works fine when the device sends a JSON string (e.g. {"msg":"message payload"})

Ideally it would be more optimal if the client could just publish "message payload"

(Using basic ingest)

All tips warmly welcomed!

Tx

Peter

答:
Some rule actions don't support non-JSON payloads. To send binary data to a rule action that only supports JSON, you can encode the data in base64 and then decode it in the receiving service.

```<code>SELECT topic() as topic, clientid() as device, encode(*, 'base64') as msg FROM 'sometopic'
</code>```

See Working with binary payloads.

Body:
I am trying to find out whether it's possible to create JSON (to forward to a Kinesis stream) based on a combination of a non-JSON input string and some IoT functions

More specifically, something like

SELECT topic() as topic, clientid() as device, * as msg FROM 'sometopic'

Where the message could be anything (in my case a CSV payload/string)

While the rule as such does not trigger any error when entering and updating, it does not seem to forward anything to the Kinesis stream. I also cannot find any trace in any cloudwatch log I looked.

A slightly adapted rule

SELECT topic() as topic, clientid() as device,* FROM 'sometopic'

works fine when the device sends a JSON string (e.g. {"msg":"message payload"})

Ideally it would be more optimal if the client could just publish "message payload"

(Using basic ingest)

All tips warmly welcomed!

Tx

Peter

Body:
Some rule actions don't support non-JSON payloads. To send binary data to a rule action that only supports JSON, you can encode the data in base64 and then decode it in the receiving service.

SELECT topic() as topic, clientid() as device, encode(*, 'base64') as msg FROM 'sometopic'

See Working with binary payloads.


问:
Turning an array of integers into an array of nonnegative integers
Start with an array of integers so that the sum of the values is some positive integer S. The following routine always terminates in the same number of steps with the same results. Why is this?

Start with an array x = [x_0, x_1, ..., x_N-1] such that all x_i's are integers. While there is a negative entry, do the following:

Choose any index i such that x_i < 0.

Add x_i (a negative number) to x_(i-1 % N).

Add x_i (a negative number) to x_(i+1 % N).

Replace x_i with -x_i (a positive number).

This process maintains the property that x_0 + x_1 + ... + x_N-1 = S. For any given starting array x, no matter which index is chosen at any step, the number of times one goes through these steps is the same as is the resulting vector. It is not even obvious (to me, at least) that this process terminates in finite time, let alone has this nice invariant property.

EXAMPLE:

Take x = [4 , -1, -2] and flipping x_1 to start, the result is

```<code>[4, -1, -2]
[3, 1, -3]
[0, -2, 3]
[-2, 2, 1]
[2, 0, -1]
[1, -1, 1]
[0, 1, 0]
</code>```

On the other hand, flipping x_2 to start gives

```<code>[4, -1, -2]
[2, -3, 2]
[-1, 3, -1]
[1, 2, -2]
[-1, 0, 2]
[1, -1, 1]
[0, 1, 0]
</code>```

and the final way give this solution with arrays reversed from the third on down if you choose x_2 instead of x_0 to flip at the third array. In all cases, 6 steps lead to [0,1,0].

I have an argument for why this is true, but it seems to me to be overly complicated (it has to do with Coxeter groups). Does anyone have a more direct way to think about why this happens? Even finding a reason why this should terminate would be great.

Bonus points to anyone who finds a way to determine the number of steps for a given array (without going through the process).

答:
I think the easiest way to see why the output vector and the number of steps are the same no matter what index you choose at each step is to look at the problem as a bunch of matrix and vector multiplications.

For the case where x has 3 components, think of x as a 3x1 vector: x = [x_0 x_1 x_2]' (where ' is the transpose operation). Each iteration of the loop will choose to flip one of x_0,x_1,x_2, and the operation it performs on x is identical to multiplication by one of the following matrices:

```<code>      -1  0  0               1  1  0                1  0  1
s_0 =  1  1  0       s_1 =   0 -1  0        s_2 =   0  1  1
       1  0  1               0  1  1                0  0 -1
</code>```

where multiplication by s_0 is the operation performed if the index i=0, s_1 corresponds to i=1, and s_2 corresponds to i=2. With this view, you can interpret the algorithm as multiplying the corresponding s_i matrix by x at each iteration. So in the first example where x_1 is flipped at the start, the algorithm computes: s_1*s_2*s_0*s_1*s_2*s_1[4 -1 -2]' = [0 1 0]'

The fact that the index you choose doesn't affect the final output vector arises from two interesting properties of the s matrices. First, s_i*s_(i-1)*s_i = s_(i-1)*s_i*s(i-1), where i-1 is computed modulo n, the number of matrices. This property is the only one needed to see why you get the same result in the examples with 3 elements:

s_1*s_2*s_0*s_1*s_2*s_1 = s_1*s_2*s_0*(s_1*s_2*s_1) = s_1*s_2*s_0*(s_2*s_1*s_2), which corresponds to choosing x_2 at the start, and lastly:

s_1*s_2*s_0*s_2*s_1*s_2 = s_1*(s_2*s_0*s_2)*s_1*s_2 = s_1*(s_0*s_2*s_0)*s1*s2, which corresponds to choosing to flip x_2 at the start, but then choosing to flip x_0 in the third iteration.

The second property only applies when x has 4 or more elements. It is s_i*s_k = s_k*s_i whenever k <= i-2 where i-2 is again computed modulo n. This property is apparent when you consider the form of matrices when x has 4 elements:

```<code>       -1  0  0  0          1  1  0  0          1  0  0  0          1  0  0  1
s_0 =   1  1  0  0   s_1 =  0 -1  0  0   s_2 =  0  1  1  0   s_3 =  0  1  0  0
        0  0  1  0          0  1  1  0          0  0 -1  0          0  0  1  1
        1  0  0  1          0  0  0  1          0  0  1  1          0  0  0 -1
</code>```

The second property essentially says that you can exchange the order in which non-conflicting flips occur. For example, in a 4 element vector, if you first flipped x_1 and then flipped x_3, this has the same effect as first flipping x_3 and then flipping x_1.

Body:
Start with an array of integers so that the sum of the values is some positive integer S. The following routine always terminates in the same number of steps with the same results. Why is this?

Start with an array x = [x_0, x_1, ..., x_N-1] such that all x_i's are integers. While there is a negative entry, do the following:

Choose any index i such that x_i < 0.

Add x_i (a negative number) to x_(i-1 % N).

Add x_i (a negative number) to x_(i+1 % N).

Replace x_i with -x_i (a positive number).

This process maintains the property that x_0 + x_1 + ... + x_N-1 = S. For any given starting array x, no matter which index is chosen at any step, the number of times one goes through these steps is the same as is the resulting vector. It is not even obvious (to me, at least) that this process terminates in finite time, let alone has this nice invariant property.

EXAMPLE:

Take x = [4 , -1, -2] and flipping x_1 to start, the result is

[4, -1, -2]
[3, 1, -3]
[0, -2, 3]
[-2, 2, 1]
[2, 0, -1]
[1, -1, 1]
[0, 1, 0]

On the other hand, flipping x_2 to start gives

[4, -1, -2]
[2, -3, 2]
[-1, 3, -1]
[1, 2, -2]
[-1, 0, 2]
[1, -1, 1]
[0, 1, 0]

and the final way give this solution with arrays reversed from the third on down if you choose x_2 instead of x_0 to flip at the third array. In all cases, 6 steps lead to [0,1,0].

I have an argument for why this is true, but it seems to me to be overly complicated (it has to do with Coxeter groups). Does anyone have a more direct way to think about why this happens? Even finding a reason why this should terminate would be great.

Bonus points to anyone who finds a way to determine the number of steps for a given array (without going through the process).

Body:
I think the easiest way to see why the output vector and the number of steps are the same no matter what index you choose at each step is to look at the problem as a bunch of matrix and vector multiplications.

For the case where x has 3 components, think of x as a 3x1 vector: x = [x_0 x_1 x_2]' (where ' is the transpose operation). Each iteration of the loop will choose to flip one of x_0,x_1,x_2, and the operation it performs on x is identical to multiplication by one of the following matrices:

      -1  0  0               1  1  0                1  0  1
s_0 =  1  1  0       s_1 =   0 -1  0        s_2 =   0  1  1
       1  0  1               0  1  1                0  0 -1

where multiplication by s_0 is the operation performed if the index i=0, s_1 corresponds to i=1, and s_2 corresponds to i=2. With this view, you can interpret the algorithm as multiplying the corresponding s_i matrix by x at each iteration. So in the first example where x_1 is flipped at the start, the algorithm computes: s_1*s_2*s_0*s_1*s_2*s_1[4 -1 -2]' = [0 1 0]'

The fact that the index you choose doesn't affect the final output vector arises from two interesting properties of the s matrices. First, s_i*s_(i-1)*s_i = s_(i-1)*s_i*s(i-1), where i-1 is computed modulo n, the number of matrices. This property is the only one needed to see why you get the same result in the examples with 3 elements:

s_1*s_2*s_0*s_1*s_2*s_1 = s_1*s_2*s_0*(s_1*s_2*s_1) = s_1*s_2*s_0*(s_2*s_1*s_2), which corresponds to choosing x_2 at the start, and lastly:

s_1*s_2*s_0*s_2*s_1*s_2 = s_1*(s_2*s_0*s_2)*s_1*s_2 = s_1*(s_0*s_2*s_0)*s1*s2, which corresponds to choosing to flip x_2 at the start, but then choosing to flip x_0 in the third iteration.

The second property only applies when x has 4 or more elements. It is s_i*s_k = s_k*s_i whenever k <= i-2 where i-2 is again computed modulo n. This property is apparent when you consider the form of matrices when x has 4 elements:

       -1  0  0  0          1  1  0  0          1  0  0  0          1  0  0  1
s_0 =   1  1  0  0   s_1 =  0 -1  0  0   s_2 =  0  1  1  0   s_3 =  0  1  0  0
        0  0  1  0          0  1  1  0          0  0 -1  0          0  0  1  1
        1  0  0  1          0  0  0  1          0  0  1  1          0  0  0 -1

The second property essentially says that you can exchange the order in which non-conflicting flips occur. For example, in a 4 element vector, if you first flipped x_1 and then flipped x_3, this has the same effect as first flipping x_3 and then flipping x_1.


问:
ASP .NET Core Web API load 32bit library in IIS leads to BadImageFormatException with 32bit enabled
So I want to run a ASP .NET Core 3.1 Web API in IIS which needs to load a 32bit library. SO I just enabled the 32bit feature in the ApplicationPool. Also is see in the TaskManager that the process is 32bit. Also I set installed the 32bit dotnet sdk and set the PATH variable to the 32bit version. But always I want to execute a method which loads the 32bit assembly I get an System.BadImageFormatException: Could not load file or assembly error which means that the process is 64bit??
When I start without the IIS it works just fine.

For building I used the win-x86 runtime

答: So I managed to fix my issue by installing Visual C++ 2013 Redistributable</p>


问:
Is there a way to skip some routes by react-router-dom
I am working on a project with create-react-app and i am planning to use strapi as my admin. I am using "react-router-dom" package for handling all my routes. However, i want to skip "/admin" from 'react-router-dom' and let it make a request to server to access strapi admin. For instance, this is how my project is handling routes at the moment.

```<code><Switch>
   <Route exact path='/' component={Home}/>
   <Route exact path='/article' component={Article}/>
   <Route exact path='/article/:id' component={ArticleDetail}/>
   <Route component={NoMatchRoute}/>
   <Route exact path='/admin' render={() => //redirect to www.example.com/admin}/>
 </Switch>
</code>```

In above example when i try to go to /admin route, it is giving me No page found and it just goes in loop, however...if i hard reload my browser, i am being able to go to the strapi admin login page, which is kind of annoying for everyday use. Any helpful tips will be much appreciated.

答:
You can skip some routes by specifing <Redirect/>

```<code><Switch>
       <Route exact path='/' component={Home}/>
       <Route exact path='/article' component={Article}/>
       <Route exact path='/article/:id' component={ArticleDetail}/>
       <Redirect exact path='/admin' to="www.example.com/admin"/> // use "https://www.example.com/admin" if it doesn't work
       <Route component={NoMatchRoute}/>
</Switch>
</code>```

Body:
I am working on a project with create-react-app and i am planning to use strapi as my admin. I am using "react-router-dom" package for handling all my routes. However, i want to skip "/admin" from 'react-router-dom' and let it make a request to server to access strapi admin. For instance, this is how my project is handling routes at the moment.

<Switch>
   <Route exact path='/' component={Home}/>
   <Route exact path='/article' component={Article}/>
   <Route exact path='/article/:id' component={ArticleDetail}/>
   <Route component={NoMatchRoute}/>
   <Route exact path='/admin' render={() => //redirect to www.example.com/admin}/>
 </Switch>

In above example when i try to go to /admin route, it is giving me No page found and it just goes in loop, however...if i hard reload my browser, i am being able to go to the strapi admin login page, which is kind of annoying for everyday use. Any helpful tips will be much appreciated.

Body:
You can skip some routes by specifing <Redirect/>

<Switch>
       <Route exact path='/' component={Home}/>
       <Route exact path='/article' component={Article}/>
       <Route exact path='/article/:id' component={ArticleDetail}/>
       <Redirect exact path='/admin' to="www.example.com/admin"/> // use "https://www.example.com/admin" if it doesn't work
       <Route component={NoMatchRoute}/>
</Switch>


问:
Is it possible to hold multiple types of enums in a variable in C++?
Is it possible to do something like this in C++:

enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
    eg1,
    eg2,
    eg3,
    ...
}

enum B {//Same structure as enum A
    e1,
    e2,
    e3,
    ...
}

some_data_type e = eg1;//No errors here
e = e2;//No errors here
```

I think it could be something like just an integer, but just to be safe is there another way to do this?

答:
In C++17 and later, you can use std::variant for that:

enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
    eg1,
    eg2,
    eg3,
    ...
}

enum B {//Same structure as enum A
    e1,
    e2,
    e3,
    ...
}

std::variant e = eg1;
e = e2;
```

Body:
Is it possible to do something like this in C++:

enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
    eg1,
    eg2,
    eg3,
    ...
}

enum B {//Same structure as enum A
    e1,
    e2,
    e3,
    ...
}

some_data_type e = eg1;//No errors here
e = e2;//No errors here

I think it could be something like just an integer, but just to be safe is there another way to do this?

Body:
In C++17 and later, you can use std::variant for that:

enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
    eg1,
    eg2,
    eg3,
    ...
}

enum B {//Same structure as enum A
    e1,
    e2,
    e3,
    ...
}

std::variant<A,B> e = eg1;
e = e2;


问:
How to keep time index when using DolphinDB Python API
When I upload a pandas.DataFrame with a time index like:

```<code>    index   |   value
 ===========|===========
 2019-02-03 |    3.9
 2019-02-04 |    4.0
</code>```

to DolphinDB server, the index seems to be dropped in DolphinDB Python API:

```<code>    value
 ===========
     3.9
     4.0
</code>```

How to keep the time index?

答: DolphinDB database does not import pandas.DataFrame's index. To keep the index column in DolphinDB, you can use df.reset_index() to create a new column in the DolphinDB table for the index. </p>

Body:
When I upload a pandas.DataFrame with a time index like:

    index   |   value
 ===========|===========
 2019-02-03 |    3.9
 2019-02-04 |    4.0

to DolphinDB server, the index seems to be dropped in DolphinDB Python API:

    value
 ===========
     3.9
     4.0

How to keep the time index?


问:
Putting coding within a ListObject table
The below VBA code looks down column B in a table. When a value (60) is identified in Column B, I then copy the adjacent value from Column C into Column D.
I've tried doing an offset which works fine when not in a formal ListObject table, but I get an error message when within a table "invalid or unqualified reference".
How to I update the VBA code to work within an excel table?  I've searched around and tried a few changes but still getting errors.</p>

```<code>Sub TableFind()

Dim LastRow As Long
Dim rng As Range, C As Range

With Worksheet.ListObjects("myTable")
    LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
    Set rng = .Range("B2:B" & LastRow)

        For Each C In rng
        If C.Value = "60" Then
            C.Offset(, 3).Copy
            C.Offset(, 4).PasteSpecial Paste:=xlPasteValues
        End If
    Next C
End With

End Sub
</code>```

答:
There is no need to find the last row in a table; DataBodyRange refers to the body of the table so just work with that.

Assuming your table starts in column A, you could potentially do the following:

```<code>With Worksheet.ListObjects("myTable")
    For Each C in .ListColumns(2).DataBodyRange
        If C.Value = "60" Then
            C.Offset(, 2).Value = C.Offset(,1).Value
        End If
    Next C
End With
</code>```

Body:
The below VBA code looks down column B in a table. When a value (60) is identified in Column B, I then copy the adjacent value from Column C into Column D.
I've tried doing an offset which works fine when not in a formal ListObject table, but I get an error message when within a table "invalid or unqualified reference".
How to I update the VBA code to work within an excel table?  I've searched around and tried a few changes but still getting errors.

Sub TableFind()

Dim LastRow As Long
Dim rng As Range, C As Range

With Worksheet.ListObjects("myTable")
    LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
    Set rng = .Range("B2:B" & LastRow)

        For Each C In rng
        If C.Value = "60" Then
            C.Offset(, 3).Copy
            C.Offset(, 4).PasteSpecial Paste:=xlPasteValues
        End If
    Next C
End With

End Sub

Body:
There is no need to find the last row in a table; DataBodyRange refers to the body of the table so just work with that.

Assuming your table starts in column A, you could potentially do the following:

With Worksheet.ListObjects("myTable")
    For Each C in .ListColumns(2).DataBodyRange
        If C.Value = "60" Then
            C.Offset(, 2).Value = C.Offset(,1).Value
        End If
    Next C
End With


问:
Error using tensorflow with tf.image.adjust_jpeg_quality , output shape is unknown?
when I run the demo code:

```<code>x = tf.random.normal(shape=(256, 256, 3))
y = tf.image.adjust_jpeg_quality(x, 75)
print('y shape is: ', y.shape)
</code>```

output as follows：

y shape is:  (?, ?, ?)

should the output is (256, 256, 3)？ why？  anything wrong？

my tensorflow version is 1.14

答:
In TF 1.x to print output, you need to execute code with in the session as below

```<code>%tensorflow_version 1.x

import tensorflow as tf
print(tf.__version__)

with tf.Session() as sess:
  x = tf.random.normal(shape=(256, 256, 3))
  y = tf.image.adjust_jpeg_quality(x, 75)
  print(sess.run(tf.shape(y)))
</code>```

Output:

```<code>1.15.2
[256 256 3]
</code>```

In TF 2.x, eager execution enabled by default, hence you don't need session

```<code>%tensorflow_version 2.x
import tensorflow as tf
print(tf.__version__)

x = tf.random.normal(shape=(256, 256, 3))
y = tf.image.adjust_jpeg_quality(x, 75)
print(y.shape)
</code>```

Output:

```<code>2.2.0
(256, 256, 3)
</code>```

Body:
when I run the demo code:

x = tf.random.normal(shape=(256, 256, 3))
y = tf.image.adjust_jpeg_quality(x, 75)
print('y shape is: ', y.shape)

output as follows：

y shape is:  (?, ?, ?)

should the output is (256, 256, 3)？ why？  anything wrong？

my tensorflow version is 1.14

Body:
In TF 1.x to print output, you need to execute code with in the session as below

%tensorflow_version 1.x

import tensorflow as tf
print(tf.__version__)

with tf.Session() as sess:
  x = tf.random.normal(shape=(256, 256, 3))
  y = tf.image.adjust_jpeg_quality(x, 75)
  print(sess.run(tf.shape(y)))

Output:

1.15.2
[256 256 3]

In TF 2.x, eager execution enabled by default, hence you don't need session

%tensorflow_version 2.x
import tensorflow as tf
print(tf.__version__)

x = tf.random.normal(shape=(256, 256, 3))
y = tf.image.adjust_jpeg_quality(x, 75)
print(y.shape)

Output:

2.2.0
(256, 256, 3)


问:
Which module to manage nodes in multiple tree?
I am creating a web tool to manage bills of materials (BOM).
I managed to get some nice presentation of BOMs using django with js-tree but now I would like to put all of this in a database.
My trees look like this:

```<code>- Root Part (ie Product A)
  - PartA - Qty: 1
    - PartB - Qty: 1
  - PartC - Qty: 1
    - Part D - Qty: 4
    - Part E - Qty: 1
      - Part F - Qty: 2
...
</code>```

The problem is that a same part can be present in different products, or in different subassembly (think of a screw for example).

I would like to be able to reuse an existing node (and its children) in an other tree (for example I could have a Product B that also include Part E (and thus Part F)).
If I am updating a node (ie Part E) the change should appear in every trees where it is used.

django-mptt seems a good candidate but unfortunately a node can only have one parent.
There is a TreeManyToManyField but nothing in the documentation about it, I am not sure if it could help me.

I could create the Part as a regular model and have a second model Bom Structure to create the trees, each instance being link to a Part but I can't see how it will keep the children of a part.

How does people manage this issue usually?

答:
There is a newer solution for BOM:
BOM is a simple Django app to manage a bill of materials. It supports multiple part numbering schemes, tracking component sourcing information, estimates costs, and contains smart integrations with Mouser to pull in the latest component pricing and Google Drive for part file management. BOM is written in Python 3 and Django 3.
https://pypi.org/project/django-bom/</p>

Body:
I am creating a web tool to manage bills of materials (BOM).
I managed to get some nice presentation of BOMs using django with js-tree but now I would like to put all of this in a database.
My trees look like this:

- Root Part (ie Product A)
  - PartA - Qty: 1
    - PartB - Qty: 1
  - PartC - Qty: 1
    - Part D - Qty: 4
    - Part E - Qty: 1
      - Part F - Qty: 2
...

The problem is that a same part can be present in different products, or in different subassembly (think of a screw for example).

I would like to be able to reuse an existing node (and its children) in an other tree (for example I could have a Product B that also include Part E (and thus Part F)).
If I am updating a node (ie Part E) the change should appear in every trees where it is used.

django-mptt seems a good candidate but unfortunately a node can only have one parent.
There is a TreeManyToManyField but nothing in the documentation about it, I am not sure if it could help me.

I could create the Part as a regular model and have a second model Bom Structure to create the trees, each instance being link to a Part but I can't see how it will keep the children of a part.

How does people manage this issue usually?


问:
In Wordpress's Blocks editor, How do I insert a block inside a list item
I have a list of text items and I want to add an image or a code element or any other block inside that list item. How is this accomplished with Wordpress's new Blocks editor? Adding a new block always puts it outside of the list block, rather than inside the current list item, as I want.</p>

答:
Unfortunately, the WP Core List Block does not allow inner blocks. It can only contain text. You can force it to allow line breaks by pressing "shift + enter" between paragraphs, but that just adds a
 tag and not even a separate paragraph. They simply didn't code lists to contain anything other than
s and
s.

It wouldn't be surprising if someone has created a third-party list block that can contain Inner Blocks, so you might try searching for a plugin for now, and perhaps raising an issue on GitHub requesting this feature. (I didn't see any issues/requests at first glance but there may already be one.)

Body:
Unfortunately, the WP Core List Block does not allow inner blocks. It can only contain text. You can force it to allow line breaks by pressing "shift + enter" between paragraphs, but that just adds a <br> tag and not even a separate paragraph. They simply didn't code lists to contain anything other than <li>s and <br>s.

It wouldn't be surprising if someone has created a third-party list block that can contain Inner Blocks, so you might try searching for a plugin for now, and perhaps raising an issue on GitHub requesting this feature. (I didn't see any issues/requests at first glance but there may already be one.)


问:
unable to understand codility fish
https://app.codility.com/demo/results/trainingAQH33G-WVS/

```<code>Array.prototype.peek = function() {
    return this[this.length-1]
}

export const fish = (A = [4, 3, 2, 1, 5], B = [0, 1, 0, 0, 0]) => {

    console.log(` A ${A}, B ${B} `)
    let c = B[0]
    let s = []
    s.push(A[0])
    console.log(`init c ${c}, n , s ${s}, A[0] ${A[0]}, `)
    console.log(`starting with ${s.peek()}`)
    for (let i = 1; i < A.length; i++) {
        let n = B[i]
        console.log(` c ${c}, n ${n}, s ${s}, A[i] ${A[i]}, `)
        if ( c === n ) {
            s.push(A[i])
            console.log(`same direction ${n}, so append ${A[i]}`)
        }
        else if (c !== n) {
            if (s.peek() > A[i]) {
                console.log(`I am fish size ${A[i]} eaten by ${s.peek()}`)
            }
            while (s.peek() < A[i]) {
                console.log(`${A[i]} eating  ${s.peek()}, so pop ${s.peek()}  `)
                s.pop()
            }
            if (s.length === 0) {
                s.push(A[i])
                c = n
                console.log(`last big fish ${A[i]} on direction ${n} `)

            }

        }
    }
    console.log('result : ', s)
    return s.length

}
</code>```

Logically Big fish should eat small fish when they meet in opposite direction.
If they are in same direction they will survive
Where I went wrong ?

```<code>fish([ 4, 3, 2, 1, 5], [ 1, 0, 1, 0, 1] ) // 3
fish([ 4, 3, 2, 0, 5], [ 0, 1, 0, 0, 0] ) // expected 2, but getting 4
fish([ 4, 3, 2, 1, 5], [ 0, 1, 0, 0, 0] ) // expected 2, but getting 4
fish([ 4, 3, 2, 1, 5], [ 0, 1, 1, 0, 0] ) // expected 2, but getting 3
fish([ 4, 3, 2, 5, 6], [ 1, 0, 1, 0, 1] ) // expected 2, but getting 1
fish([ 7, 4, 3, 2, 5, 6 ], [ 0, 1, 1, 1, 0, 1 ] ) // expected 3, but getting 7
fish([ 3, 4, 2, 1, 5 ], [ 1, 0, 0, 0, 0 ] ) // expected 4
fish([ 3 ], [ 1 ] ) // 1
fish([ 3 ], [ 0 ] ) // 1
</code>```

答:
https://app.codility.com/demo/results/trainingFHX89J-JQ9/</p>

```<code>

export const fish_count = (A = [4, 3, 2, 1, 5], B = [0, 1, 0, 0, 0]) => {

    console.log(` A ${A}, B ${B} `)

    const fish = (idx, siz, dir) => {  return { idx, siz, dir,
                print () {
                    return  ` ${this.siz} ${this.dir} `
                } } }

    const fishes = []

    for (let i = 0; i < A.length; i++) {
        let f = fish(i, A[i], B[i])
        fishes.push(f)
    }

    let f = fishes.shift()

    const survive = []
    survive.push(f)

    const print = () => {

        let str = survive.map((v) =>  v.print() ).join(' : ')
        return str

    }
    console.log(`${f.idx}, ${f.siz}, ${f.dir}`)

    const handle_move = (g) => {

        f = survive.peek()
        console.log(`${g.idx}, ${g.siz}, ${g.dir}, array ${print()}`)

        if (survive.length === 0) {
            console.log(` empty so append`)
            survive.push(g)
        }
        else if (f.dir === g.dir) {
            console.log(` same direction `)
            survive.push(g)
        }
        else if (f.dir === 0 && g.dir === 1) {
            console.log(` diamond direction, no eating `)
            survive.push(g)
        }
        else if (f.dir === 1 && g.dir === 0) {
            if (f.siz > g.siz) {
                console.log(` survive ${f.siz} > fishes ${g.siz}, so fishes ${g.print()} die`)
                // do not push. let g die
            }
            else if (f.siz < g.siz) {
                console.log(` survive ${f.siz} < fishes ${g.siz}, so survive ${f.print()} die`)
                survive.pop()
                return true // recursive
            }
        }

        return false
    }

    for ( let g of fishes) {
        while (handle_move(g)) {}
    }
    console.log(` array ${print()}`)

    console.log('result : ', survive.length)
    return survive.length

}

</code>```

Title: unable to understand codility fish

Body:
https://app.codility.com/demo/results/trainingAQH33G-WVS/

Array.prototype.peek = function() {
    return this[this.length-1]
}

export const fish = (A = [4, 3, 2, 1, 5], B = [0, 1, 0, 0, 0]) => {

    console.log(` A ${A}, B ${B} `)
    let c = B[0]
    let s = []
    s.push(A[0])
    console.log(`init c ${c}, n , s ${s}, A[0] ${A[0]}, `)
    console.log(`starting with ${s.peek()}`)
    for (let i = 1; i < A.length; i++) {
        let n = B[i]
        console.log(` c ${c}, n ${n}, s ${s}, A[i] ${A[i]}, `)
        if ( c === n ) {
            s.push(A[i])
            console.log(`same direction ${n}, so append ${A[i]}`)
        }
        else if (c !== n) {
            if (s.peek() > A[i]) {
                console.log(`I am fish size ${A[i]} eaten by ${s.peek()}`)
            }
            while (s.peek() < A[i]) {
                console.log(`${A[i]} eating  ${s.peek()}, so pop ${s.peek()}  `)
                s.pop()
            }
            if (s.length === 0) {
                s.push(A[i])
                c = n
                console.log(`last big fish ${A[i]} on direction ${n} `)

            }

        }
    }
    console.log('result : ', s)
    return s.length

}

Logically Big fish should eat small fish when they meet in opposite direction.
If they are in same direction they will survive
Where I went wrong ?

fish([ 4, 3, 2, 1, 5], [ 1, 0, 1, 0, 1] ) // 3
fish([ 4, 3, 2, 0, 5], [ 0, 1, 0, 0, 0] ) // expected 2, but getting 4
fish([ 4, 3, 2, 1, 5], [ 0, 1, 0, 0, 0] ) // expected 2, but getting 4
fish([ 4, 3, 2, 1, 5], [ 0, 1, 1, 0, 0] ) // expected 2, but getting 3
fish([ 4, 3, 2, 5, 6], [ 1, 0, 1, 0, 1] ) // expected 2, but getting 1
fish([ 7, 4, 3, 2, 5, 6 ], [ 0, 1, 1, 1, 0, 1 ] ) // expected 3, but getting 7
fish([ 3, 4, 2, 1, 5 ], [ 1, 0, 0, 0, 0 ] ) // expected 4
fish([ 3 ], [ 1 ] ) // 1
fish([ 3 ], [ 0 ] ) // 1

Body:
https://app.codility.com/demo/results/trainingFHX89J-JQ9/

export const fish_count = (A = [4, 3, 2, 1, 5], B = [0, 1, 0, 0, 0]) => {

    console.log(` A ${A}, B ${B} `)

    const fish = (idx, siz, dir) => {  return { idx, siz, dir,
                print () {
                    return  ` ${this.siz} ${this.dir} `
                } } }

    const fishes = []

    for (let i = 0; i < A.length; i++) {
        let f = fish(i, A[i], B[i])
        fishes.push(f)
    }

    let f = fishes.shift()

    const survive = []
    survive.push(f)

    const print = () => {

        let str = survive.map((v) =>  v.print() ).join(' : ')
        return str

    }
    console.log(`${f.idx}, ${f.siz}, ${f.dir}`)

    const handle_move = (g) => {

        f = survive.peek()
        console.log(`${g.idx}, ${g.siz}, ${g.dir}, array ${print()}`)

        if (survive.length === 0) {
            console.log(` empty so append`)
            survive.push(g)
        }
        else if (f.dir === g.dir) {
            console.log(` same direction `)
            survive.push(g)
        }
        else if (f.dir === 0 && g.dir === 1) {
            console.log(` diamond direction, no eating `)
            survive.push(g)
        }
        else if (f.dir === 1 && g.dir === 0) {
            if (f.siz > g.siz) {
                console.log(` survive ${f.siz} > fishes ${g.siz}, so fishes ${g.print()} die`)
                // do not push. let g die
            }
            else if (f.siz < g.siz) {
                console.log(` survive ${f.siz} < fishes ${g.siz}, so survive ${f.print()} die`)
                survive.pop()
                return true // recursive
            }
        }

        return false
    }

    for ( let g of fishes) {
        while (handle_move(g)) {}
    }
    console.log(` array ${print()}`)

    console.log('result : ', survive.length)
    return survive.length

}


问:
Send PdfByte Array from JS to php via Ajax and send an email with the php-File
i have following problem.

I use the pdf-lib libary for js to create a pdf. As last step i create an uint8array:

```<code>const pdfBytes = await pdfDoc.save()
</code>```

Now i want to send this pdfbytes with the help of ajax to a php.file on my web server.
This php-file should create an pdf out of the pdf byte array and attach this to an email and send it to an specific email-address.

I coded the ajax call like this:

```<code> function sendWithAjax(pdfBytes, email) {
        if (window.XMLHttpRequest) {
            // AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
                xmlhttp=new XMLHttpRequest();
            }
        else {
            // AJAX mit IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("POST", "sendContractEmail.php", true);
        const data = {bytes: pdfBytes, mail: email};
        xmlhttp.send(data);

    }
</code>```

But how can i code the php.file to generate the pdf and send it per email?

My php Code:

```<code><?php

if($_SERVER['REQUEST_METHOD'] == 'PUT') {
    echo "this is a put request\";
    parse_str(file_get_contents("php://input"),$post_vars);

    echo $post_vars['pdfBytes']." is pdfBytes\";

?>
</code>```

Thans for your help!

答:
I fought for the same problem for a week. In the end I got the result.

The first problem is to convert TypedArray Buffer (pdfBytes) to Base64

```<code>var data = new Uint8Array(pdfBytes);

var base64 = bufferToBase64(data); // cal function that convert TypedArray Buffer
</code>```

//console.log(base64); check output

```<code>var formData = new FormData();

   formData.append("name", name);
   formData.append("surname", surname);
   formData.append("email", email);
   formData.append("pdffile", base64);

   var request = new XMLHttpRequest();
   request.open("POST", "test.php");
   request.send(formData);
</code>```

send to php

```<code>    $first_name = $_POST['name']; // required
    $last_name = $_POST['surname']; // required
    $email_to = $_POST['email']; // required
    $binarr=$_POST['pdffile'];
    $email_from = 'sundsx@mailaddress.it';
    $extension = 'pdf';

    $FileName = str_replace("'", "_", $first_name);
    $FileSurName = str_replace("'", "_", $last_name);

    $filePath = $_SERVER['DOCUMENT_ROOT'].'/files/'.$FileName."_".$FileSurName.".".$extension;

    # Decode the Base64 string, making sure that it contains only valid characters
    $bin = base64_decode($binarr, true);
</code>```

check your $bin here base64guru

```<code>    if (strpos($bin, '%PDF') !== 0) {
    throw new Exception('Missing the PDF file signature');
    }

    # Write the PDF contents to a local file
    file_put_contents($filePath, $bin); // Goal!
</code>```

Enjoy the easy life

Body:
i have following problem.

I use the pdf-lib libary for js to create a pdf. As last step i create an uint8array:

const pdfBytes = await pdfDoc.save()

Now i want to send this pdfbytes with the help of ajax to a php.file on my web server.
This php-file should create an pdf out of the pdf byte array and attach this to an email and send it to an specific email-address.

I coded the ajax call like this:

 function sendWithAjax(pdfBytes, email) {
        if (window.XMLHttpRequest) {
            // AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
                xmlhttp=new XMLHttpRequest();
            }
        else {
            // AJAX mit IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("POST", "sendContractEmail.php", true);
        const data = {bytes: pdfBytes, mail: email};
        xmlhttp.send(data);

    }

But how can i code the php.file to generate the pdf and send it per email?

My php Code:

<?php

if($_SERVER['REQUEST_METHOD'] == 'PUT') {
    echo "this is a put request\";
    parse_str(file_get_contents("php://input"),$post_vars);

    echo $post_vars['pdfBytes']." is pdfBytes\";

?>

Thans for your help!

Body:
I fought for the same problem for a week. In the end I got the result.

The first problem is to convert TypedArray Buffer (pdfBytes) to Base64

var data = new Uint8Array(pdfBytes);

var base64 = bufferToBase64(data); // cal function that convert TypedArray Buffer

//console.log(base64); check output

var formData = new FormData();

   formData.append("name", name);
   formData.append("surname", surname);
   formData.append("email", email);
   formData.append("pdffile", base64);

   var request = new XMLHttpRequest();
   request.open("POST", "test.php");
   request.send(formData);

send to php

    $first_name = $_POST['name']; // required
    $last_name = $_POST['surname']; // required
    $email_to = $_POST['email']; // required
    $binarr=$_POST['pdffile'];
    $email_from = 'sundsx@mailaddress.it';
    $extension = 'pdf';

    $FileName = str_replace("'", "_", $first_name);
    $FileSurName = str_replace("'", "_", $last_name);

    $filePath = $_SERVER['DOCUMENT_ROOT'].'/files/'.$FileName."_".$FileSurName.".".$extension;

    # Decode the Base64 string, making sure that it contains only valid characters
    $bin = base64_decode($binarr, true);

check your $bin here base64guru

    if (strpos($bin, '%PDF') !== 0) {
    throw new Exception('Missing the PDF file signature');
    }

    # Write the PDF contents to a local file
    file_put_contents($filePath, $bin); // Goal!

Enjoy the easy life


问:
How to save base64 string as an image into a folder in C#?
I want to save a base64 string as an image into a folder on server and database using C#. But I am getting 'A generic error occurred in GDI+.' Can someone tell me what is wrong with this code?

My Controller:

```<code>    public ActionResult ShareProduct(Product item, PhotoProduct prphoto, string[] Photo)
    {
    foreach (string file in Photo)
            {
                if (file != null)
                {
                    string base64 = file.Substring(file.IndexOf(',') + 1);
                    base64 = base64.Trim('\0');
                    byte[] imageBytes = Convert.FromBase64String(base64);
                    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
                    {
                        Image image = Image.FromStream(ms, true);
                        string newPhoto = Guid.NewGuid().ToString() + ".png";
                        var path = Path.Combine(Server.MapPath("~/Uploads/"));
                        image.Save("~/Uploads/" + newPhoto);
                        prphoto.ImageName = "/Uploads/" + newPhoto;
                    }
                     }
                      }
</code>```

Debug result:

答:
I solved it by changing the code like below. But I'm not sure if it's safe. It works fine for now.</p>

```<code>   string base64 = file.Substring(file.IndexOf(',') + 1);
   base64 = base64.Trim('\0');
   string fileName = Guid.NewGuid().ToString() + ".Jpeg";
   byte[] imageBytes = Convert.FromBase64String(base64);
   MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
   ms.Write(imageBytes, 0, imageBytes.Length);
   System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
    image.Save(Server.MapPath("~/Uploads/"+fileName),
    System.Drawing.Imaging.ImageFormat.Png);
    prphoto.ImageName = "/Uploads/" + fileName;
</code>```

Body:
I want to save a base64 string as an image into a folder on server and database using C#. But I am getting 'A generic error occurred in GDI+.' Can someone tell me what is wrong with this code?

My Controller:

    public ActionResult ShareProduct(Product item, PhotoProduct prphoto, string[] Photo)
    {
    foreach (string file in Photo)
            {
                if (file != null)
                {
                    string base64 = file.Substring(file.IndexOf(',') + 1);
                    base64 = base64.Trim('\0');
                    byte[] imageBytes = Convert.FromBase64String(base64);
                    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
                    {
                        Image image = Image.FromStream(ms, true);
                        string newPhoto = Guid.NewGuid().ToString() + ".png";
                        var path = Path.Combine(Server.MapPath("~/Uploads/"));
                        image.Save("~/Uploads/" + newPhoto);
                        prphoto.ImageName = "/Uploads/" + newPhoto;
                    }
                     }
                      }

Debug result:

Body:
I solved it by changing the code like below. But I'm not sure if it's safe. It works fine for now.

   string base64 = file.Substring(file.IndexOf(',') + 1);
   base64 = base64.Trim('\0');
   string fileName = Guid.NewGuid().ToString() + ".Jpeg";
   byte[] imageBytes = Convert.FromBase64String(base64);
   MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
   ms.Write(imageBytes, 0, imageBytes.Length);
   System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
    image.Save(Server.MapPath("~/Uploads/"+fileName),
    System.Drawing.Imaging.ImageFormat.Png);
    prphoto.ImageName = "/Uploads/" + fileName;


问:
Matplotlib figure is not saving in a specific folder
I am trying to save matplotlib figure in r"C:\Users\USER\Handcrafted dataset\binary_image". but instead of saving figure in binary_image folder figure is saving in Handcrafted dataset  folder. And the image name is becoming binary_image0.png. But i want to save figure in my desired directory as i.png .How can i fix this?

```<code>di=r"C:\Users\USER\Handcrafted dataset\binary_image"
for i,img in enumerate(images):
    img = rgb2gray(img)
    plt.figure(figsize=(5,5))
    plt.imshow(img ,cmap='gray')
    plt.savefig(di+str(i)+".png")
</code>```

答:
You forgot a backslash:

```<code>plt.savefig(save_to + '\' + str(i) + '.png')
</code>```

Note: dir is a build-in function -- do not name your variable like that.

Body:
I am trying to save matplotlib figure in r"C:\Users\USER\Handcrafted dataset\binary_image". but instead of saving figure in binary_image folder figure is saving in Handcrafted dataset  folder. And the image name is becoming binary_image0.png. But i want to save figure in my desired directory as i.png .How can i fix this?

di=r"C:\Users\USER\Handcrafted dataset\binary_image"
for i,img in enumerate(images):
    img = rgb2gray(img)
    plt.figure(figsize=(5,5))
    plt.imshow(img ,cmap='gray')
    plt.savefig(di+str(i)+".png")

Body:
You forgot a backslash:

plt.savefig(save_to + '\' + str(i) + '.png')

Note: dir is a build-in function -- do not name your variable like that.


问:
Is it possible to rename an index using a rails migration?
I know that there is a rename_column transformation, but it seems that rename_index does not exist.

Do I have to use remove_index and add_index instead?

答:
You can execute arbitrary SQL in your migrations as well.

We have some helper methods that add foreign keys to our tables:

```<code>def add_foreign_key(from_table, from_column, to_table)
  constraint_name = "fk_#{from_table}_#{from_column}"

  execute %{alter table #{from_table}
            add constraint #{constraint_name}
            foreign key (#{from_column})
            references #{to_table}(id)
           }
  end
</code>```

You can use any SQL your database supports.

OwnerDisplayName: hectorsq

ContentLicense: CC BY-SA 2.5

Body:
You can execute arbitrary SQL in your migrations as well.

We have some helper methods that add foreign keys to our tables:

def add_foreign_key(from_table, from_column, to_table)
  constraint_name = "fk_#{from_table}_#{from_column}"

  execute %{alter table #{from_table}
            add constraint #{constraint_name}
            foreign key (#{from_column})
            references #{to_table}(id)
           }
  end

You can use any SQL your database supports.

OwnerDisplayName: Toby Hede


问:
Is there a way to lazy load components, not modules, in Angular?
Lazy loading is a commonly used technique. However, in Angular it seems that the granularity level of this technique stops at the module level.

That means that you can have module main that loads in the browser, and then on special occasion module B and C and D can be loaded lazily.

Almost all tutorials on web explain that. However, is there a way to load components lazily?

Consider this simple example that user goes inside the application, and when clicks "invoices" link, URL changes to the new route /invoice/list and a progress bar shows loading, while the invoices component including HTML and JS is being loaded inside the browser, is registered dynamically with the main module, and is being shown in the relevant outlet. Is that possible with Angular?

答:
Update, with Angular 9 and Ivy it is possible and relatively easy.
First of all you need to have some anchor in your app where you want to load your component, it could be named templateRef if you want multiple different components at the same time or ng-template for single one. To do that (i will use ng-template) in your component.html:

```<code><ng-template>
</code>```

component.ts:

```<code>export class ExampleComponent {
    @ViewChild(TemplateRef, { read: ViewContainerRef })
    private anchorRef: ViewContainerRef;

    constructor(
        private readonly componentFactoryResolver: ComponentFactoryResolver
    ) {}

    private async loadComponent() {
        this.anchorRef.clear(); // clear if some components are already there
        const { component } = await import(
            'path to your component'
        );
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
            component
        );
        // We could attach @Input and react to @Output by using below instance if needed.
        // Remember we should handle the ngOnChanges lifecycle hook.
        // For that implementation needed.
        this.anchorRef.createComponent(componentFactory);
    }
}
</code>```

All that is left is basically call loadComponent when it's needed;

If you need some modules, for ex you want to use Angular Material. You need to create simple ngModule without export inside your lazyLoaded component. Like this:

```<code>@Component({...})
export class Component implements OnInit {
    constructor() {}

    ngOnInit() {}
}

@NgModule({
    declarations: [Component],
    imports: [MatIconModule],
})
class TasksListModule {}
</code>```

Also, you could follow the approach Angular team has in their documentation:
https://angular.io/guide/dynamic-component-loader

Body:
Update, with Angular 9 and Ivy it is possible and relatively easy.
First of all you need to have some anchor in your app where you want to load your component, it could be named templateRef if you want multiple different components at the same time or ng-template for single one. To do that (i will use ng-template) in your component.html:

<ng-template>

component.ts:

export class ExampleComponent {
    @ViewChild(TemplateRef, { read: ViewContainerRef })
    private anchorRef: ViewContainerRef;

    constructor(
        private readonly componentFactoryResolver: ComponentFactoryResolver
    ) {}

    private async loadComponent() {
        this.anchorRef.clear(); // clear if some components are already there
        const { component } = await import(
            'path to your component'
        );
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
            component
        );
        // We could attach @Input and react to @Output by using below instance if needed.
        // Remember we should handle the ngOnChanges lifecycle hook.
        // For that implementation needed.
        this.anchorRef.createComponent(componentFactory);
    }
}

All that is left is basically call loadComponent when it's needed;

If you need some modules, for ex you want to use Angular Material. You need to create simple ngModule without export inside your lazyLoaded component. Like this:

@Component({...})
export class Component implements OnInit {
    constructor() {}

    ngOnInit() {}
}

@NgModule({
    declarations: [Component],
    imports: [MatIconModule],
})
class TasksListModule {}

Also, you could follow the approach Angular team has in their documentation:
https://angular.io/guide/dynamic-component-loader


问:
How to efficiently assign to a slice of a tensor in TensorFlow
I want to assign some values to slices of an input tensor in one of my model in TensorFlow 2.x (I am using 2.2 but ready to accept a solution for 2.1).
A non-working template of what I am trying to do is:

import tensorflow as tf
from tensorflow.keras.models import Model

class AddToEven(Model):
    def call(self, inputs):
        outputs = inputs
        outputs[:, ::2] += inputs[:, ::2]
        return outputs
```

<p>of course when building this (<code>AddToEven().build(tf.TensorShape([None, None]))</code>) I get the following error:</p>

```TypeError: 'Tensor' object does not support item assignment
```

<p>I can achieve this simple example via the following:</p>

<pre class="lang-py prettyprint-override"><code>class AddToEvenScatter(Model):
    def call(self, inputs):
        batch_size = tf.shape(inputs)[0]
        n = tf.shape(inputs)[-1]
        update_indices = tf.range(0, n, delta=2)[:, None]
        scatter_nd_perm = [1, 0]
        inputs_reshaped = tf.transpose(inputs, scatter_nd_perm)
        outputs = tf.tensor_scatter_nd_add(
            inputs_reshaped,
            indices=update_indices,
            updates=inputs_reshaped[::2],
        )
        outputs = tf.transpose(outputs, scatter_nd_perm)
        return outputs
</code>```

(you can sanity-check with:

model = AddToEvenScatter()
model.build(tf.TensorShape([None, None]))
model(tf.ones([1, 10]))
```

)

But as you can see it's very complicated to write. And this is only for a static number of updates (here 1) on a 1D (+ batch size) tensor.

What I want to do is a bit more involved and I think writing it with tensor_scatter_nd_add is going to be a nightmare.

A lot of the current QAs on the topic cover the case for variables but not tensors (see e.g. this or this).
It is mentionned here that indeed pytorch supports this, so I am surprised to see no response from any tf members on that topic recently.
This answer doesn't really help me, because I will need some kind of mask generation which is going to be awful as well.

The question is thus: how can I do slice assignment efficiently (computation-wise, memory-wise and code-wise) w/o tensor_scatter_nd_add? The trick is that I want this to be as dynamical as possible, meaning that the shape of the inputs could be variable.

(For anyone curious I am trying to translate this code in tf).

This question was originally posted in a GitHub issue.

答:
It seem to produce no errors with this:</p>
```<code>import tensorflow as tf
from tensorflow.keras.models import Model

class AddToEven(Model):
    def call(self, inputs):
        outputs = inputs
        outputs = outputs[:, ::2] + 1
        return outputs

# tf.Tensor.__iadd__ does not seem to exist, but tf.Tensor.__add__ does.
</code>```

Body:
I want to assign some values to slices of an input tensor in one of my model in TensorFlow 2.x (I am using 2.2 but ready to accept a solution for 2.1).
A non-working template of what I am trying to do is:

import tensorflow as tf
from tensorflow.keras.models import Model

class AddToEven(Model):
    def call(self, inputs):
        outputs = inputs
        outputs[:, ::2] += inputs[:, ::2]
        return outputs

of course when building this (AddToEven().build(tf.TensorShape([None, None]))) I get the following error:

TypeError: 'Tensor' object does not support item assignment

I can achieve this simple example via the following:

class AddToEvenScatter(Model):
    def call(self, inputs):
        batch_size = tf.shape(inputs)[0]
        n = tf.shape(inputs)[-1]
        update_indices = tf.range(0, n, delta=2)[:, None]
        scatter_nd_perm = [1, 0]
        inputs_reshaped = tf.transpose(inputs, scatter_nd_perm)
        outputs = tf.tensor_scatter_nd_add(
            inputs_reshaped,
            indices=update_indices,
            updates=inputs_reshaped[::2],
        )
        outputs = tf.transpose(outputs, scatter_nd_perm)
        return outputs

(you can sanity-check with:

model = AddToEvenScatter()
model.build(tf.TensorShape([None, None]))
model(tf.ones([1, 10]))

)

But as you can see it's very complicated to write. And this is only for a static number of updates (here 1) on a 1D (+ batch size) tensor.

What I want to do is a bit more involved and I think writing it with tensor_scatter_nd_add is going to be a nightmare.

A lot of the current QAs on the topic cover the case for variables but not tensors (see e.g. this or this).
It is mentionned here that indeed pytorch supports this, so I am surprised to see no response from any tf members on that topic recently.
This answer doesn't really help me, because I will need some kind of mask generation which is going to be awful as well.

The question is thus: how can I do slice assignment efficiently (computation-wise, memory-wise and code-wise) w/o tensor_scatter_nd_add? The trick is that I want this to be as dynamical as possible, meaning that the shape of the inputs could be variable.

(For anyone curious I am trying to translate this code in tf).

This question was originally posted in a GitHub issue.

Body:
It seem to produce no errors with this:

import tensorflow as tf
from tensorflow.keras.models import Model

class AddToEven(Model):
    def call(self, inputs):
        outputs = inputs
        outputs = outputs[:, ::2] + 1
        return outputs

# tf.Tensor.__iadd__ does not seem to exist, but tf.Tensor.__add__ does.


问:
How to make that bottomSheet not to cover or I can get height of BottomSheet?
I want to use BottomSheet as Footer but BottomSheet hide other container from body?

I think about 2 ways.

First way, Getting height of the BottomSheet and calculate

```<code>...
     return Container(
      height: MediaQuery.of(context).size.height - bottomSheetSize
      children: [
      Expanded(
          child: Container(
            color: Colors.white,
            child: listView,
        )
      ),
...
</code>```

or second way, the BottomSheet doesn't cover a body

I don't know how to get size of the BottomSheet or not to cover body.

Can you help me with one of option?

答: You cannot do anything in the current screen if you open bottom sheets. If you are making a footer type of thing, use another container at the bottom of the first container wrapped in a column or use Stack and stack the footer on top of the first container.</p>

Body:
I want to use BottomSheet as Footer but BottomSheet hide other container from body?

I think about 2 ways.

First way, Getting height of the BottomSheet and calculate

...
     return Container(
      height: MediaQuery.of(context).size.height - bottomSheetSize
      children: [
      Expanded(
          child: Container(
            color: Colors.white,
            child: listView,
        )
      ),
...

or second way, the BottomSheet doesn't cover a body

I don't know how to get size of the BottomSheet or not to cover body.

Can you help me with one of option?


问:
How to insert an integer at specific index in a file using Jupyter-Notebook/python?
[]
The Image is the perfect display of my problem.

I have a .txt file. containing the alphabet: a b c d e f g h i ...

I want to insert a number with each letter, so the updated file look like this:

a1 b2 c3 d4 e5 f6 and so on.

How can I do this in Python?

Note: Also, how to do the same when the letters are in a column, not a row?

答:
this is another solution based on your modified question.

you can write the output on the file

```<code>with open('s.txt') as s:
    alphabet = s.readlines()
    i = 1
    for l in alphabet:
        res = l.split()
        print(res[0], " ", (res[1] + str(i)))
        i = i+1
</code>```

Output on the console

```<code>A   a1
B   b2
C   c3
D   d4
E   e5
F   f6
G   g7
H   h8
I   i9
J   j10
</code>```

Body:
this is another solution based on your modified question.

you can write the output on the file

with open('s.txt') as s:
    alphabet = s.readlines()
    i = 1
    for l in alphabet:
        res = l.split()
        print(res[0], " ", (res[1] + str(i)))
        i = i+1

Output on the console

A   a1
B   b2
C   c3
D   d4
E   e5
F   f6
G   g7
H   h8
I   i9
J   j10