问:
How to import zip file from batch importation in Windows?
i'm trying to import a zip file in windows by batch import dspace in prompt but the windows is not recognizing the DIR from file:

Apparently it is outputting twice the file path: How i can solve this?

C:\dspace5\bin>dspace import -a -e admin -c capes/218424 -s C:\Users\admins\Desktop\projects\community\migration\bitstreams   -z SimpleArchiveFormat.zip  -m mapfilesCOM

```<code>Using DSpace installation in: C:\dspace5
Destination collections:
Owning  Collection: materials
java.io.FileNotFoundException: C:\Users\admins\Desktop\projects\community\migration\bitstreams\C:\Users\admins\Desktop\projects\community\migration\bitstreams\SimpleArchiveFormat.zip (The syntax of the file name, directory name, or volume label is incorrect)
        at java.util.zip.ZipFile.open(Native Method)
        at java.util.zip.ZipFile.<init>(Unknown Source)
        at java.util.zip.ZipFile.<init>(Unknown Source)
        at java.util.zip.ZipFile.<init>(Unknown Source)
        at org.dspace.app.itemimport.ItemImport.unzip(ItemImport.java:2021)
        at org.dspace.app.itemimport.ItemImport.unzip(ItemImport.java:1987)
        at org.dspace.app.itemimport.ItemImport.unzip(ItemImport.java:2098)
        at org.dspace.app.itemimport.ItemImport.main(ItemImport.java:490)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.dspace.app.launcher.ScriptLauncher.runOneCommand(ScriptLauncher.java:226)
        at org.dspace.app.launcher.ScriptLauncher.main(ScriptLauncher.java:78)
java.io.FileNotFoundException: C:\Users\admins\Desktop\projects\community\migration\bitstreams\C:\Users\admins\Desktop\projects\community\migration\bitstreams\SimpleArchiveFormat.zip (The syntax of the file name, directory name, or volume label is incorrect)

Deleting temporary zip directory: /dspace5/imports
Started: 1512488260816
Ended: 1512488268886

Elapsed time: 8 secs (8070 msecs)
</code>```

答:
I believe your problem is this known (and fixed) bug in some versions of DSpace: https://jira.duraspace.org/browse/DS-3585

You should either upgrade to a more recent version or reproduce the fix that is described in the issue and in DSpace's Git.

Good luck !

Body:
i'm trying to import a zip file in windows by batch import dspace in prompt but the windows is not recognizing the DIR from file:

Apparently it is outputting twice the file path: How i can solve this?

C:\dspace5\bin>dspace import -a -e admin -c capes/218424 -s C:\Users\admins\Desktop\projects\community\migration\bitstreams   -z SimpleArchiveFormat.zip  -m mapfilesCOM

Using DSpace installation in: C:\dspace5
Destination collections:
Owning  Collection: materials
java.io.FileNotFoundException: C:\Users\admins\Desktop\projects\community\migration\bitstreams\C:\Users\admins\Desktop\projects\community\migration\bitstreams\SimpleArchiveFormat.zip (The syntax of the file name, directory name, or volume label is incorrect)
        at java.util.zip.ZipFile.open(Native Method)
        at java.util.zip.ZipFile.<init>(Unknown Source)
        at java.util.zip.ZipFile.<init>(Unknown Source)
        at java.util.zip.ZipFile.<init>(Unknown Source)
        at org.dspace.app.itemimport.ItemImport.unzip(ItemImport.java:2021)
        at org.dspace.app.itemimport.ItemImport.unzip(ItemImport.java:1987)
        at org.dspace.app.itemimport.ItemImport.unzip(ItemImport.java:2098)
        at org.dspace.app.itemimport.ItemImport.main(ItemImport.java:490)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.dspace.app.launcher.ScriptLauncher.runOneCommand(ScriptLauncher.java:226)
        at org.dspace.app.launcher.ScriptLauncher.main(ScriptLauncher.java:78)
java.io.FileNotFoundException: C:\Users\admins\Desktop\projects\community\migration\bitstreams\C:\Users\admins\Desktop\projects\community\migration\bitstreams\SimpleArchiveFormat.zip (The syntax of the file name, directory name, or volume label is incorrect)

Deleting temporary zip directory: /dspace5/imports
Started: 1512488260816
Ended: 1512488268886

Elapsed time: 8 secs (8070 msecs)


来源: stackexchange

问:
Making a local scope inside a for loop, into a global scope
I have been searching but I cant get a clear answer. (I am a beginner in javascript and this is a test/practice inside the console) How can I make a local scope within a for loop, a global scope so I can then add it to variable with an array of objects. For Example :
I want the user to set how many stars(rating) a movie has inside a variable(prompt) named "stars". Then be able to call it inside the movieDb variable inside the object/array where it says "rating :" ... using the variable stars so it can console log the stars the user inputs along with the other information. Is this allowed or is there a different approach? </p>

```<code> var movieDb =[
  {
    haswatched : "i",
    title : "In Burges",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : stars,
  },
]

for (var i = 0; i < movieDb.length ; i++) {
  var w = prompt("did you watch the movie?")
  if (w === 'yes'){//first IF
    movieDb[i].haswatched = "you have watched";
    var r = prompt("would you like to rate us?");
        if (r === "yes") {//nested in first IF
            var stars = prompt("Enters Stars");
            alert("Thanks for rating & Watching!")
        } else if(r === "no"){ //nested in second IF
            alert("You did not rate, Thanks for watching!")
        }
  }
  else if (w === "no"){ //first ELSE IF
    movieDb[i].haswatched = "you have not seen";
  }
console.log(movieDb[i].haswatched + " " + "\""+movieDb[i].title+"\"" + " -" + movieDb[i].rating);
}'
</code>```

答:
I think if I understand what you are trying to achieve, this should help ...

```<code>var movieDb = [
    {
    haswatched : "i",
    title : "In Burges",
    rating : 0,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : 0,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : 0,
  },
];

for (var i = 0; i < movieDb.length ; i++) {
   var w = prompt("did you watch the movie " + movieDb[i].title + "?")
   if (w === 'yes'){//first IF
      movieDb[i].haswatched = "you have watched";
      var r = prompt("would you like to rate us?");
      if (r === "yes") {//nested in first IF
          var stars = prompt("Enters Stars");
          movieDb[i].rating = stars;
          alert("Thanks for rating & Watching!")
      } else if(r === "no"){ //nested in second IF
          alert("You did not rate, Thanks for watching!")
      }
   } else if (w === "no"){ //first ELSE IF
      movieDb[i].haswatched = "you have not seen";
   }
}

console.log(movieDb);
</code>```

https://jsfiddle.net/ramsmxms/

ContentLicense: CC BY-SA 3.0

Body:
I have been searching but I cant get a clear answer. (I am a beginner in javascript and this is a test/practice inside the console) How can I make a local scope within a for loop, a global scope so I can then add it to variable with an array of objects. For Example :
I want the user to set how many stars(rating) a movie has inside a variable(prompt) named "stars". Then be able to call it inside the movieDb variable inside the object/array where it says "rating :" ... using the variable stars so it can console log the stars the user inputs along with the other information. Is this allowed or is there a different approach?

 var movieDb =[
  {
    haswatched : "i",
    title : "In Burges",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : stars,
  },
]

for (var i = 0; i < movieDb.length ; i++) {
  var w = prompt("did you watch the movie?")
  if (w === 'yes'){//first IF
    movieDb[i].haswatched = "you have watched";
    var r = prompt("would you like to rate us?");
        if (r === "yes") {//nested in first IF
            var stars = prompt("Enters Stars");
            alert("Thanks for rating & Watching!")
        } else if(r === "no"){ //nested in second IF
            alert("You did not rate, Thanks for watching!")
        }
  }
  else if (w === "no"){ //first ELSE IF
    movieDb[i].haswatched = "you have not seen";
  }
console.log(movieDb[i].haswatched + " " + "\""+movieDb[i].title+"\"" + " -" + movieDb[i].rating);
}'

Body:
I think if I understand what you are trying to achieve, this should help ...

var movieDb = [
    {
    haswatched : "i",
    title : "In Burges",
    rating : 0,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : 0,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : 0,
  },
];

for (var i = 0; i < movieDb.length ; i++) {
   var w = prompt("did you watch the movie " + movieDb[i].title + "?")
   if (w === 'yes'){//first IF
      movieDb[i].haswatched = "you have watched";
      var r = prompt("would you like to rate us?");
      if (r === "yes") {//nested in first IF
          var stars = prompt("Enters Stars");
          movieDb[i].rating = stars;
          alert("Thanks for rating & Watching!")
      } else if(r === "no"){ //nested in second IF
          alert("You did not rate, Thanks for watching!")
      }
   } else if (w === "no"){ //first ELSE IF
      movieDb[i].haswatched = "you have not seen";
   }
}

console.log(movieDb);

https://jsfiddle.net/ramsmxms/


问:
How to copy (and rename) a database?
I am coding in Delphi, using a TADOConnection to access ODBC compliant databases.

How do I copy a database leaving the new copy on the same database server?

And how do I rename? (I suppose I could copy & delete the original - if I knew how to copy).

答:
ODBC does not provide for the copying or creating databases. That is a technology-specific (specific to the RDBMS) facility. The closest you can get is by creating and populating (copying) tables.

The only way you could do it would be to issue a db-specific command via an ODBC connection but for that we would have to know exactly what type of database you're using.

ContentLicense: CC BY-SA 2.5

Title: How to copy (and rename) a database?


问:
string match all possible variable combinations and output new data frame containing 2 new variables: combination count and strings matched
Have a data frame as described here:

```<code>ID <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
String <- c('a', 'b', 'c', 'd', 'a', 'c', 'd', 'e', 'b', 'd', 'e', 'f')

id_data <- data.frame(ID, String)
</code>```

Which produces:

```<code>ID  String
1     a
1     b
1     c
1     d
2     a
2     c
2     d
2     e
3     b
3     d
3     e
3     f
</code>```

Trying to compare all possible ID combinations to find count of 'String' that matches by 'ID'.  Desired output is a data frame that includes four variables:

1) 'ID' variable indicating the variables tested

2)  'Count' variable indicating the number of strings matched for a given ID pair

2) 'Matched' variable containing strings that match for that particular variable combination, separated by commas.

3)  'Unmatched' variable containing strings that do not match for that particular ID combination (also comma separated).

Desired output:

```<code> ID  Count   Matched   Unmatched
1-2    3     a, c, d      e
1-3    2     b, d         a, e
2-3    2     d, e         a, c, f
</code>```

I've referenced the following, but haven't found a solution to fulfill the above:

Matching R Data Frames

combn solution

Duplicate and self ID combos can be included in the output.

答:
```<code>do.call(rbind,
        combn(
            x = unique(id_data$ID),
            m = 2,
            FUN = function(x) {
                temp = id_data[id_data$ID %in% x, ]
                temp2 = Reduce(intersect, split(temp$String, temp$ID))
                data.frame(
                    ID = paste(x, collapse = "-"),
                    Count = length(temp2),
                    Matched = toString(temp2),
                    Unmatched = toString(setdiff(temp$String, temp2)))
            },
            simplify = FALSE
        ))
#    ID Count Matched  Unmatched
# 1 1-2     3 a, c, d       b, e
# 2 1-3     2    b, d a, c, e, f
# 3 2-3     2    d, e a, c, b, f
</code>```

Body:
Have a data frame as described here:

ID <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
String <- c('a', 'b', 'c', 'd', 'a', 'c', 'd', 'e', 'b', 'd', 'e', 'f')

id_data <- data.frame(ID, String)

Which produces:

ID  String
1     a
1     b
1     c
1     d
2     a
2     c
2     d
2     e
3     b
3     d
3     e
3     f

Trying to compare all possible ID combinations to find count of 'String' that matches by 'ID'.  Desired output is a data frame that includes four variables:

1) 'ID' variable indicating the variables tested

2)  'Count' variable indicating the number of strings matched for a given ID pair

2) 'Matched' variable containing strings that match for that particular variable combination, separated by commas.

3)  'Unmatched' variable containing strings that do not match for that particular ID combination (also comma separated).

Desired output:

 ID  Count   Matched   Unmatched
1-2    3     a, c, d      e
1-3    2     b, d         a, e
2-3    2     d, e         a, c, f

I've referenced the following, but haven't found a solution to fulfill the above:

Matching R Data Frames

combn solution

Duplicate and self ID combos can be included in the output.


问:
CRYSTAL REPORT display duplicated record
i have write sql statement and execute it into sql studio it display result successful but to display it in crystal report record are duplicated </p>

```<code>    select debit , credit , supplier.name from sales,supplier where supplied.id = sales.suuplierid
</code>```

答:
Check the below link.It will filter all the duplicates.
https://www.itsupportguides.com/knowledge-base/crystal-reports/crystal-reports-filter-duplicates-by-field/</p>

Body:
i have write sql statement and execute it into sql studio it display result successful but to display it in crystal report record are duplicated

    select debit , credit , supplier.name from sales,supplier where supplied.id = sales.suuplierid


问:
Compute dissimilarity matrix for large data
I'm trying to compute a dissimilarity matrix based on a big data frame with both numerical and categorical features. When I run the daisy function from the cluster package I get the error message:

Error: cannot allocate vector of size X.

In my case X is about 800 GB. Any idea how I can deal with this problem? Additionally it would be also great if someone could help me to run the function in parallel cores. Below you can find the function that computes the dissimilarity matrix on the iris dataset:

```<code>require(cluster)
d <- daisy(iris)
</code>```

答:
I've had a similar issue before. Running daisy() on even 5k rows of my dataset took a really long time.

I ended up using the kmeans algorithm in the h2o package which parallelizes and 1-hot encodes categorical data. I would just make sure to center and scale your data (mean 0 w/ stdev = 1) before plugging it into h2o.kmeans. This is so that the clustering algorithm doesn't prioritize columns that have high nominal differences (since it's trying to minimize the distance calculation). I used the scale() function.

After installing h2o:

```<code>h2o.init(nthreads = 16, min_mem_size = '150G')
h2o.df <- as.h2o(df)
h2o_kmeans <- h2o.kmeans(training_frame = h2o.df, x = vars, k = 5, estimate_k = FALSE, seed = 1234)
summary(h2o_kmeans)
</code>```

Body:
I'm trying to compute a dissimilarity matrix based on a big data frame with both numerical and categorical features. When I run the daisy function from the cluster package I get the error message:

Error: cannot allocate vector of size X.

In my case X is about 800 GB. Any idea how I can deal with this problem? Additionally it would be also great if someone could help me to run the function in parallel cores. Below you can find the function that computes the dissimilarity matrix on the iris dataset:

require(cluster)
d <- daisy(iris)

Body:
I've had a similar issue before. Running daisy() on even 5k rows of my dataset took a really long time.

I ended up using the kmeans algorithm in the h2o package which parallelizes and 1-hot encodes categorical data. I would just make sure to center and scale your data (mean 0 w/ stdev = 1) before plugging it into h2o.kmeans. This is so that the clustering algorithm doesn't prioritize columns that have high nominal differences (since it's trying to minimize the distance calculation). I used the scale() function.

After installing h2o:

h2o.init(nthreads = 16, min_mem_size = '150G')
h2o.df <- as.h2o(df)
h2o_kmeans <- h2o.kmeans(training_frame = h2o.df, x = vars, k = 5, estimate_k = FALSE, seed = 1234)
summary(h2o_kmeans)


问:
Plot a line along a constant latitude in Basemap, Python when using a conic projection
I would like to draw a line connecting two points of equal latitude on a basemap instance, using a conical map projection (i.e. where latitudes are not straight lines).

Irrespective of whether I use m.drawgreatcircle or m.plot, the resulting line is a straight (-I think...?) line between the two points, as opposed to a line that goes along a constant latitude. Does anybody know how to solve this problem? Some example code and the resulting image is below. I would dearly love that yellow dashed line to run along the 55N line.

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

#set up the map
m = Basemap(resolution='l',area_thresh=1000.,projection='lcc',\
        lat_1=50.,lat_2=60,lat_0=57.5,lon_0=-92.5,\
        width=6000000,height=4500000)

#add some basic map features
m.drawmeridians(np.arange(-155,-5,10),\
       labels=[0,0,0,1],fontsize=8,linewidth=0.5)
m.drawparallels(np.arange(30,85,5),\
       labels=[1,0,0,0],fontsize=8,linewidth=0.5)
m.drawcoastlines(linewidth=0.5)
m.drawcountries(linewidth=1)
m.drawstates(linewidth=0.3)

#plot some topography data
m.etopo()

#draw a line between two points of the same latitude
m.drawgreatcircle(-120,55,-65,55,linewidth=1.5,\
       color='yellow',linestyle='--')
</code>```

Apologies if I am missing something extremely simple...!

答:
drawgreatcicle is apparently not working correctly on a lcc projection map.

You can always just create a line yourself instead of relying on this helper function. To this end, create coordinates along the line, project them and call plot.

```<code>lon = np.linspace(-120,-65)
lat = np.linspace(55,55)
x,y = m(lon,lat)
m.plot(x,y, linewidth=1.5, color='yellow',linestyle='--')
</code>```

Body:
I would like to draw a line connecting two points of equal latitude on a basemap instance, using a conical map projection (i.e. where latitudes are not straight lines).

Irrespective of whether I use m.drawgreatcircle or m.plot, the resulting line is a straight (-I think...?) line between the two points, as opposed to a line that goes along a constant latitude. Does anybody know how to solve this problem? Some example code and the resulting image is below. I would dearly love that yellow dashed line to run along the 55N line.

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

#set up the map
m = Basemap(resolution='l',area_thresh=1000.,projection='lcc',\
        lat_1=50.,lat_2=60,lat_0=57.5,lon_0=-92.5,\
        width=6000000,height=4500000)

#add some basic map features
m.drawmeridians(np.arange(-155,-5,10),\
       labels=[0,0,0,1],fontsize=8,linewidth=0.5)
m.drawparallels(np.arange(30,85,5),\
       labels=[1,0,0,0],fontsize=8,linewidth=0.5)
m.drawcoastlines(linewidth=0.5)
m.drawcountries(linewidth=1)
m.drawstates(linewidth=0.3)

#plot some topography data
m.etopo()

#draw a line between two points of the same latitude
m.drawgreatcircle(-120,55,-65,55,linewidth=1.5,\
       color='yellow',linestyle='--')

Apologies if I am missing something extremely simple...!

Body:
drawgreatcicle is apparently not working correctly on a lcc projection map.

You can always just create a line yourself instead of relying on this helper function. To this end, create coordinates along the line, project them and call plot.

lon = np.linspace(-120,-65)
lat = np.linspace(55,55)
x,y = m(lon,lat)
m.plot(x,y, linewidth=1.5, color='yellow',linestyle='--')


问:
Java ArrayDeque instantiation from existing Collection vs Iteration
I am trying to evaluate two of creating an ArrayDeque with existing collection.. I see two options :

Using ArrayDeque's constructor which accepts an existing Collection

Iterate over the Collection and call dequeu.offer(element) while iterating over Collection

From my benchmarks I see first option running faster than second. Is there any reason for the first option to be better than second ?

答:
On the first option.

```<code>public ArrayDeque(Collection<? extends E> c) {
    allocateElements(c.size());
    addAll(c);
}
</code>```

It allocates all the elements in one call (that is, it allocates an array with enough elements) and then just adds them one by one (without any additional allocations).

But when you use option 2, several allocations happen during this process when ArrayDeque grows (doubling itself); plus on each reallocation the elements are copied to the new array.

Just one allocation (for option 1) versus several allocations plus copying (for option 2) gives the difference.

For reference:

```<code>public boolean offerLast(E e) {
    addLast(e);
    return true;
}

public void addLast(E e) {
    if (e == null)
        throw new NullPointerException();
    elements[tail] = e;
    if ( (tail = (tail + 1) & (elements.length - 1)) == head)
        doubleCapacity();
}
</code>```

All code is from Java 8.

Body:
On the first option.

public ArrayDeque(Collection<? extends E> c) {
    allocateElements(c.size());
    addAll(c);
}

It allocates all the elements in one call (that is, it allocates an array with enough elements) and then just adds them one by one (without any additional allocations).

But when you use option 2, several allocations happen during this process when ArrayDeque grows (doubling itself); plus on each reallocation the elements are copied to the new array.

Just one allocation (for option 1) versus several allocations plus copying (for option 2) gives the difference.

For reference:

public boolean offerLast(E e) {
    addLast(e);
    return true;
}

public void addLast(E e) {
    if (e == null)
        throw new NullPointerException();
    elements[tail] = e;
    if ( (tail = (tail + 1) & (elements.length - 1)) == head)
        doubleCapacity();
}

All code is from Java 8.


问:
How to ensure that the /EDITANDCONTINUE directive is not ignored
I get this message when I try to edit and continue in VSC15:

```<code>'file.cpp' in 'LIB.DLL' was not linked with Edit and Continue enabled.
Ensure that /INCREMENTAL linking is enabled, and the /EDITANDCONTINUE directive is not ignored.
</code>```

I've already ensured that /INCREMENTAL is enabled but can't figure out the second part.

Compiler command line:

```<code>/Yu"stdfx.h" /GS /analyze- /W3 /Gy /Zc:wchar_t /ZI /Gm- /Od /Fd".\Debug\vc140.pdb" /Zc:inline /fp:fast /D "x86" /D "WIN32" /D "_WINDOWS" /D "DEBUG" /D "_UNICODE" /D "UNICODE" /D "_WINDLL" /errorReport:none /WX- /Zc:forScope /RTC1 /GR /Gd /Oy- /MTd /Fa".\Debug\" /EHsc /Fo".\Debug\" /Fp".\Debug\LIB.pch"
</code>```

Linker command line:

```<code>/OUT:".\Debug\LIB.dll" /MANIFEST:NO /NXCOMPAT /PDB:".\Debug\LIB.pdb" /DYNAMICBASE /DEF:"EXPORT.DEF" /IMPLIB:".\Debug\LIB.lib" /DLL /MACHINE:X86 /NODEFAULTLIB:"libc.lib" /OPT:REF /SAFESEH /INCREMENTAL /PGD:".\Debug\LIB.pgd" /SUBSYSTEM:WINDOWS /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /ManifestFile:".\Debug\LIB.dll.intermediate.manifest" /MAP /OPT:ICF
</code>```

答:
I had the same problem, did all steps described above but no luck.

I use VS2017.

Helped next: you have to specify /ZI for each specific *.cpp file in your project:

right click on the *.cpp file in the Solution Explorer

Properties > C/C++ > General > Debug Information Format = Program Database for Edit And Continue (/ZI)

Body:
I get this message when I try to edit and continue in VSC15:

'file.cpp' in 'LIB.DLL' was not linked with Edit and Continue enabled.
Ensure that /INCREMENTAL linking is enabled, and the /EDITANDCONTINUE directive is not ignored.

I've already ensured that /INCREMENTAL is enabled but can't figure out the second part.

Compiler command line:

/Yu"stdfx.h" /GS /analyze- /W3 /Gy /Zc:wchar_t /ZI /Gm- /Od /Fd".\Debug\vc140.pdb" /Zc:inline /fp:fast /D "x86" /D "WIN32" /D "_WINDOWS" /D "DEBUG" /D "_UNICODE" /D "UNICODE" /D "_WINDLL" /errorReport:none /WX- /Zc:forScope /RTC1 /GR /Gd /Oy- /MTd /Fa".\Debug\" /EHsc /Fo".\Debug\" /Fp".\Debug\LIB.pch"

Linker command line:

/OUT:".\Debug\LIB.dll" /MANIFEST:NO /NXCOMPAT /PDB:".\Debug\LIB.pdb" /DYNAMICBASE /DEF:"EXPORT.DEF" /IMPLIB:".\Debug\LIB.lib" /DLL /MACHINE:X86 /NODEFAULTLIB:"libc.lib" /OPT:REF /SAFESEH /INCREMENTAL /PGD:".\Debug\LIB.pgd" /SUBSYSTEM:WINDOWS /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /ManifestFile:".\Debug\LIB.dll.intermediate.manifest" /MAP /OPT:ICF


问:
What is the backing property for ngModel directive when you use it without the [()] syntax
Looking at an angular forms example that I'm editing I see one example that uses the ngModel keyword without assigning it to a backing property name.

```<code><input ngModel required type="password" class="form-control" name="password" id="password" placeholder="Password" >
</code>```

I normally see it with a binding bracket of [ngModel]="password" or [(ngModel)]="password"

If we use the plain ngModel directive of the first example without an assignment, what backing property is the input data bound to?  Is it not bound to anything and only accesible from form.values?  In what use case would you want to use the plain ngModel directive - when you don't need binding and only want to access it from the form values?

答:
A use case that comes to my mind is when you don't want to bind it to a field, but you want update your model when it changes, like

```<code><input ngModel (ngModelChange)="updateModel($event)"
</code>```

The following code would not work because ngModelChange is not a selector matching the NgModel directive

```<code><input (ngModelChange)="updateModel($event)"
</code>```

therefore you add a bar ngModel to get the NgModel directive applied and get ngModelChange events.

Body:
Looking at an angular forms example that I'm editing I see one example that uses the ngModel keyword without assigning it to a backing property name.

<input ngModel required type="password" class="form-control" name="password" id="password" placeholder="Password" >

I normally see it with a binding bracket of [ngModel]="password" or [(ngModel)]="password"

If we use the plain ngModel directive of the first example without an assignment, what backing property is the input data bound to?  Is it not bound to anything and only accesible from form.values?  In what use case would you want to use the plain ngModel directive - when you don't need binding and only want to access it from the form values?

Body:
A use case that comes to my mind is when you don't want to bind it to a field, but you want update your model when it changes, like

<input ngModel (ngModelChange)="updateModel($event)"

The following code would not work because ngModelChange is not a selector matching the NgModel directive

<input (ngModelChange)="updateModel($event)"

therefore you add a bar ngModel to get the NgModel directive applied and get ngModelChange events.


问:
how to rename files shared by some onedrive user with us, using microsoft graph apis
I have a written code to rename files of onedrive logged in user, using graph api with following call.

```<code>www.graph.microsoft.com/v1.0/me/drive/items/{FileOrFolderID}

with body:
{
"name":"newfilename.txt",
"@name.conflictBehavior": "rename"
}
</code>```

I'm not able rename the files which has been shared by some other onedrive user with me, which I can if done in browser. The other user has given me editable permissions.

I have tried following syntax to rename file shared with me, but it gives me access denied error.

```<code>www.graph.microsoft.com/v1.0/me/drives/{DriveId}/items/{FileOrFolderID}
</code>```

Can someone please answer what thing I am missing.

答:
A couple of things to try:

Make sure you're requesting Files.ReadWrite.All if you need to modify someone else's items

Try hitting https://graph.microsoft.com/v1.0/drives/{DriveId}/items/{FileOrFolderID}. Using "me" may work, but it's semantically weird.

If neither of those work please update your question to include the full response so we can debug further.

Body:
I have a written code to rename files of onedrive logged in user, using graph api with following call.

www.graph.microsoft.com/v1.0/me/drive/items/{FileOrFolderID}

with body:
{
"name":"newfilename.txt",
"@name.conflictBehavior": "rename"
}

I'm not able rename the files which has been shared by some other onedrive user with me, which I can if done in browser. The other user has given me editable permissions.

I have tried following syntax to rename file shared with me, but it gives me access denied error.

www.graph.microsoft.com/v1.0/me/drives/{DriveId}/items/{FileOrFolderID}

Can someone please answer what thing I am missing.


答: Creating new ArrayDeque with constructor and in way to iterate through Collection and add each element by one is similar. Because in constructor of this class used iteration through all collection.</p>

Title: Java ArrayDeque instantiation from existing Collection vs Iteration

Body:
I am trying to evaluate two of creating an ArrayDeque with existing collection.. I see two options :

Using ArrayDeque's constructor which accepts an existing Collection

Iterate over the Collection and call dequeu.offer(element) while iterating over Collection

From my benchmarks I see first option running faster than second. Is there any reason for the first option to be better than second ?


问:
Optimizing JOINED results with Order By clause
Consider following schema (available on sqlFiddle)

```<code>create table ad (
  id int primary key auto_increment,
  category_id int,
  city_id int,
  name varchar(255),
  key(category_id),
  key(city_id)
);

create table category (
  id int primary key auto_increment,
  name varchar(255)
);

create table city (
  id int primary key auto_increment,
  name varchar(255)
);

insert into category values (null, 'Category 1');
insert into category values (null, 'Category 2');
insert into category values (null, 'Category 3');

insert into city values (null, 'City 1');
insert into city values (null, 'City 2');

insert into ad values (null, 1, 1, "Category 1 city 1");
insert into ad values (null, 1, 2, "Category 1 city 2");
insert into ad values (null, 2, 1, "Category 2 city 1");
insert into ad values (null, 2, 2, "Category 2 city 2");
insert into ad values (null, 3, 1, "Category 3 city 1");
insert into ad values (null, 3, 2, "Category 3 city 2");
</code>```

When executing simple joined query without any order by:

```<code>SELECT ad.id, ad.name, category.name, city.name FROM ad
INNER JOIN category ON category.id = ad.category_id
INNER JOIN city ON city.id = ad.city_id
</code>```

the result is quite efficient:

However as soon as I add the ORDER BY clause, temporary table and file sort is involved:

```<code>SELECT ad.id, ad.name, category.name, city.name FROM ad
INNER JOIN category ON category.id = ad.category_id
INNER JOIN city ON city.id = ad.city_id
ORDER BY ad.id
</code>```

How to optimize such query?

答:
I managed to find a solution by myself. First of all, one needs to efficiently calculate required ID's from the main table (having them filtered and sorted), then simply again join the results against that keys inside inner query:

```<code>SELECT ad.id, ad.name, category.name, city.name FROM
    (
        SELECT id FROM ad WHERE price <= 3000 ORDER BY id DESC
    ) AS v
JOIN ad ON v.id = ad.id
JOIN category ON category.id = ad.category_id
JOIN city ON city.id = ad.city_id
</code>```

There're of course more columns involved in my case. With such query (having 60k records in the main table) the execution speed has increased from 0.16s to 0.004s, as long as I order by an indexed column(s).

Body:
Consider following schema (available on sqlFiddle)

create table ad (
  id int primary key auto_increment,
  category_id int,
  city_id int,
  name varchar(255),
  key(category_id),
  key(city_id)
);

create table category (
  id int primary key auto_increment,
  name varchar(255)
);

create table city (
  id int primary key auto_increment,
  name varchar(255)
);

insert into category values (null, 'Category 1');
insert into category values (null, 'Category 2');
insert into category values (null, 'Category 3');

insert into city values (null, 'City 1');
insert into city values (null, 'City 2');

insert into ad values (null, 1, 1, "Category 1 city 1");
insert into ad values (null, 1, 2, "Category 1 city 2");
insert into ad values (null, 2, 1, "Category 2 city 1");
insert into ad values (null, 2, 2, "Category 2 city 2");
insert into ad values (null, 3, 1, "Category 3 city 1");
insert into ad values (null, 3, 2, "Category 3 city 2");

When executing simple joined query without any order by:

SELECT ad.id, ad.name, category.name, city.name FROM ad
INNER JOIN category ON category.id = ad.category_id
INNER JOIN city ON city.id = ad.city_id

the result is quite efficient:

However as soon as I add the ORDER BY clause, temporary table and file sort is involved:

SELECT ad.id, ad.name, category.name, city.name FROM ad
INNER JOIN category ON category.id = ad.category_id
INNER JOIN city ON city.id = ad.city_id
ORDER BY ad.id

How to optimize such query?

Body:
I managed to find a solution by myself. First of all, one needs to efficiently calculate required ID's from the main table (having them filtered and sorted), then simply again join the results against that keys inside inner query:

SELECT ad.id, ad.name, category.name, city.name FROM
    (
        SELECT id FROM ad WHERE price <= 3000 ORDER BY id DESC
    ) AS v
JOIN ad ON v.id = ad.id
JOIN category ON category.id = ad.category_id
JOIN city ON city.id = ad.city_id

There're of course more columns involved in my case. With such query (having 60k records in the main table) the execution speed has increased from 0.16s to 0.004s, as long as I order by an indexed column(s).


问:
Calling `super()` in parent class
I'm reading Raymond Hettinger's Python’s super() considered super!  About a page in, there's this example:

```<code>class Shape:
    def __init__(self, shapename, **kwds):
        self.shapename = shapename
        super().__init__(**kwds)

class ColoredShape(Shape):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)

cs = ColoredShape(color='red', shapename='circle')
</code>```

Why is it necessary to call super() in Shape here?  My understanding is that this calls object.__init__(**kwds) since Shape implicitly inherits from object.

Even without that statement, we've already

established shapename already in the parent's __init__,

established the child class's color in an explicit method override,

then invoked the parent's __init__ with super() in ColoredShape.

As far as I can tell, dropping this line produces the same behavior & functionality:

```<code>class Shape:  # (object)
    def __init__(self, shapename, **kwds):
        self.shapename = shapename
        # super().__init__(**kwds)

class ColoredShape(Shape):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)
    def check(self):
        print(self.color)
        print(self.shapename)

cs = ColoredShape(color='red', shapename='circle')

cs.check()
# red
# circle
</code>```

What is the purpose of super() within Shape here?

答:
I see that @user2357112 has already provided a correct answer. I was working on an example that I'd though I'd leave here because it's pretty much what user2357112 is describing.  Consider a mixin class like this:

```<code>class PositionMixin:
    def __init__(self, x=0, y=0, **kwds):
        super().__init__(**kwds)
        self.x = x
        self.y = y
</code>```

Let's say you apply that to your ColoredShape class:

```<code>class ColoredShape(Shape, PositionMixin):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)
</code>```

If Shape doesn't call super.__init__, then when you do this:

```<code>myshape = ColoredShape('red', shapename='circle', x=1, y=1)
print(myshape.x, myshape.y)
</code>```

You get:

```<code>Traceback (most recent call last):
  File "supertest.py", line 18, in <module>
    print (myshape.x, myshape.y)
AttributeError: 'ColoredShape' object has no attribute 'x'
</code>```

The call to super.__init__ in shape is necessary to call the __init__ method on PositionMixin.

Title: Calling `super()` in parent class

Body:
I'm reading Raymond Hettinger's Python’s super() considered super!  About a page in, there's this example:

class Shape:
    def __init__(self, shapename, **kwds):
        self.shapename = shapename
        super().__init__(**kwds)

class ColoredShape(Shape):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)

cs = ColoredShape(color='red', shapename='circle')

Why is it necessary to call super() in Shape here?  My understanding is that this calls object.__init__(**kwds) since Shape implicitly inherits from object.

Even without that statement, we've already

established shapename already in the parent's __init__,

established the child class's color in an explicit method override,

then invoked the parent's __init__ with super() in ColoredShape.

As far as I can tell, dropping this line produces the same behavior & functionality:

class Shape:  # (object)
    def __init__(self, shapename, **kwds):
        self.shapename = shapename
        # super().__init__(**kwds)

class ColoredShape(Shape):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)
    def check(self):
        print(self.color)
        print(self.shapename)

cs = ColoredShape(color='red', shapename='circle')

cs.check()
# red
# circle

What is the purpose of super() within Shape here?

Body:
I see that @user2357112 has already provided a correct answer. I was working on an example that I'd though I'd leave here because it's pretty much what user2357112 is describing.  Consider a mixin class like this:

class PositionMixin:
    def __init__(self, x=0, y=0, **kwds):
        super().__init__(**kwds)
        self.x = x
        self.y = y

Let's say you apply that to your ColoredShape class:

class ColoredShape(Shape, PositionMixin):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)

If Shape doesn't call super.__init__, then when you do this:

myshape = ColoredShape('red', shapename='circle', x=1, y=1)
print(myshape.x, myshape.y)

You get:

Traceback (most recent call last):
  File "supertest.py", line 18, in <module>
    print (myshape.x, myshape.y)
AttributeError: 'ColoredShape' object has no attribute 'x'

The call to super.__init__ in shape is necessary to call the __init__ method on PositionMixin.


问:
Changing mvc form controller on submit
I recently came upon this question as I have a solution I need to work on.

I have a controller which does some logic, with some method:

```<code>   public Controller1: MvcController
   {
     public ActionResult SomeLogic(Model model)
     {
       return view();
     }
     public ActionResult SomeLogic2(Model model)
     {
       return view();
     }
  }
</code>```

And I have a second controller which does different logic:

```<code>   public Controller2: MvcController
   {
     public ActionResult SomeLogic(Model model)
     {
       return view();
     }
     public ActionResult SomeLogic2(Model model)
     {
       return view();
     }
  }
</code>```

Both are working on the same view:

```<code>MyView.cshtml
</code>```

The view contains a begin form that works on submit:

```<code>@using(Html.BeginForm("SomeLogic", "Controller1", FormMethod.Post)
</code>```

and 4 submit buttons:

```<code><input type='submit' formaction='SomeLogic' value='submit' />
<input type='submit' formaction='SomeLogic2' value='submit2' />
<input type='submit' formaction='SomeLogic' value='submit3' />
<input type='submit' formaction='SomeLogic2' value='submit4' />
</code>```

I know I can control the action to which I am redirecting the submit using the:
formaction attribute.

I there a way to change the controller as well? meaning that:

```<code><input type='submit' formaction='SomeLogic' value='submit3' />
<input type='submit' formaction='SomeLogic2' value='submit4' />
</code>```

Will submit to controller2 instead of Controller1 which is defined in my begin form.

This will solve my debate whether to create a new controller or use the existing one, which is already full of complex logic.

答:
Just intercept the submit with jQuery

You can add an ID to your form, to be able to select it easily in jQuery

```<code>@using(Html.BeginForm("SomeLogic", "Controller1", FormMethod.Post, new { @id = "yourForm" })
</code>```

Then

```<code>$("#yourForm").submit(function(e){
    e.preventDefault();

    var url1 = '@(Url.Action("SomeLogic1", "SomeController", null, Request.Url.Scheme))';
    var url2 = '@(Url.Action("SomeLogic", "SomeController2", null, Request.Url.Scheme))';

    //Whatever logic should you do to select which URL you want to POST to

    $.ajax({
        type: 'POST',
        url: url_selected_above,
        data: $('#yourForm').serializeArray(),
        success: function (xhr, response) {
             //...
        },
        error: function (xhr, response) {
            //...
        }
    });
});
</code>```

This should work if all the methods expect the same view model.

Alternatively, if you do not want to mess around in the UI, you can do something as such in the action that generates the form.

```<code>var controllerName = "SomeController";
var actionName = "Action1";

//do your logic to select whichever controller/action.

viewModel.ControllerName = controllerName;
viewModel.ActionName = actionName;
</code>```

And in the view that has the form:

```<code>@using(Html.BeginForm(@Model.ActionName, @Model.ControllerName, FormMethod.Post)
</code>```

Again, if all the actions expect the same view model, that should work.

Title: Changing mvc form controller on submit

Body:
I recently came upon this question as I have a solution I need to work on.

I have a controller which does some logic, with some method:

   public Controller1: MvcController
   {
     public ActionResult SomeLogic(Model model)
     {
       return view();
     }
     public ActionResult SomeLogic2(Model model)
     {
       return view();
     }
  }

And I have a second controller which does different logic:

   public Controller2: MvcController
   {
     public ActionResult SomeLogic(Model model)
     {
       return view();
     }
     public ActionResult SomeLogic2(Model model)
     {
       return view();
     }
  }

Both are working on the same view:

MyView.cshtml

The view contains a begin form that works on submit:

@using(Html.BeginForm("SomeLogic", "Controller1", FormMethod.Post)

and 4 submit buttons:

<input type='submit' formaction='SomeLogic' value='submit' />
<input type='submit' formaction='SomeLogic2' value='submit2' />
<input type='submit' formaction='SomeLogic' value='submit3' />
<input type='submit' formaction='SomeLogic2' value='submit4' />

I know I can control the action to which I am redirecting the submit using the:
formaction attribute.

I there a way to change the controller as well? meaning that:

<input type='submit' formaction='SomeLogic' value='submit3' />
<input type='submit' formaction='SomeLogic2' value='submit4' />

Will submit to controller2 instead of Controller1 which is defined in my begin form.

This will solve my debate whether to create a new controller or use the existing one, which is already full of complex logic.

Body:
Just intercept the submit with jQuery

You can add an ID to your form, to be able to select it easily in jQuery

@using(Html.BeginForm("SomeLogic", "Controller1", FormMethod.Post, new { @id = "yourForm" })

Then

$("#yourForm").submit(function(e){
    e.preventDefault();

    var url1 = '@(Url.Action("SomeLogic1", "SomeController", null, Request.Url.Scheme))';
    var url2 = '@(Url.Action("SomeLogic", "SomeController2", null, Request.Url.Scheme))';

    //Whatever logic should you do to select which URL you want to POST to

    $.ajax({
        type: 'POST',
        url: url_selected_above,
        data: $('#yourForm').serializeArray(),
        success: function (xhr, response) {
             //...
        },
        error: function (xhr, response) {
            //...
        }
    });
});

This should work if all the methods expect the same view model.

Alternatively, if you do not want to mess around in the UI, you can do something as such in the action that generates the form.

var controllerName = "SomeController";
var actionName = "Action1";

//do your logic to select whichever controller/action.

viewModel.ControllerName = controllerName;
viewModel.ActionName = actionName;

And in the view that has the form:

@using(Html.BeginForm(@Model.ActionName, @Model.ControllerName, FormMethod.Post)

Again, if all the actions expect the same view model, that should work.


问:
Using Go with fish fish shell - error when running `go install /path/to/src`
I am following the "How to Write Code" portion of the golang docs, here. I am also using fish fish shell.

I have followed the tutorial and set the proper environment variables (GOPATH and PATH) but I can't get the command go install github.com/user/hello to work with my installation.

I am getting an error:

can't load package: package github.com/user/hello: import
  "github.com/user/hello": cannot find package

答:
Even better than editing the config.fish file, run set command with --universal (to persist) and -x (export) in your shell like so:

```<code>set --universal -x GOPATH $HOME/path/to/goworkspace
</code>```

Body:
Even better than editing the config.fish file, run set command with --universal (to persist) and -x (export) in your shell like so:

set --universal -x GOPATH $HOME/path/to/goworkspace


问:
Feed_dict doesnt accept my data
I've been trying to be able to feed my own images in some tensorflow code to look how the code would react to my own images instead of the MNIST set. I've been able to import images(i think) into tensorflow but I have two placeholders that should get my image data and label data. I tried to use feed_dict(which still seems right to me) to be able to use my data in the rest of my code but it won't accept any data I feed it. I know I can't feed it a Tensor and apparently not a batch but the only way I can think of to make this work is to feed it a list. I saw feed_dict is able to use numpy arrays but im not sure how i should approach converting data to a numpy array.

I'm new to TensorFlow and python so please forgive any mistakes I made, I'm still learning how everything works.

```<code>with tf.name_scope('Image_Data_Input'):
  def read_labeled_image_list(image_list_file):
    print('read_labeled_image_list function opened')
    f = open(image_list_file, 'r')
    print('image_list_file opened')
    filenames = []
    labels = []
    print('Arrays formed')
    for line in f:
      filename, label = line[:-1].split(' ')
      filenames.append(filename)
      labels.append(label)
    print('Lines deconstructed')
    return filenames, labels

def read_image(input_queue):
    label = input_queue[1]
    file_contents = tf.read_file(input_queue[0])
    decoded_image = tf.image.decode_jpeg(file_contents, channels=3)
    print('Image decoded to JPEG')
    decoded_image.set_shape([2560, 1440, 3])
    decoded_image = tf.image.resize_images(decoded_image, [128, 128])
    return decoded_image, label

image_list, label_list = read_labeled_image_list(image_list_file)
images = tf.convert_to_tensor(image_list, dtype=tf.string)
labels = tf.convert_to_tensor(label_list, dtype=tf.string)

input_queue = tf.train.slice_input_producer([images, labels], num_epochs=None, shuffle=True)

image, label = read_image(input_queue)
</code>```

The indentation behaved a little weird when i pasted my code so I'm not sure everything is properly placed.

Well now I have these placeholder:

```<code>with tf.name_scope('input'):
  x = tf.placeholder(tf.float32, shape=[None, 784])
  y_ = tf.placeholder(tf.float32, shape=[None, 10])
</code>```

And I've seen the code routing data to those placeholder this way:

```<code>batch_x, batch_y = tf.train.batch([image, label], batchsize)
#_, summary = sess.run([train_writer, summary_op], feed_dict={x: batch_x, y_: batch_y})
</code>```

But I can't seem to make this work.

Does anyone have any idea how i could make this work?

Again sorry for any mistakes and thanks in advance.

答:
As the error says, you can't feed tensors into a placeholder. batch_x and batch_y are tensors. The new tf.Dataset API is the preferred way to input data into a model (guide here). I think Dataset.from_tensor_slices would require minimal rewriting. Short of that, build the graph so that batch_x and batch_y flow into the model you're using directly. Then you don't need to use placeholders.

I don't recommend this, but for completeness I want to mention another method. You could:

```<code>numpy_batch_x, numpy_batch_y = sess.run([batch_x, batch_y])
_, summary = sess.run([train_writer, summary_op],
    feed_dict={x: numpy_batch_x, y_: numpy_batch_y})
</code>```

PS: If train_writer is a tf.summary.FileWriter, I think you want to:

```<code>summary = sess.run([summary_op], ...)
train_writer.add_summary(summary)
</code>```

EDIT: In response to confusion on the dataset API, I am going to show how to handle this with a Dataset. I am going to use TFRecords. It may not be the simplest solution, but it's one way.

```<code>import numpy as np
from scipy.misc import imread  # There are others that would work here.
from cv2 import resize  # Again, others to choose from.

def read_labeled_image_list(...)
    # See question
    return filenames, labels

def make_tfr(tfr_dir="/YOUR/PREFERRED/TFR/DIR")
    def _int64_list_feature(a_list):
        return tf.train.Feature(int64_list=tf.train.Int64List(value=a_list)

    def _bytes_feature(value):
        return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

    writer = tf.python_io.TFRecordWriter(tfr_dir)
    all_image_paths, all_labels = read_labeled_image_list(...)
    for path, label in zip(all_image_paths, all_labels):
        disk_im = imread(path)
        resized_im = cv2.resize(disk_im, (128, 128))
        raw_im = resized_im.tostring()
        # Construct an example proto-obj,
        example = tf.train.Example(
            # which wants a Features proto-obj,
            features=tf.train.Features(
                # which wants a dict.
                feature={
                    'image_raw': _bytes_feature(raw_im),
                    'label': _int64_list_feature(label)
        })) # close your example object
        serialized = example.SerializeToString()
        writer.write(serialized)

make_tfr()  # After you've done it successfully once, comment out.

def input_pipeline(batch_size, epochs, tfr_dir="/YOUR/PREFERRED/TFR/DIR"):
    # with tf.name_scope("Input"):  maybe you like to scope as much as I do?
    dataset = tf.data.TFRecordDataset(tfr_dir)

    def parse_protocol_buffer(example_proto):
        features = {'image_raw': tf.FixedLenFeature((), tf.string),
                    'label': tf.FixedLenFeature((), tf.int64)}
        parsed_features = tf.parse_single_example(
            example_proto, features)
        return parsed_features['image_raw'], parsed_features['label']

    dataset = dataset.map(parse_protocol_buffer)

    def convert_parsed_proto_to_input(image_string, label):
        image_decoded = tf.decode_raw(image_string, tf.uint8)
        image_resized = tf.reshape(image_decoded, (128, 128, 3))
        image = tf.cast(image_resized, tf.float32)
        # I usually put my image elements in [-1, 1]
        return image * (2. /255) -1, label

    dataset = dataset.map(converted_parsed_proto_to_input)
    dataset = dataset.shuffle(buffer_size=1000)
    dataset = dataset.repeat(batch_size * epochs)
    return dataset

def model(image_tensor):
    ...
    # However you want to do this.
    return predictions

def loss(predictions, labels):
    ...
    return some_loss

def train(some_loss):
    ...
    return train_op

batch_size = 50
iterations = 10000
train_dataset = input_pipeline(batch_size, iterations)
train_iterator = train_dataset.make_initializable_iterator()
image, label = train_iterator.get_next()
predictions = model(image)
loss_op = loss(image, predictions)
train_op = train(loss_op)
summary_op = tf.summary.merge_all()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    train_writer = tf.summary.FileWriter("/YOUR/LOGDIR", sess.graph)
    sess.run(train_iterator.initializer)
    for epoch in range(iterations + 1):
        _, summary = sess.run([train_op, summary_op])
        train_writer.add_summary(summary, epoch)
</code>```

You say you're new to TensorFlow. I hope this doesn't intimidate you. I was new to TensorFlow not long ago, and it was a pain to figure out how to make a good input pipeline. Learning TFRecords seemed impossible. You also say you're new to Python, so I'll warn you that cv2 has a reputation of difficult installs. You may want to look into other ways to resize an image (though I'd advise against PIL, which is probably even more confusing and difficult at first).

Basically, I'm posting this code because because the documentation on writing TFRecords is confusing (Exhibit A vs a blog post that helped me figure it out) but TFRecords is the way I know how to make a Dataset best. Even if you don't go the TFRecords route, this could help you with the map function for datasets, e.g. notice how I pass label through convert... even though it's not used. Making a dataset (specifically from TFRecords) is a lot of lines of code, but Dataset is the preferred way to construct an input pipeline and it's designed to replace the old queue method you're using.

As a side note, the purpose of the queue strategy was to read data from memory directly into the graph without placeholders. Placeholders are slow and memory-intensive compared to the queue strategy, but Datasets are even better when implemented correctly.

I see in your comment that you want to see the placeholder namescope get connected to your graph. The dataset way, you'll see some dataset nodes on the graph. If you scope them with what I commented out, it should be apparent that everything's hooked up right. Your way, you're actually adding this queue-and-preprocess structure onto the graph. Since you'll have to de-tensor-ify the images to pass them into a placeholder, it won't be apparent that your data is flowing correctly.

Now, as I mentioned in the original post, you can just pass batch_x and batch_y into your model and forget the placeholder and dataset altogether. You'll see everything hooked up right from the preprocessing stage, if the queue is implemented right. Still, your images are large before reshaping them. Reading them will be an intensive task. I'd recommend going the hard route of learning to use Datasets and TFRecords.

I hope this helps you implement a Dataset in your code. I hope this helps you get TensorBoard running. And I hope this helps you figure out TFRecords if you decide to go that route.

PS: On the topic of TensorBoard validating that the model is working, you could attach a tf.summary.image(img) as the first line of model(...). Then check out the image dash and see if it's what you expect.

EDIT 2: example = tf.train.Example(features=tf.train.Features(feature={}))

Title: Feed_dict doesnt accept my data

Body:
I've been trying to be able to feed my own images in some tensorflow code to look how the code would react to my own images instead of the MNIST set. I've been able to import images(i think) into tensorflow but I have two placeholders that should get my image data and label data. I tried to use feed_dict(which still seems right to me) to be able to use my data in the rest of my code but it won't accept any data I feed it. I know I can't feed it a Tensor and apparently not a batch but the only way I can think of to make this work is to feed it a list. I saw feed_dict is able to use numpy arrays but im not sure how i should approach converting data to a numpy array.

I'm new to TensorFlow and python so please forgive any mistakes I made, I'm still learning how everything works.

with tf.name_scope('Image_Data_Input'):
  def read_labeled_image_list(image_list_file):
    print('read_labeled_image_list function opened')
    f = open(image_list_file, 'r')
    print('image_list_file opened')
    filenames = []
    labels = []
    print('Arrays formed')
    for line in f:
      filename, label = line[:-1].split(' ')
      filenames.append(filename)
      labels.append(label)
    print('Lines deconstructed')
    return filenames, labels

def read_image(input_queue):
    label = input_queue[1]
    file_contents = tf.read_file(input_queue[0])
    decoded_image = tf.image.decode_jpeg(file_contents, channels=3)
    print('Image decoded to JPEG')
    decoded_image.set_shape([2560, 1440, 3])
    decoded_image = tf.image.resize_images(decoded_image, [128, 128])
    return decoded_image, label

image_list, label_list = read_labeled_image_list(image_list_file)
images = tf.convert_to_tensor(image_list, dtype=tf.string)
labels = tf.convert_to_tensor(label_list, dtype=tf.string)

input_queue = tf.train.slice_input_producer([images, labels], num_epochs=None, shuffle=True)

image, label = read_image(input_queue)

The indentation behaved a little weird when i pasted my code so I'm not sure everything is properly placed.

Well now I have these placeholder:

with tf.name_scope('input'):
  x = tf.placeholder(tf.float32, shape=[None, 784])
  y_ = tf.placeholder(tf.float32, shape=[None, 10])

And I've seen the code routing data to those placeholder this way:

batch_x, batch_y = tf.train.batch([image, label], batchsize)
#_, summary = sess.run([train_writer, summary_op], feed_dict={x: batch_x, y_: batch_y})

But I can't seem to make this work.

Does anyone have any idea how i could make this work?

Again sorry for any mistakes and thanks in advance.

Body:
As the error says, you can't feed tensors into a placeholder. batch_x and batch_y are tensors. The new tf.Dataset API is the preferred way to input data into a model (guide here). I think Dataset.from_tensor_slices would require minimal rewriting. Short of that, build the graph so that batch_x and batch_y flow into the model you're using directly. Then you don't need to use placeholders.

I don't recommend this, but for completeness I want to mention another method. You could:

numpy_batch_x, numpy_batch_y = sess.run([batch_x, batch_y])
_, summary = sess.run([train_writer, summary_op],
    feed_dict={x: numpy_batch_x, y_: numpy_batch_y})

PS: If train_writer is a tf.summary.FileWriter, I think you want to:

summary = sess.run([summary_op], ...)
train_writer.add_summary(summary)

EDIT: In response to confusion on the dataset API, I am going to show how to handle this with a Dataset. I am going to use TFRecords. It may not be the simplest solution, but it's one way.

import numpy as np
from scipy.misc import imread  # There are others that would work here.
from cv2 import resize  # Again, others to choose from.

def read_labeled_image_list(...)
    # See question
    return filenames, labels

def make_tfr(tfr_dir="/YOUR/PREFERRED/TFR/DIR")
    def _int64_list_feature(a_list):
        return tf.train.Feature(int64_list=tf.train.Int64List(value=a_list)

    def _bytes_feature(value):
        return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

    writer = tf.python_io.TFRecordWriter(tfr_dir)
    all_image_paths, all_labels = read_labeled_image_list(...)
    for path, label in zip(all_image_paths, all_labels):
        disk_im = imread(path)
        resized_im = cv2.resize(disk_im, (128, 128))
        raw_im = resized_im.tostring()
        # Construct an example proto-obj,
        example = tf.train.Example(
            # which wants a Features proto-obj,
            features=tf.train.Features(
                # which wants a dict.
                feature={
                    'image_raw': _bytes_feature(raw_im),
                    'label': _int64_list_feature(label)
        })) # close your example object
        serialized = example.SerializeToString()
        writer.write(serialized)

make_tfr()  # After you've done it successfully once, comment out.

def input_pipeline(batch_size, epochs, tfr_dir="/YOUR/PREFERRED/TFR/DIR"):
    # with tf.name_scope("Input"):  maybe you like to scope as much as I do?
    dataset = tf.data.TFRecordDataset(tfr_dir)

    def parse_protocol_buffer(example_proto):
        features = {'image_raw': tf.FixedLenFeature((), tf.string),
                    'label': tf.FixedLenFeature((), tf.int64)}
        parsed_features = tf.parse_single_example(
            example_proto, features)
        return parsed_features['image_raw'], parsed_features['label']

    dataset = dataset.map(parse_protocol_buffer)

    def convert_parsed_proto_to_input(image_string, label):
        image_decoded = tf.decode_raw(image_string, tf.uint8)
        image_resized = tf.reshape(image_decoded, (128, 128, 3))
        image = tf.cast(image_resized, tf.float32)
        # I usually put my image elements in [-1, 1]
        return image * (2. /255) -1, label

    dataset = dataset.map(converted_parsed_proto_to_input)
    dataset = dataset.shuffle(buffer_size=1000)
    dataset = dataset.repeat(batch_size * epochs)
    return dataset

def model(image_tensor):
    ...
    # However you want to do this.
    return predictions

def loss(predictions, labels):
    ...
    return some_loss

def train(some_loss):
    ...
    return train_op

batch_size = 50
iterations = 10000
train_dataset = input_pipeline(batch_size, iterations)
train_iterator = train_dataset.make_initializable_iterator()
image, label = train_iterator.get_next()
predictions = model(image)
loss_op = loss(image, predictions)
train_op = train(loss_op)
summary_op = tf.summary.merge_all()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    train_writer = tf.summary.FileWriter("/YOUR/LOGDIR", sess.graph)
    sess.run(train_iterator.initializer)
    for epoch in range(iterations + 1):
        _, summary = sess.run([train_op, summary_op])
        train_writer.add_summary(summary, epoch)

You say you're new to TensorFlow. I hope this doesn't intimidate you. I was new to TensorFlow not long ago, and it was a pain to figure out how to make a good input pipeline. Learning TFRecords seemed impossible. You also say you're new to Python, so I'll warn you that cv2 has a reputation of difficult installs. You may want to look into other ways to resize an image (though I'd advise against PIL, which is probably even more confusing and difficult at first).

Basically, I'm posting this code because because the documentation on writing TFRecords is confusing (Exhibit A vs a blog post that helped me figure it out) but TFRecords is the way I know how to make a Dataset best. Even if you don't go the TFRecords route, this could help you with the map function for datasets, e.g. notice how I pass label through convert... even though it's not used. Making a dataset (specifically from TFRecords) is a lot of lines of code, but Dataset is the preferred way to construct an input pipeline and it's designed to replace the old queue method you're using.

As a side note, the purpose of the queue strategy was to read data from memory directly into the graph without placeholders. Placeholders are slow and memory-intensive compared to the queue strategy, but Datasets are even better when implemented correctly.

I see in your comment that you want to see the placeholder namescope get connected to your graph. The dataset way, you'll see some dataset nodes on the graph. If you scope them with what I commented out, it should be apparent that everything's hooked up right. Your way, you're actually adding this queue-and-preprocess structure onto the graph. Since you'll have to de-tensor-ify the images to pass them into a placeholder, it won't be apparent that your data is flowing correctly.

Now, as I mentioned in the original post, you can just pass batch_x and batch_y into your model and forget the placeholder and dataset altogether. You'll see everything hooked up right from the preprocessing stage, if the queue is implemented right. Still, your images are large before reshaping them. Reading them will be an intensive task. I'd recommend going the hard route of learning to use Datasets and TFRecords.

I hope this helps you implement a Dataset in your code. I hope this helps you get TensorBoard running. And I hope this helps you figure out TFRecords if you decide to go that route.

PS: On the topic of TensorBoard validating that the model is working, you could attach a tf.summary.image(img) as the first line of model(...). Then check out the image dash and see if it's what you expect.

EDIT 2: example = tf.train.Example(features=tf.train.Features(feature={}))


问:
export_graphviz extratreesclassifier python visualization
Is there a way to use export_graphviz to represent the final tree of extratreesclasiffier? If not, how can it be visually representented?</p>

答:
I think there is no way to visualize a specific tree from sklearn.ensemble.ExtraTreesClassifier.

But you can visualize it with a single tree from sklearn.tree.ExtraTreeClassifier.

```<code>from sklearn import tree
...

#Fit an Extra Tree model to the data
model = tree.ExtraTreeClassifier()
model.fit(X_train, y_train)

#Use http://webgraphviz.com to visualize the graph of this file
with open("tree_classifier.txt", "w") as f:
    f = tree.export_graphviz(model, out_file=f)
</code>```

Here an example with Decision tree that also work with Extra tree:
http://dataaspirant.com/2017/04/21/visualize-decision-tree-python-graphviz/

Body:
I think there is no way to visualize a specific tree from sklearn.ensemble.ExtraTreesClassifier.

But you can visualize it with a single tree from sklearn.tree.ExtraTreeClassifier.

from sklearn import tree
...

#Fit an Extra Tree model to the data
model = tree.ExtraTreeClassifier()
model.fit(X_train, y_train)

#Use http://webgraphviz.com to visualize the graph of this file
with open("tree_classifier.txt", "w") as f:
    f = tree.export_graphviz(model, out_file=f)

Here an example with Decision tree that also work with Extra tree:
http://dataaspirant.com/2017/04/21/visualize-decision-tree-python-graphviz/


问:
CSS gradient border not showing correctly
I want to set half blue and orange for border-color of text input.

I tried using a gradient but it doesn't work.

what is my code problem?

.search {
  width: 550px;
  height: 50px;
  margin-left: 350px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid;
  border-image: linear-gradient(to right, rgb(254, 113, 53) 50%, rgb(55, 154, 214) 50%);
  font-size: 20px;
  text-align: center;
  transition: all 0.2s linear;
}

.search:hover,
.search:focus {
  border: #4cbea5 solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form>
</div></code>```

答:
You had a typo on this gradient line, it should be like this:

```<code>  border-image: linear-gradient(to right, rgb(254, 113, 53), rgb(55, 154, 214)) 1 20%;
</code>```

See running demo:

.search {
  width: 550px;
  height: 50px;
  margin-left: 50px;  /* adjust as needed */
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid 5px;  /* made thicker for illustration purposes only */
  border-image: linear-gradient(to right, rgb(254, 113, 53), rgb(55, 154, 214)) 1 20%;
  font-size: 20px;
  text-align: center;
}

.search:hover,
.search:focus {
  border: #4cbea5 solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form>
</div></code>```

Body:
I want to set half blue and orange for border-color of text input.

I tried using a gradient but it doesn't work.

what is my code problem?

.search {
  width: 550px;
  height: 50px;
  margin-left: 350px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid;
  border-image: linear-gradient(to right, rgb(254, 113, 53) 50%, rgb(55, 154, 214) 50%);
  font-size: 20px;
  text-align: center;
  transition: all 0.2s linear;
}

.search:hover,
.search:focus {
  border: #4cbea5 solid;
}

  <form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form>

Body:
You had a typo on this gradient line, it should be like this:

  border-image: linear-gradient(to right, rgb(254, 113, 53), rgb(55, 154, 214)) 1 20%;

See running demo:

.search {
  width: 550px;
  height: 50px;
  margin-left: 50px;  /* adjust as needed */
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid 5px;  /* made thicker for illustration purposes only */
  border-image: linear-gradient(to right, rgb(254, 113, 53), rgb(55, 154, 214)) 1 20%;
  font-size: 20px;
  text-align: center;
}

.search:hover,
.search:focus {
  border: #4cbea5 solid;
}

<div>
  <form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form>
</div>


问:
How are the equational reasoning operators used in practice?
The Agda Standard Library exports some operators that allow you to write proofs in a manner similar to what you would do on paper, or how it is taught in the Haskell community. While you can write "conventional" Agda proofs in a somewhat systematic manner by refining a Goal using with abstractions, rewrites or helper lemmas as needed, it isn't really clear to me how a proof using the equality reasoning primitives "comes to be".

That is, while you can find examples about what these proofs look like when they are finished and type-check here and there, these already worked examples don't show you how they are developed in a systematic step-by-step (maybe hole-driven) manner.

How is it done in practice? Do people "refactor" an already existing proof? Do you try to "burn the candle from both sides" by starting with the left-hand and right-hand sides of the initial Goal and a hole in the middle?

Furthermore, the Agda documentation states that if the equality reasoning primitives are in scope, "then Auto will do equality reasoning using these constructs". What does that mean?

I would appreciate it if someone could point me in the right direction, or even post an example of how they develop these kinds of proofs step-by-step, what questions they ask themselves as they go through it, where they put the holes and so on. Thanks!

答:
I think it would be more helpful for you to look at the definitions for equational reasoning for Identity here Equational Reasoning. The main point is that it is just a nicer way to apply transitivity chains and allowing the user to see the actual expression in code, rather than the proof evidence which is not that easy to read.

The way I go about building a proof using equational reasoning for any setoid is this. With the example of natural numbers

```<code>open import Relation.Binary.PropositionalEquality
open ≡-Reasoning

data ℕ : Set where
  zero : ℕ
  succ : ℕ → ℕ

_+_ : ℕ → ℕ → ℕ
m + zero   = m
m + succ n = succ (m + n)
</code>```

Let's take commutativity as an example.
This is how I start with the goals.

```<code>comm+ : ∀ m n → m + n ≡ n + m
comm+ m zero     = {!!}
comm+ m (succ n) =
  begin
    succ (m + n)
  ≡⟨ {!!} ⟩
    succ n + m
  ∎
</code>```

Now I see the original expression and goal and my goal proof is between the brackets.
I work only on the expression leaving the proof objects untouched and add
what I think should work.

```<code>comm+ : ∀ m n → m + n ≡ n + m
comm+ m zero     = {!!}
comm+ m (succ n) =
  begin
    succ (m + n)
  ≡⟨ {!!} ⟩
    succ (n + m)
  ≡⟨ {!!}⟩
    succ n + m
  ∎
</code>```

Once I think I have a proof, I work on the proof objects that justify my steps.

Regarding the auto-tactic, you should not bother with that in my opinion. It's not being worked on for a while.

Body:
I think it would be more helpful for you to look at the definitions for equational reasoning for Identity here Equational Reasoning. The main point is that it is just a nicer way to apply transitivity chains and allowing the user to see the actual expression in code, rather than the proof evidence which is not that easy to read.

The way I go about building a proof using equational reasoning for any setoid is this. With the example of natural numbers

open import Relation.Binary.PropositionalEquality
open ≡-Reasoning

data ℕ : Set where
  zero : ℕ
  succ : ℕ → ℕ

_+_ : ℕ → ℕ → ℕ
m + zero   = m
m + succ n = succ (m + n)

Let's take commutativity as an example.
This is how I start with the goals.

comm+ : ∀ m n → m + n ≡ n + m
comm+ m zero     = {!!}
comm+ m (succ n) =
  begin
    succ (m + n)
  ≡⟨ {!!} ⟩
    succ n + m
  ∎

Now I see the original expression and goal and my goal proof is between the brackets.
I work only on the expression leaving the proof objects untouched and add
what I think should work.

comm+ : ∀ m n → m + n ≡ n + m
comm+ m zero     = {!!}
comm+ m (succ n) =
  begin
    succ (m + n)
  ≡⟨ {!!} ⟩
    succ (n + m)
  ≡⟨ {!!}⟩
    succ n + m
  ∎

Once I think I have a proof, I work on the proof objects that justify my steps.

Regarding the auto-tactic, you should not bother with that in my opinion. It's not being worked on for a while.


问:
PHP Tree Traversal For Sub Forums Within Sub Forums
I have been developing my own forum for about a week now and I am almost done with all of the code, however, I am stuck on one single issue that I have not been able to figure out.

Well, simply said I have sub forums that can be within any amount of other sub forums.

How would I create a path dynamically to any of those sub forums on the spot with PHP.

After the path is created I would use it within href's and other things.

I am guessing I would somehow need to traverse the database based on a ID column and another column that would link one sub forum to another sub forum.

Let's assume that my database table looks like this:

```<code>ID | Name        | Link |
---+-------------+-------
1  | Forum-One   | Top  |
2  | Forum-Two   | 1    |
3  | Forum-Three | 2    |
4  | Forum-Four  | 2    |
5  | Forum-Five  | 3    |
6  | Forum-Six   | 3    |
</code>```

How would I go about doing this - or is there something else that must be done instead?

I hope I was clear enough for everyone to understand.

EDIT:

```<code> include("inc/config.php");

 function generateBreadcrumb($startingID){

  $result = mysql_query("SELECT * FROM temp_table WHERE ID='$startingID'");

  while($row = mysql_fetch_array($result))
  {
    $db_id=$row['ID'];
    $db_name=$row['Name'];
  }

     if($db_id!='Top'){
         return generateBreadCrumb($db_id);
     } else {
         return $db_name;
     }
 }

 $startID='6';
 echo generateBreadcrumb($startID);
</code>```

答:
First you need a terminating condition.  So set your top level Forum[link] to null, or 'top', or something.  Then its simply a matter of using a recursive function put your bread-crumb together.

So lets assume you wanted to go to display the breadcrumb to Forum-One:Forum-Three:Forum-Six , better known as Forum-Six.

Example code:

```<code> <?php
 $yourForumId = 6; // replace this dynamically with your forum;
 $breadcrumb = generateBreadcrumb($yourForum);
 function generateBreadcrumb($startingForumId){
     $sql= "SELECT Name ,link FROM Forums WHERE ID = ".$startingForumId;
     //run your $sql however you do to get results
     //assuming you get associative arrays back
     if($res['link'] != 'top'){
         return generateBreadCrumb($res['link']).":".$res['Name'];
     } else {
         return $res['Name'];
     }
 }
 echo $breadcrumb;
 ?>
</code>```

It's recursion, which if you're new to it may seem complicated, but I hope that helps!

EDIT: here's your code with the needed edit...

```<code>include("inc/config.php");

 function generateBreadcrumb($startingID){

     $result = mysql_query("SELECT * FROM temp_table WHERE ID='$startingID'");

     $row = mysql_fetch_array($result);
     $db_id=$row['link'];
     $db_name=$row['Name'];

     if($db_id!='Top'){
         return generateBreadCrumb($db_id).":".$db_name;
     } else {
         return $db_name;
     }
 }

 $startID='6';
 echo generateBreadcrumb($startID);
</code>```

Body:
I have been developing my own forum for about a week now and I am almost done with all of the code, however, I am stuck on one single issue that I have not been able to figure out.

Well, simply said I have sub forums that can be within any amount of other sub forums.

How would I create a path dynamically to any of those sub forums on the spot with PHP.

After the path is created I would use it within href's and other things.

I am guessing I would somehow need to traverse the database based on a ID column and another column that would link one sub forum to another sub forum.

Let's assume that my database table looks like this:

ID | Name        | Link |
---+-------------+-------
1  | Forum-One   | Top  |
2  | Forum-Two   | 1    |
3  | Forum-Three | 2    |
4  | Forum-Four  | 2    |
5  | Forum-Five  | 3    |
6  | Forum-Six   | 3    |

How would I go about doing this - or is there something else that must be done instead?

I hope I was clear enough for everyone to understand.

EDIT:

 include("inc/config.php");

 function generateBreadcrumb($startingID){

  $result = mysql_query("SELECT * FROM temp_table WHERE ID='$startingID'");

  while($row = mysql_fetch_array($result))
  {
    $db_id=$row['ID'];
    $db_name=$row['Name'];
  }

     if($db_id!='Top'){
         return generateBreadCrumb($db_id);
     } else {
         return $db_name;
     }
 }

 $startID='6';
 echo generateBreadcrumb($startID);

Body:
First you need a terminating condition.  So set your top level Forum[link] to null, or 'top', or something.  Then its simply a matter of using a recursive function put your bread-crumb together.

So lets assume you wanted to go to display the breadcrumb to Forum-One:Forum-Three:Forum-Six , better known as Forum-Six.

Example code:

 <?php
 $yourForumId = 6; // replace this dynamically with your forum;
 $breadcrumb = generateBreadcrumb($yourForum);
 function generateBreadcrumb($startingForumId){
     $sql= "SELECT Name ,link FROM Forums WHERE ID = ".$startingForumId;
     //run your $sql however you do to get results
     //assuming you get associative arrays back
     if($res['link'] != 'top'){
         return generateBreadCrumb($res['link']).":".$res['Name'];
     } else {
         return $res['Name'];
     }
 }
 echo $breadcrumb;
 ?>

It's recursion, which if you're new to it may seem complicated, but I hope that helps!

EDIT: here's your code with the needed edit...

include("inc/config.php");

 function generateBreadcrumb($startingID){

     $result = mysql_query("SELECT * FROM temp_table WHERE ID='$startingID'");

     $row = mysql_fetch_array($result);
     $db_id=$row['link'];
     $db_name=$row['Name'];

     if($db_id!='Top'){
         return generateBreadCrumb($db_id).":".$db_name;
     } else {
         return $db_name;
     }
 }

 $startID='6';
 echo generateBreadcrumb($startID);


问:
SQL row in column
I have this SQL query

```<code>SELECT COUNT(*)*100/(SELECT COUNT(*) FROM tickets WHERE status = 'closed')
FROM tickets
WHERE closed_at <= due_at
UNION
SELECT COUNT(*)*100/(SELECT COUNT(*) FROM tickets WHERE status = 'closed')
FROM tickets
WHERE closed_at > due_at;
</code>```

and it returns this

```<code>ROW 1 - 35
ROW 2 - 47
</code>```

but I need the return like this:

```<code> 1 | 2 |
35  47
</code>```

I need the returns in columns, not rows.

Thanks.

答:
Use conditional aggregation.  I would recommend:

```<code>SELECT (SUM(CASE WHEN closed_at <= due_at THEN 100.0 ELSE 0 END) /
        SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END)
       ),
       (SUM(CASE WHEN closed_at > due_at THEN 100.0 ELSE 0 END) /
        SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END)
       )
FROM tickets ;
</code>```

It seems strange that you are filtering on status = 'closed' in the denominator, but not in the numerator.  If status = closed should be the filter for both, then you can simplify this to:

```<code>SELECT AVG(CASE WHEN closed_at <= due_at THEN 100.0 ELSE 0 END),
       AVG(CASE WHEN closed_at > due_at THEN 100.0 ELSE 0 END)
FROM tickets
WHERE status = 'closed';
</code>```

Title: SQL row in column

Body:
I have this SQL query

SELECT COUNT(*)*100/(SELECT COUNT(*) FROM tickets WHERE status = 'closed')
FROM tickets
WHERE closed_at <= due_at
UNION
SELECT COUNT(*)*100/(SELECT COUNT(*) FROM tickets WHERE status = 'closed')
FROM tickets
WHERE closed_at > due_at;

and it returns this

ROW 1 - 35
ROW 2 - 47

but I need the return like this:

 1 | 2 |
35  47

I need the returns in columns, not rows.

Thanks.

Body:
Use conditional aggregation.  I would recommend:

SELECT (SUM(CASE WHEN closed_at <= due_at THEN 100.0 ELSE 0 END) /
        SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END)
       ),
       (SUM(CASE WHEN closed_at > due_at THEN 100.0 ELSE 0 END) /
        SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END)
       )
FROM tickets ;

It seems strange that you are filtering on status = 'closed' in the denominator, but not in the numerator.  If status = closed should be the filter for both, then you can simplify this to:

SELECT AVG(CASE WHEN closed_at <= due_at THEN 100.0 ELSE 0 END),
       AVG(CASE WHEN closed_at > due_at THEN 100.0 ELSE 0 END)
FROM tickets
WHERE status = 'closed';


问:
How to hide Wordpress widget ID programmatically
Based on a particular value(appID) I want to hide one of the widget ID in my wordpress blog.

my widget Id : custom_html-2  ( I got this value from enabling accessibility mode)
( from this url I got widgetID : /wp-admin/widgets.php?widgets-access=on&_wpnonce=0b123456fb2&editwidget=custom_html-2&sidebar=right-sidebar&key=0 )

Here I want to hide custom_html-2  when the value of appID is in.abcd.app .

I just echoed appID , I am getting the value in.abcd.app , but the widget is not getting hidden.

I opened the Sidebar (sidebar.php) in the word press and did modification as bellow. Didnt workout - I am new to wordpress and PHP

```<code><!-- Sidebar -->
<div class="col-lg-4 col-md-4 col-sm-4">

    <aside class="sidebar">

        <?php if ( is_active_sidebar( 'right-sidebar' ) ) : ?>
        <div class="sidebar-widget">

            <?php dynamic_sidebar( 'right-sidebar' ); ?>

            <?php
                <?php $widgets  = get_option('widget'.sidebar-widget); ?>
                $appID =  $_SERVER['HTTP_X_REQUESTED_WITH']
                if ($appID = 'in.abcd.app')
                {
                <?php unset($widgets['custom_html-2']); ?>
            ?>

        </div>
        <?php endif; ?>

    </aside>

</div>
<!-- /end sidebar -->
</code>```

答:
You'll want to add something like the following to your functions.php</p>

```<code>add_filter( 'sidebars_widgets', 'unset_sidebar_widget' );

function unset_sidebar_widget( $sidebars_widgets ) {
    $appID =  $_SERVER['HTTP_X_REQUESTED_WITH'];
    if ($appID = 'in.abcd.app')
    {
        unset($sidebars_widgets['custom_html-2']);
    }
  return $sidebars_widgets;
}
</code>```

Body:
Based on a particular value(appID) I want to hide one of the widget ID in my wordpress blog.

my widget Id : custom_html-2  ( I got this value from enabling accessibility mode)
( from this url I got widgetID : /wp-admin/widgets.php?widgets-access=on&_wpnonce=0b123456fb2&editwidget=custom_html-2&sidebar=right-sidebar&key=0 )

Here I want to hide custom_html-2  when the value of appID is in.abcd.app .

I just echoed appID , I am getting the value in.abcd.app , but the widget is not getting hidden.

I opened the Sidebar (sidebar.php) in the word press and did modification as bellow. Didnt workout - I am new to wordpress and PHP

        <?php if ( is_active_sidebar( 'right-sidebar' ) ) : ?>

            <?php dynamic_sidebar( 'right-sidebar' ); ?>

            <?php
                <?php $widgets  = get_option('widget'.sidebar-widget); ?>
                $appID =  $_SERVER['HTTP_X_REQUESTED_WITH']
                if ($appID = 'in.abcd.app')
                {
                <?php unset($widgets['custom_html-2']); ?>
            ?>

        <?php endif; ?>

Body:
You'll want to add something like the following to your functions.php

add_filter( 'sidebars_widgets', 'unset_sidebar_widget' );

function unset_sidebar_widget( $sidebars_widgets ) {
    $appID =  $_SERVER['HTTP_X_REQUESTED_WITH'];
    if ($appID = 'in.abcd.app')
    {
        unset($sidebars_widgets['custom_html-2']);
    }
  return $sidebars_widgets;
}


问:
How a middleware is deployed for a distributed system?
I studied about distributed systems but I'm still not understanding how a middleware is deployed in order to install a distributed system.

I practiced sockets, but didn't anything about middleware and distributed system development and administration.

I'm confused about how the middleware can be deployed - must it be installed on a proxy machine, or must be installed on every machine (as part of the distributed system)? How client machines make use of middleware, is there a client part of the middleware?

答:
Many of the middleware integrations in enterprise level systems are based on the concept of Service oriented architecture(SOA).

In SOA,you are responsible to connect disparate systems into one functional integral unit. Web services act as a way of integrating the different systems. Many of the Web applications use REST but still there are many enterprises which expose there services through SOAP(due to better security standards).

Simple example: Suppose you are building a web management system for a bank say. There are many operations involved: you need to handle creating customers, financial transactions,managing customers. You don't have to create every design from scratch. You can leverage some operations.Like suppose creating customer , functionality already available in c# and you want to use the same logic in your java code let us say. Than you need to use Web services.
This was just to explain you how distributed pattern works in SOA.

Further, there will be many server end configuration like JMS(Java messaging service), MQ's which play a crucial role in integration.

I suggest you to read about these, this could provide you some picture over the clarifications you need.

Edited:

Think of the system-1 has a Client like Web Browser

system-2 you can see that is connected to various sub units. System 2 is your entire app which you have built by reusing the functionalities through the sub units connected.

http request/response you are able to send back and forth information between client and server.

Through Web Services you are able to connect to any sub system in a platform independent way to build whatever you need by leveraging already existing functions from them.

MQ's you use for data storage while routing/message transformation in the flows.


问:
Newton method in python for multivariables (system of equations)
My code is running fine for first iteration but after that it outputs the following error:

```<code>ValueError: matrix must be 2-dimensional
</code>```

To the best of my knowledge (which is not much in python), my code is correct. but I don't know, why it is not running correctly for all given iterations. Could anyone help me in this problem.

```<code>from __future__ import division
import numpy as np
import math
import matplotlib.pylab as plt
import sympy as sp
from numpy.linalg import inv

#initial guesses
x = -2
y = -2.5
i1 = 0

while i1<5:
    F= np.matrix([[(x**2)+(x*y**3)-9],[(3*y*x**2)-(y**3)-4]])
    theta = np.sum(F)
    J = np.matrix([[(2*x)+y**3, 3*x*y**2],[6*x*y, (3*x**2)-(3*y**2)]])
    Jinv = inv(J)
    xn = np.array([[x],[y]])
    xn_1 = xn - (Jinv*F)
    x = xn_1[0]
    y = xn_1[1]
    #~ print theta
    print xn
    i1 = i1+1
</code>```

答:
I believe xn_1 is a 2D matrix. Try printing it you and you will see [[something], [something]]

Therefore to get the x and y, you need to use multidimensional indexing. Here is what I did

```<code>x = xn_1[0,0]
y = xn_1[1,0]
</code>```

This works because within the 2D matrix xn_1 are two single element arrays. Therefore we need to further index 0 to get that single element.

Edit: To clarify, xn_1[1,0] means to index 1 and then take that subarray and index 0 on that. And although according to Scipy it may seem that it should be functionally equivalent to xn_1[1][0], that only applies to the general np.array type and not the np.matrix type. Here is an excellent thread on SO that explains this.

So you should use the xn_1[1,0] way to get the element you want.

Body:
My code is running fine for first iteration but after that it outputs the following error:

ValueError: matrix must be 2-dimensional

To the best of my knowledge (which is not much in python), my code is correct. but I don't know, why it is not running correctly for all given iterations. Could anyone help me in this problem.

from __future__ import division
import numpy as np
import math
import matplotlib.pylab as plt
import sympy as sp
from numpy.linalg import inv

#initial guesses
x = -2
y = -2.5
i1 = 0

while i1<5:
    F= np.matrix([[(x**2)+(x*y**3)-9],[(3*y*x**2)-(y**3)-4]])
    theta = np.sum(F)
    J = np.matrix([[(2*x)+y**3, 3*x*y**2],[6*x*y, (3*x**2)-(3*y**2)]])
    Jinv = inv(J)
    xn = np.array([[x],[y]])
    xn_1 = xn - (Jinv*F)
    x = xn_1[0]
    y = xn_1[1]
    #~ print theta
    print xn
    i1 = i1+1

Body:
I believe xn_1 is a 2D matrix. Try printing it you and you will see [[something], [something]]

Therefore to get the x and y, you need to use multidimensional indexing. Here is what I did

x = xn_1[0,0]
y = xn_1[1,0]

This works because within the 2D matrix xn_1 are two single element arrays. Therefore we need to further index 0 to get that single element.

Edit: To clarify, xn_1[1,0] means to index 1 and then take that subarray and index 0 on that. And although according to Scipy it may seem that it should be functionally equivalent to xn_1[1][0], that only applies to the general np.array type and not the np.matrix type. Here is an excellent thread on SO that explains this.

So you should use the xn_1[1,0] way to get the element you want.


问:
Can i import and edit code from one external library ? (e.g. google-maps-utils)
I´m using google-maps-utils (only marker clustering) and the code is read-only.

```<code>dependencies {
    compile 'com.google.maps.android:android-maps-utils:0.5+'
}
</code>```

I want to comment 3 lines in ClusterManager.java

```<code>    /**
     * Might re-cluster.
     */
    @Override
    public void onCameraIdle() {
        if (mRenderer instanceof GoogleMap.OnCameraIdleListener) {
            ((GoogleMap.OnCameraIdleListener) mRenderer).onCameraIdle();
        }

        // Don't re-compute clusters if the map has just been panned/tilted/rotated.
        CameraPosition position = mMap.getCameraPosition();
//        if (mPreviousCameraPosition != null && mPreviousCameraPosition.zoom == position.zoom) {
//            return;
//        }
        mPreviousCameraPosition = mMap.getCameraPosition();

        cluster();
    }
</code>```

Can i import this code to my app and edit these lines ?

If yes, how can i do that ? (step by step)

I'm trying to import the modules but I'm doing something wrong.

答:
If this is a high level class which you will use directly you can simply extend this class and override the method:

```<code>public class MyClusterManager<T extends ClusterItem> extends ClusterManager<T> {
  @Override
  public void onCameraIdle() {
    if (mRenderer instanceof GoogleMap.OnCameraIdleListener) {
      ((GoogleMap.OnCameraIdleListener) mRenderer).onCameraIdle();
    }
    CameraPosition position = mMap.getCameraPosition();
    mPreviousCameraPosition = mMap.getCameraPosition();
    cluster();
  }
}
</code>```

and then:

```<code>ClusterManager<MyClusterItem> clusterManager = new MyClusterManager<MyClusterItem>();
// do something with your own clusterManager ...
</code>```

Body:
I´m using google-maps-utils (only marker clustering) and the code is read-only.

dependencies {
    compile 'com.google.maps.android:android-maps-utils:0.5+'
}

I want to comment 3 lines in ClusterManager.java

    /**
     * Might re-cluster.
     */
    @Override
    public void onCameraIdle() {
        if (mRenderer instanceof GoogleMap.OnCameraIdleListener) {
            ((GoogleMap.OnCameraIdleListener) mRenderer).onCameraIdle();
        }

        // Don't re-compute clusters if the map has just been panned/tilted/rotated.
        CameraPosition position = mMap.getCameraPosition();
//        if (mPreviousCameraPosition != null && mPreviousCameraPosition.zoom == position.zoom) {
//            return;
//        }
        mPreviousCameraPosition = mMap.getCameraPosition();

        cluster();
    }

Can i import this code to my app and edit these lines ?

If yes, how can i do that ? (step by step)

I'm trying to import the modules but I'm doing something wrong.

Body:
If this is a high level class which you will use directly you can simply extend this class and override the method:

public class MyClusterManager<T extends ClusterItem> extends ClusterManager<T> {
  @Override
  public void onCameraIdle() {
    if (mRenderer instanceof GoogleMap.OnCameraIdleListener) {
      ((GoogleMap.OnCameraIdleListener) mRenderer).onCameraIdle();
    }
    CameraPosition position = mMap.getCameraPosition();
    mPreviousCameraPosition = mMap.getCameraPosition();
    cluster();
  }
}

and then:

ClusterManager<MyClusterItem> clusterManager = new MyClusterManager<MyClusterItem>();
// do something with your own clusterManager ...


问:
How do I select only 1 row in sybase without using rowcount
How do I select only 1 row in sybase without using rowcount? I don't have the privilege to set rowcount in sybase. Is there a way to select only 1 row?

For example:

```<code>select * from table where name = 'jack'
</code>```

This returns two rows; how do I select only one row from the result set without using set rowcount?

答:
Try the query:

```<code>SELECT TOP 1 * FROM mytable
WHERE name = 'jack'
</code>```

As you might guess, this selects the TOP 1 matching results. If you wanted more (which you don't here) you could use any number (TOP 100 or TOP 1000, etc).

A more comprehensive example can be found on w3schools: http://www.w3schools.com/Sql/sql_top.asp

Body:
How do I select only 1 row in sybase without using rowcount? I don't have the privilege to set rowcount in sybase. Is there a way to select only 1 row?

For example:

select * from table where name = 'jack'

This returns two rows; how do I select only one row from the result set without using set rowcount?

Body:
Try the query:

SELECT TOP 1 * FROM mytable
WHERE name = 'jack'

As you might guess, this selects the TOP 1 matching results. If you wanted more (which you don't here) you could use any number (TOP 100 or TOP 1000, etc).

A more comprehensive example can be found on w3schools: http://www.w3schools.com/Sql/sql_top.asp


问:
CORS error when using PHP on IIS on server side and angular 4 on client side
I have 2 web sites that communicate with REST API on my server side.
The main web site has the main domain and the second website has a sub domain.
for example www.example.com and www.admin.example.com

i have a REST API on the www.example.com root directory and when the www.example.com address to the API everything is OK, but when www.admin.example.com is trying to address to the API, i get an error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://admin.example.com' is therefore not allowed access.

I have this PHP code line on my RestController.php file:

```<code>header("Access-Control-Allow-Origin: *");
</code>```

I also tried to add to my web.config  the following code:

```<code><system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
      <add name="Access-Control-Max-Age" value="1000" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
</code>```

but still i get the the  No 'Access-Control-Allow-Origin' header error, or the error "The 'Access-Control-Allow-Origin' header contains multiple values '*, *, but only one is allowed."

i don't know if it's important, but we are using Angular 4 for client side.

Does anyone has an idea what is the problem, is it an IIS issue or PHP issue or even client side issue?

Thank You

答:
Previously you have to either write your own code or other hacking methods, but now Microsoft ships an official IIS extension, called IIS CORS Module.

You can configure CORS responses easily after installing it.

Body:
I have 2 web sites that communicate with REST API on my server side.
The main web site has the main domain and the second website has a sub domain.
for example www.example.com and www.admin.example.com

i have a REST API on the www.example.com root directory and when the www.example.com address to the API everything is OK, but when www.admin.example.com is trying to address to the API, i get an error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://admin.example.com' is therefore not allowed access.

I have this PHP code line on my RestController.php file:

header("Access-Control-Allow-Origin: *");

I also tried to add to my web.config  the following code:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
      <add name="Access-Control-Max-Age" value="1000" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

but still i get the the  No 'Access-Control-Allow-Origin' header error, or the error "The 'Access-Control-Allow-Origin' header contains multiple values '*, *, but only one is allowed."

i don't know if it's important, but we are using Angular 4 for client side.

Does anyone has an idea what is the problem, is it an IIS issue or PHP issue or even client side issue?

Thank You