text:
Q: Regex for Python Needed Here are my strings :
-rwxrwx--- Administrators/unknown      563092   0% 2018-05-29 02:16:49 E:/program files/bak fil/sql server (mssqlserver)/var/work.log

-rwxrwx--- kandep2/Domain Users      563092   0% 2018-05-29 02:16:49 E:/program files/bak fil/sql server (mssqlserver)/var/dummy.log

I would like to capture everything in a group except 0%.
So far, i have the following regex:
([rwexXst-]+) ([^1-9]+) +(\d+)+.+? +(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (.*)

This works for the first row, but it fails on the second row because second row username has a number in it.
How should i modify my regex to get output like this:
Group#1
-rwxrwx---
Administrators/unknown
563092
2018-05-29 02:16:49
E:/program files/bak fil/sql server (mssqlserver)/var/work.log

Group #2
-rwxrwx---
kandep2/Domain Users
563092
2018-05-29 02:16:49
E:/program files/bak fil/sql server (mssqlserver)/var/dummy.log

A: Let me suggest named groups. Also, try and generalize your regex so you don't have to count exact spaces.
Try:
pattern = re.compile(r'''(?P<rw>[rwexXst\-]+)\s+
(?P<dir>\w+(?:\s+\w+)?\/\w+(?:\s+\w+)?)\s+
(?P<nums>\d+)(?:.+\%)?\s+
(?P<date>\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\s+
(?P<msg>.*)$''', flags=re.M|re.X)

test_text = '''
-rwxrwx--- Administrators/unknown      563092   0% 2018-05-29 02:16:49 E:/program files/bak fil/sql server (mssqlserver)/var/work.log

-rwxrwx--- kandep2/Domain Users      563092   0% 2018-05-29 02:16:49 E:/program files/bak fil/sql server (mssqlserver)/var/dummy.log
'''

for i in re.finditer(test_text):
    match = re.search(i)
    if match:
        print(match.groupdict())
        print(match.groups())

Or the even simpler:
for match in pattern.finditer(test_text):
    print(match.groupdict())
    print(match.groups())

Should give you:
{'rw': '-rwxrwx---',
 'dir': 'Administrators/unknown',
 'nums': '563092',
 'date': '2018-05-29 02:16:49',
 'msg': 'E:/program files/backup agents for cluster groups/sql server (mssqlserver)/var/work.log'}
('-rwxrwx---',
 'Administrators/unknown',
 '563092',
 '2018-05-29 02:16:49',
 'E:/program files/bak fil/sql server (mssqlserver)/var/work.log')
{'rw': '-rwxrwx---',
 'dir': 'kandep2/Domain Users',
 'nums': '563092',
 'date': '2018-05-29 02:16:49',
 'msg': 'E:/program files/backup agents for cluster groups/sql server (mssqlserver)/var/dummy.log'}
('-rwxrwx---',
 'kandep2/Domain Users',
 '563092', '2018-05-29 02:16:49',
 'E:/program files/bak fil/sql server (mssqlserver)/var/dummy.log')

A: You could use a verbose expression with named capturing groups like so:
(?P<rights>-[-rwx]+)\s+         # rights -> one of -,r,w,x
(?P<group>(?:(?!\s{2,}).)+)\s+  # anything not two consecutive whitespaces
(?P<uid>\d+)\s+                 # only digits
(?:[\d%]+)\s+                   # digits and %
(?P<date>[- :\d]+)\s+           # the date
(?P<filename>.+)                # and the filename

In Python this is:

import re

data = """
-rwxrwx--- Administrators/unknown      563092   0% 2018-05-29 02:16:49 E:/program files/bak fil/sql server (mssqlserver)/var/work.log

-rwxrwx--- kandep2/Domain Users      563092   0% 2018-05-29 02:16:49 E:/program files/bak fil/sql server (mssqlserver)/var/dummy.log
"""

rx = re.compile(r'''
    (?P<rights>-[-rwx]+)\s+
    (?P<group>(?:(?!\s{2,}).)+)\s+
    (?P<uid>\d+)\s+
    (?:[\d%]+)\s+
    (?P<date>[- :\d]+)\s+
    (?P<filename>.+)''', re.M | re.X)

results = [m.groupdict() for m in rx.finditer(data)]
print(results)

This will yield
[
    {'rights': '-rwxrwx---', 'group': 'Administrators/unknown', 'uid': '563092', 'date': '2018-05-29 02:16:49', 'filename': 'E:/program files/bak fil/sql server (mssqlserver)/var/work.log'},
    {'rights': '-rwxrwx---', 'group': 'kandep2/Domain Users', 'uid': '563092', 'date': '2018-05-29 02:16:49', 'filename': 'E:/program files/bak fil/sql server (mssqlserver)/var/dummy.log'}
]

The idea is to capture anything of interest and to match (or use non-capturing groups) for the "garbage". See a demo for the expression on regex101.com.

A: Solution without regex.
from pprint import pprint

input_row = '-rwxrwx--- kandep2/Domain %Users      563092   0%% 2018-05-29 02:16:49 E:/program $files/bak fil/sql server (mssqlserver)/var/dummy.log'

def parse(value):
    v = value.index(':/')

    row = input_row[:v-1].strip()
    row = row.split()

    return {
        'rw': row.pop(0),
        'date': '%s %s' % (row.pop(-2), row.pop(-1)),
        'value': row.pop(-1),
        'nums': row.pop(-1),
        'msg': input_row[v-1:],
        'dir': ' '.join(row),
    }

pprint(parse(input_row))

Result:
{'date': '2018-05-29 02:16:49',
 'dir': 'kandep2/Domain %Users',
 'msg': 'E:/program $files/bak fil/sql server (mssqlserver)/var/dummy.log',
 'nums': '563092',
 'rw': '-rwxrwx---',
 'value': '0%%'}


text:
Q: Merging two XML source documents with XSLT XML file one could have 1000 - 6000 forms; XML file two could have one to 100 or more.  I want to replace any identical form in file one with file two.  If it exists in file 2 but not in file one I want to add it to file 1.  After the files are merged I want to run it against my XSLT.  I am using a 2.0 stylesheet and a Saxon parser.
File 1:

<Forms>
    <Form name="fred" date="10/01/2008"/>
    <Form name="barney" date="12/31/2009"/>
    <Form name="wilma" date="12/31/2010"/>
  </Forms>

File 2:

<Forms>
  <Form name="barney" date="01/31/2010"/>
  <Form name="betty" date="6/31/2009"/>
  </Forms>

Merged file should look like:

<Forms>
    <Form name="fred" date="10/01/2008"/>
    <Form name="barney" date="01/31/2010"/>
    <Form name="wilma" date="12/31/2010"/>
    <Form name="betty" date="6/31/2009"/>
  </Forms>

A: If maintaining document order is not a priority:
<xsl:variable name="forms1" select="document('forms1.xml')/Forms/Form" />
<xsl:variable name="forms2" select="document('forms2.xml')/Forms/Form" />

<xsl:variable name="merged" select="
  $forms1[not(@name = $forms2/@name)] | $forms2
" />

<xsl:template match="/">
  <xsl:apply-templates select="$merged" />
</xsl:template>

<xsl:template match="Form">
  <!-- for the sake of the example; you can use a more specialized template -->
  <xsl:copy-of select="." />
</xsl:template>

If maintaining document order is a priority for whatever reason…
<xsl:template match="/">
  <!-- check values of file 1 sequentially, and replace them if needed -->
  <xsl:for-each select="$forms1">
    <xsl:variable name="this"  select="." />
    <xsl:variable name="newer" select="$forms2[@name = $this/@name]" />
    <xsl:choose>
      <xsl:when test="$newer">
        <xsl:apply-templates select="$newer" />
      </xsl:when>
      <xsl:otherwise>
        <xsl:apply-templates select="$this" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:for-each>
  <!-- append any values from file 2 that are not in file 1 -->
  <xsl:apply-templates select="$forms2[not(@name = $forms1/@name)]" />
</xsl:template>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Truststore setup for gradle plugin in IntelliJ I am using a gradle plugin from a trusted artifactory. I am facing a problem that truststore is not getting picked up while running gradle build through IntelliJ.
I have tried to set it up from three below mentioned places but there is no luck:

*

*gradlew
DEFAULT_JVM_OPTS="-Djavax.net.ssl.trustStore={path to truststore}
This works from command line with command: ./gradlew build
but not from IntelliJ
Note: Using default gradle wrapper as recommended by IntelliJ

*gradle.properties
systemProp.javax.net.ssl.trustStore={path to truststore}
This also works from command line but not from IntelliJ

*Gradle JVM Options in IntelliJ

This does not work from IntelliJ
What can be the issue, any suggestions?
EDIT: gradle distribution url is also from a trusted artiactory and my hunch is that's why nothing is working.


text:
Q: Do I use a delegate or an event I have a Connection class which reads packets (commands) from a text stream and then distributes the commands to a set of handlers which process the commands as they see fit.
Eg.. Connection class reads in a command "HELLO" and then passes the command off to the handlers, where one or more handler may do something useful with the HELLO command.
Right now I use a delegate called HandleCommand which all command handlers must adhere to in order to receive the commands.
The question is, would it be more logical to use an event (eg.. CommandReceived) which the handlers could individually subscribe to? I'm having a hard time weighing up the pros and cons. it seems more wasteful to make it an event, because then an EventArgs class has to be generated for each command received.
In contrast, there is also a DisconnectCallback delegate which I strongly believe would be better as an event and will probably change.
Thank you

A: It seems your distributor now has to keep a list of handlers (class or delegates). That means you are duplicating the functionality of event.
The situation seems to call for events. It would decouple the components.
Concerning the 'wastefulness' of events and eventargs, see this question and stop worrying.

A: First - until you have evidence that it's a performance bottleneck, don't sacrifice clarity.  The GC is fast and it's unlikely cleaning up a short-lived eventargs class will be the dominating performance factor here.
Anyway, If the consumers are only going to read and not modify the data, I'd make it an event.  Otherwise you'd probably want to make an interface for a 'filter' that can read and modify, and pass the new value to the next one.

A: Events would be the most obvious approach as there are more than one command handlers.
I'm curious as to how command handlers "adhere" to a connection using delegates. You have to either simulate the event behavior by using a list of listeners or the command must actively call the handlers, what indeed compromises decoupling.

A: You are not required to use EventHandler or EventHandler<T> when creating an event, even though that is against Microsoft's recomendation. You can use your current delegate as the datatype for the event like so:
public event MyDelegateType EventName;

Edit:
If you are concerned about performance you can use an EventHandlerList class like so:
private EventHandlerList _events = new EventHandlerList();
private static object MyDelegateKey = new object()
public event MyDelegate EventName {
  add {
     _events.AddHandler(MyDelegateKey, value);
  }
  remove {
     _events.RemoveHandler(MyDelegateKey, value);
  }
}


text:
Q: How to check if an element is visible in Java Script by using its name? At the moment I can look up an element by Id and check if it's visible, like this...
this.CheckFormField = function (fieldId) {
    return ($("#" + fieldId).length > 0 && $("#" + fieldId).is(":visible"));
}

How do I achieve the same result by using the elements name?

A: To filter on attributes, you can use the [] notation. So if you want all elements with the name test, you use [name=test].
this.CheckFormField = function (fieldId) {
    return ($("[name=" + fieldId + "]").length > 0 && $("[name=" + fieldId + "]").is(":visible"));
}


text:
Q: Why are my weights after training in this strange format? I am currently trying to learn logistic regression, and am stuck on plotting a line from the weights after training. I am expecting an array of 3 values, but when I print the weights to check them, I get (with different values each time, but the same format):
[array([[ 0.42433906],
       [-0.67847246]], dtype=float32)
 array([-0.06681705], dtype=float32)]
My question, is why are the weights in this format of 2 arrays, rather than 1 array of length 3? And how do I interpret these weights so that I can plot the separating line?
Here is my code:
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.regularizers import L1L2
import random
import numpy as np

# return the array data of shape (m, 2) and the array labels of shape (m, 1)
def get_random_data(w, b, mu, sigma, m): # slope, y-intercept, mean of the data, standard deviation, size of arrays
  data = np.empty((m, 2))
  labels = np.empty((m, 1))

  # fill the arrays with random data
  for i in range(m):
    c = (random.random() > 0.5) # 0 with probability 1/2 and 1 with probability 1/2
    n = random.normalvariate(mu, sigma) # noise using normal distribution
    x_1 = random.random() # uniform distribution on [0, 1)
    x_2 = w * x_1 + b + (-1)**c * n

    labels[i] = c
    data[i][0] = x_1
    data[i][1] = x_2

  # the train set is the first 80% of our data, and the test set is the following 20%
  train_length = int(round(m * 0.8, 1))

  train_data = np.empty((train_length, 2))
  train_labels = np.empty((train_length, 1))
  test_data = np.empty((m - train_length, 2))
  test_labels = np.empty((m - train_length, 1))

  for i in range(train_length):
    train_data[i] = data[i]
    train_labels[i] = labels[i]

  for i in range(train_length, m):
    test_data[i - train_length] = data[i]
    test_labels[i - train_length] = labels[i]

  return (train_data, train_labels), (test_data, test_labels)

(train_data, train_labels), (test_data, test_labels) = get_random_data(2,3,100,100,200)

model = Sequential()
model.add(Dense(train_labels.shape[1],
                activation='sigmoid',
                kernel_regularizer=L1L2(l1=0.0, l2=0.1),
                input_dim=(train_data.shape[1])))
model.compile(optimizer='sgd',
              loss='binary_crossentropy',
              metrics=['accuracy'])

model.fit(train_data, train_labels, epochs=100, validation_data=(test_data,test_labels))

weights = np.asarray(model.get_weights())
print("the weights are " , weights)

A: The first index of the array shows the weights of coefficients and the second array shows the bias.
So you have a equation like below.
h(x) = 0.42433906x1 + -0.67847246x2 + -0.06681705
Logistic regression takes this equation and applies sigmoid function to squeeze the results between 0-1.
So if you want to draw an equation of a line, you can use do it with the returned weights like I explained above.


text:
Q: Why is Windows 10 telling me that I have 0 free space on my D: drive, when I actually have > 10 GB? Often, especially when I'm running a long-running process that uses a lot of RAM, the process will get half way through then crash because Windows thinks there's no more available disk space. Then I restart the PC to discover everything is fine, there's still more than enough space for the process to finish. Why?
Does Microsoft assume that "everyone has a 500 GB or larger hard drive these days, so we can waste as much of their space as we like"? Well I have a 6 year old MacBook Air with a 128 GB SSD, and even the newer ones only come with 256 GB.
For example: I just tried to use Deluge to download a 16 GB torrent file on to my D: drive (system partition is C: as it is on 99% of PCs) while File Explorer was showing 18 GB of free space on that drive. Giving me a theoretical wiggle room of 2 GB, right?
No other programs running at the same time, no Windows Updates dl'ing in the background (as far as I can tell), no other obvious reasons for 2 GB to be inadequate margin. Yet the download stopped at 68%. I had to restart, force re-check in Deluge and continue before it happened again at 84%!
Another restart resulted in the dl finally completing and being left with the expected 2 GB of space on D:. So why is this happening?!?! Am I missing something really obvious here because I still don't get it...and it doesn't just happen with Deluge, it happens with all sorts of programs.
Oh and BTW, don't know if this is relevant but I've never seen my system RAM usage go above 80%...not even once. I only have 4 GB but that seems to be more than enough for what I do regularly.

A: There are several reasons this happens, but the most critical piece you're missing is how downloads work.  When you are conventionally downloading a 16GB file, you may actually need 32GB free, because the file is downloaded as a "partial" download until it's complete, then it actually writes the completed download as a new file which is saved.  There are different download mechanisms, but if you watch the download progress in the folder where you're saving a conventional download, you can often see the partial download as it is marked in some way (e.g. "filename.partial").
When you are downloading Torrents, you have the additional factor that the pieces may come from different sources, and therefore be different sizes, each time you attempt the download.  So a Torrent download is more like "assembling" a file from pieces, than like a traditional download of an intact file.
The best explanation of this process that I could locate is at How Torrent Downloading works .
In addition, there are other ways that your system temporarily consumes disk space until you restart.  Most visible are just temp files that are open while given applications are open, essentially the "working files", which are often removed on closing the app.  On a Mac, there is also swap file space;  there is a discussion at Question about Mac restart freeing up disk space about this phenomenon, although not all the comments are technically correct.


text:
Q: script to find and kill windows RDS session using powershell I am working on an automation to create users for temporary session and delete them along with their home directory after a specific duration.
User creation and deletion is handled using Ansible ansible.windows.win_user module. User's home folder deletion is handled using ansible.windows.win_file module. The ansible is run from my linux server.
They are all working fine. But the home folder deletion is not working always, it fails to delete the home folder when the user is not logged out.
So, I want to forcefully kill the user session before running the delete home folder command.
I can do the function manually in powershell by getting the session ID using the following command
qwinsta | Select-String -Pattern <username>
I get the following output.
                   <username>           4  Disc
here 4 is the session id, and then I can kill the session id using the following command
rwinsta /server:servername 4
Now, I need a programmatic way to only get the session id to kill the user session. I can do the same in linux using awk command eg: qwinsta | Select-String -Pattern  | awk ('print $2') but I am not sure about similar command on windows.
To wrap up, I know the windows username and I need to forcefully log him out.

A: Split it on whitespace and pick the 2nd array element:
(-split '                   <username>           4  Disc')[1]

4

Various ways to parse qwinsta or quser:  Easier way to parse 'query user' in PowerShell (or quser)

A: why can't use logoff ?
To log off a user from a session by using the name of the session and server, for example session TERM04 on Server1, type:
logoff TERM04 /server:Server1

check this out https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/logoff
And also work using username with rwinsta also
rwinsta {<sessionname> | <sessionID>} [/server:<servername>] [/v]
rwinsta TERM04 /server:Server1

As an addon , it is better delete profile registries if you want completely delete a user profile. Else may cause temporary profile problem when the same user try login back.

A: I was able to solve the requirement by following
https://winaero.com/log-off-another-user-in-windows-10/
Type or copy-paste the following command: $sessionID = ((quser /server:'you computer name' | Where-Object { $_ -match 'user name to sign off' }) -split ' +')[2]
Will register the session ID into the variable name sessionID.
Now, execute the command logoff $sessionID.
Thank you Harikrishnan for letting me know logoff command.
Thank you js2010 for the guidance on split command .


text:
Q: Maven uses an incorrect Java version when it is executed by Jenkins I have some projects compiled and deployed with Maven and Jenkins and they have worked fine until now that I have changed the java version from 6 to 7.
In order to do this I executed the command sudo update-alternatives --config javac and changed the values of JAVA_HOME and PATH in the /etc/profile file. I have also modified the pom file so it uses jdk 1.7:
<properties>
    ...
    <jdk.version>1.7</jdk.version>
</properties>

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
        ...
        <configuration>
            <source>${jdk.version}</source>
            <target>${jdk.version}</target>
        </configuration>
</plugin>

When I execute them on the console they compile fine and the displayed version is correct:
javac -version
javac 1.7.0_55

mvn install -debug
Apache Maven 2.2.1 (rdebian-8)
Java version: 1.7.0_55
Java home: /usr/lib/jvm/java-7-openjdk-amd64/jre

However, when I do the same in a jenkins job, Maven uses the 1.6 version instead of 1.7:
javac -version
javac 1.7.0_55

mvn install -debug
Apache Maven 2.2.1 (rdebian-8)
Java version: 1.6.0_31
Java home: /usr/lib/jvm/java-6-openjdk-amd64/jre

I have also modified the maven configuration file that I use to indicate the new version, and in the Jenkins administration panel I have changed the JDK version. However, Maven is still using the 1.6 jdk.
Do you know how can I change it?

A: I found the solution here.
It is necessary to define the JAVA_HOME variable also in the global configuration of Jenkins.
As Sudharsan explained, the steps are:

*

*Go to Manage Jenkins - Configure system

*Add JAVA_HOME and its path in Global Properties - Environment Variables

A: Had a similar problem when changing Jenkins jobs from JDK 1.6 to JDK 1.8. I deleted the JDK1.6 entry from "Manage Jenkins/Configure System", leaving only JDK1.8. I expected jobs would begin using JDK1.8 but they didn't. I checked the jobs and they didn't have any JDK assignment. Restarting Jenkins didn't help either.
In the end, I noticed that by just re-Saving a job, it subsequently started using the correct JDK1.8.
(Jenkins ver. 1.602)


text:
Q: 'module' object has no attribute 'contrib' error when I train with gcloud and Tensorflow 1.15 I have launched a training job on gcloud. The cloud yaml file specifies a runtimeVersion=1.15 so I suppose that the tensorflow version launched on Google VM is 1.15 right? Training task terminates with error though that seems related to TF2. The error is:
...
File "/root/.local/lib/python2.7/site-packages/object_detection/model_lib.py", line 28, in <module>
from object_detection import exporter as exporter_lib
File "/root/.local/lib/python2.7/site-packages/object_detection/exporter.py", line 32, in <module>
slim = tf.contrib.slim
File "/usr/local/lib/python2.7/dist-packages/tensorflow_core/python/util/module_wrapper.py", line 193, in __getattr__
attr = getattr(self._tfmw_wrapped_module, name)
AttributeError: 'module' object has no attribute 'contrib'

(contrib module has moved out of TF>=2.0). Am I right when I say that TF version on VM is the bad one and if yes, how can I specify lower version (if it's not with runtimeVersion parameter in config yaml file)?
EDIT: I add the json corresponding to the training input details as seen on AI Platform dashboard:
{
  "scaleTier": "CUSTOM",
  "masterType": "standard_gpu",
  "workerType": "standard_gpu",
  "parameterServerType": "standard",
  "workerCount": "5",
  "parameterServerCount": "3",
  "packageUris": [
    "gs://mybucket/detection/train/packages/object_detection-0.1.tar.gz",
    "gs://mybucket/detection/train/packages/slim-0.1.tar.gz",
    "gs://mybucket/detection/train/packages/pycocotools-2.0.tar.gz"
  ],
  "pythonModule": "object_detection.model_main",
  "args": [
    "--train_dir=gs://mybucket/detection/train",
    "--pipeline_config_path=gs://mybucket/detection/data/faster_rcnn_resnet101_dumptruck.config"
  ],
  "region": "us-central1",
  "runtimeVersion": "1.15",
  "jobDir": "gs://mybucket/detection/train"
}

The command to launch the training was:
gcloud ai-platform jobs submit training ${JOB_ID}  \
    --job-dir=${OUTPUT_DIR} \
    --region us-central1     \
    --packages dist/object_detection-0.1.tar.gz,slim/dist/slim-0.1.tar.gz,/tmp/pycocotools/pycocotools-2.0.tar.gz
    --module-name object_detection.model_main  \
    --config object_detection/samples/cloud/cloud.yml \
    --  \
    --train_dir=${OUTPUT_DIR} \
    --pipeline_config_path=${PIPELINE_CONFIG_PATH}


text:
Q: Python str.contains function related to other columns I have a table that includes title, genre columns, and I need to change genre columns if title columns have a word blue. But the thing is I have many blue names in title, so I want to change only a specific genre type. ex:
title     genre                       title      genre
blue      x                           blue        x
red       x          ------->         red         x
blue      y                           blue        ychanged
red       y                           red         y

I used this but this function changed all genre if title has blue
df['genre'][df.title.str.contains('blue')] = 'ychanged'

How can I make a specific str.contains?

A: You can use &
df.loc[df.title.str.contains('blue') & df.genre.isin(['y']), 'genre'] = 'ychanged'

A: You can directly index the desired rows using a logical expression like:
Code:
df.loc[df.title.str.contains('blue') & (df.genre == 'y'), 'genre'] = 'ychanged'

Test Code:
df = pd.read_fwf(StringIO(u"""
    title     genre
    blue      x
    red       x
    blue      y
    red       y      """), header=1)

print(df)

df.loc[df.title.str.contains('blue') & (df.genre == 'y'), 'genre'] = 'ychanged'

print(df)

Results:
  title genre
0  blue     x
1   red     x
2  blue     y
3   red     y

  title     genre
0  blue         x
1   red         x
2  blue  ychanged
3   red         y


text:
Q: Influence of Yau's solution to the Calabi Conjecture on the field of PDEs I remember reading a long time ago(I can't recall where, unfortunately) that Yau's solution of the Calabi-Yau conjecture introduced new techniques that were very important for the field of partial differential equations.
My question is essentially two-fold: first of all, what exactly were the breakthroughs that he made, and secondly, why do they have a wide applicability to other PDEs? My background is in geometry, so I'm well-aware of the importance of the confirmation of the Calabi conjecture, but I'm interested in the analytic side here. I know that he applied the continuity method, and used some very hard a priori bounds to show closedness of the set of solutions, the openness having been proved by Calabi, but not much more.

A: Probably not quite the answer to your question,  nevertheless some historical remarks: the barrier function employed by Yau for deriving the estimates on the Laplacian was already used by Progorelov in his resolution of the Minkowski problem.
In that approach,  one reduces the Laplacian estimate to the zero order estimates, that is, to  $\sup |\phi|$. This was the missing piece in deriving the estimates.
The case of finding K\"ahler-Einstein metrics, when $c_1<0$, was in that respect easier as the first order estimates are pretty easy to derive. This was independently done by Aubin as well. But rather than the continuity method, Aubin uses a more difficult variational approach.
Yau's method for finding the zeroth order estimate was pretty involoved, which was later simplified by Kazdan and Bourguignon. Notice that if one wanted to solve the equation on a domain with boundary rather than a closed manifold, the $C^0$ estimate again comes for free.
The third order estimates are also not straightforward  to derive. The quantity, $S$, that was considered by Yau for deriving the third order bound was intorduced by Calabi in his ingenuous calculation in the case of real Monge-Amp`ere equation, and If I'm not mistaken, Yau's method for bounding $S$ using  the maximum principle to was due to Nirenberg.
The continuity method itself was already classical, know, probably since Sergej Bernstein's work.


text:
Q: Limit question where $f(x)=\sin x$ using the definition of the derivative If $f(x)=\sin x$, I am asked to evaluate the following limit to two decimal places:
$$\lim _{h\rightarrow 0}\dfrac {f\left( 2+h\right) -f\left( 2\right) } {h}$$
So far I have the following using an identity:
$$\lim _{h\rightarrow 0}\dfrac {\sin \left( 2\right) \cos \left( h\right) +\cos \left( 2\right) \sin \left( h\right) -\sin \left( 2\right) } {h}$$
Using a hint, I am still stuck:
$$\lim _{h\rightarrow 0}\left( \dfrac {\sin \left( 2\right) \left( \cos \left( h\right) -1\right) +\cos \left( 2\right) \sin \left( h\right) } {h}\right) $$

A: Hint:
$$ \lim_{x \to 0} \frac{\sin x}{x} = 1 $$
$$ \lim_{x \to 0 } \frac{\cos x- 1}{x} = 0 $$
Added:
Now, put
$$ \phi(h) = \dfrac {\sin \left( 2\right) \cos \left( h\right) +\cos \left( 2\right) \sin \left( h\right) -\sin \left( 2\right) } {h} $$
You want $\lim_{h \to 0} \phi(h) $. Notice,
$$ \phi(h) = \frac{ \sin(2) \cos(h) - \sin(2) + \cos(2)\sin(h)}{h} = \frac{ \sin(2) (\cos(h)-1)}{h} + \frac{ \cos (2) \sin (h)}{h}$$
Hence,
$$ \lim_{h\to0} \phi(h) = \sin(2) \lim_{h\to0} \frac{\cos(h)-1}{h} + \cos(2) \lim_{h\to0} \frac{\sin(h)}{h} = \sin(2) \cdot 0 + \cos(2) \cdot 1 = \cos(2) $$


text:
Q: How to style an "option" in jQuery Mobile multi-select box I've added Close as an option, then I would like to trigger it to close the dialog if clicked. In addition I would like to set "display: none" for span with class "ui-icon ui-icon-checkbox-off ui-icon-shadow", to make it look like a button.
Any advice?
http://jsfiddle.net/N5r4A/

A: To hide the check-boxes:
#select-choice-0-menu span.ui-icon {
    display: none;
}

http://jsfiddle.net/nirmaljpatel/N5r4A/7/
To close the dialog on selecting one of the options; you should REMOVE the multiple="multiple" attrib from your select tag... ie change
<select name="select-choice-0" id="select-choice-0" multiple="multiple" data-native-menu="false">

to
<select name="select-choice-0" id="select-choice-0" data-native-menu="false">

On a multi-select list; following will close the open dialog when "Close" option is clicked.
 $(function () {
  $('#select-choice-0').bind('change', function () {
      console.log('change in select', this);
      for (var i = 0; i < this.options.length; i++) {
          if (this.options[i].selected) {
              if(this.options[i].value == 'closeMe'){
                  console.log('...closing Dialog');
                  $('.ui-dialog').dialog('close');
              }
          }
      }
  });
 });

Updated jsfiddle: http://jsfiddle.net/N5r4A/10/


text:
Q: Custom UINavigationBar Image I am trying to implement a custom UINavigationBar Image background for iOS 6 but I am having no luck. All it displays is the normal one from Apple (with no back button).
I have tried the following code within viewDidLoad (One at time):
[[UINavigationBar appearance] setBackgroundImage:myImage forBarMetrics:UIBarMetricsDefault];

[self.navigationController.navigationBar setBackgroundImage:myImage forBarMetrics:UIBarMetricsDefault];

I am presenting the desired view by:
optionViewController *choose= [[optionViewController alloc] initWithNibName:@"optionViewController" bundle:nil];
UINavigationController *aNavController = [[UINavigationController alloc] initWithRootViewController:choose];
[self presentViewController: aNavController animated:YES completion:nil];

Any help would be appreciated. Thanks!

A: you can set Navigation bar Custom image like this way:-
        optionViewController *choose= [[optionViewController alloc] initWithNibName:@"optionViewController" bundle:nil];
        UINavigationController *aNavController = [[UINavigationController alloc] initWithRootViewController:choose];
        UIImage *image = [UIImage imageNamed:@"imageName"];
        [aNavController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];

        [self presentModalViewController:aNavController animated:YES]; //change here to PresentViewcontroller to presentmodelViewcontroller

here' is image:-

and in above image the Back button is not the Default one, but it's putting through programmatically.

A: Try this,
if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
    //iOS 5 new UINavigationBar custom background
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbg_ForiPhone5_Imagename.png"] forBarMetrics: UIBarMetricsDefault];
} else {
    [self.navigationController.navigationBar insertSubview:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navbg_ForOtherIphone_Imagename.png"]] atIndex:0];
}

and For info goto this link


text:
Q: Прерывается работа couroutine (Unity3d) Всем привет. Пишу Space Shooter. В скрипте Gamecontroller есть couroutine, отвечающий за респавн противников.
IEnumerator SpawnEnemies() {
    yield return new WaitForSeconds(timeBeforeSpawning);
    while(true) {
        if (currentNumberOfEnemies <= 1) {
            waveNumber++;
            waveText.text = "Волна: " + waveNumber;
            float randDirection;
            float randDistance;
            for (int i = 0; i < enemiesPerWave; i++) {
                randDistance = Random.Range (10, 25);
                randDirection = Random.Range (0, 360);
                float posX = this.transform.position.x + (Mathf.Cos ((randDirection) * Mathf.Deg2Rad) * randDistance);
                float posY = this.transform.position.y + (Mathf.Cos ((randDirection) * Mathf.Deg2Rad) * randDistance);
                Instantiate(enemy, new Vector3(posX, posY, 0), this.transform.rotation);
                currentNumberOfEnemies++;
                yield return new WaitForSeconds(timeBetweenEnemies);
            }
        }
        yield return new WaitForSeconds (timeBeforeWaves);
    }
}

В другом скрипте, который контролирует игрока, есть строчка, останавливающая выполнение couroutine, когда у игрока заканчиваются очки здоровья.
if (hp == 0)
{
    GameOverText.enabled = true;
    GameController gameController = GameObject.FindGameObjectWithTag("GameController").GetComponent("GameController") as GameController;
    gameController.StopAllCoroutines();
}

В случае, если всех противников в волне убивает лазер (стандартный сценарий их смерти), все идет хорошо. Но если хотя бы один противник разбивается об игрока, независимо от количества здоровья игрока, спавн противников прекращается.
Подскажите, плиз, куда копать?


text:
Q: How to remove the stock status in magento2 I need to remove the stock status for particular product type in admin product form.

Thanks.

A: You don't need to remove This attribute from Products.Just goto Advance Inventory Section and make Manage Stock ToNo`.

A: For remove the stock status attribute for specific product type
 $meta['product-details']['children']['container_quantity_and_stock_status']['children']['quantity_and_stock_status']['arguments']['data']['config'] = [
            'componentType' => 'container',
            'label' => __('Stock Status'),
            'visible' => false,
        ];


text:
Q: Running TensorFlow trainer with Cloud ML Engine on TPU produces google.rpc.QuotaFailure I have developed a TensorFlow model on Cloud ML Engine with scaleTier: BASIC.
Running its trainer experimentally on a GPU with scaleTier: BASIC_GPU works fine. But an attempt of running it on a TPU with scaleTier: BASIC_TPU produces this error message:
type.googleapis.com/google.rpc.QuotaFailure
The request for 1 TPU_V2 accelerators exceeds the allowed maximum
of 30 K80, 30 P100.

Where does this limitation come from and can it be lifted e.g. by enabling another API or increasing my initial budget?

A: As announced at Google Cloud Next '18, Cloud TPUs are now available to everyone, without whitelisting.
To enable them for Cloud ML Engine, go here:
https://cloud.google.com/ml-engine/docs/tensorflow/using-tpus
...scroll down to the heading "Authorize your Cloud TPU to access your project", and follow the instructions there.  In short, you need to provide IAM access of your resources to the TPU that you have created.

A: I tried the same thing and got the same result. The documentation implies that TPUs are available to everyone, but that's not the case. To the best of my knowledge, you have to specially request TPU access (I filled out the request but didn't get a response).


text:
Q: niblack thresholding I am trying to implement the niblack thresholding algorithm which uses the formula:
pixel = ( pixel >  mean + k * standard_deviation ) ? object : background

where k has standard value 0.
Could someone please tell me how to implement this in matlab? I cant figure out how to do it

A: The power of Matlab is matrix operations, so you can do a lot without a single for-loop.
The code below does what you need.
% define parameters
imgname = 'rice.png'; % matlab's image
filt_radius = 25; % filter radius [pixels]
k_threshold = 0.2; % std threshold parameter
%% load the image
X = double(imread(imgname));
X = X / max(X(:)); % normalyze to [0, 1] range
%% build filter
fgrid = -filt_radius : filt_radius;
[x, y] = meshgrid(fgrid);
filt = sqrt(x .^ 2 + y .^ 2) <= filt_radius;
filt = filt / sum(filt(:));
%% calculate mean, and std
local_mean = imfilter(X, filt, 'symmetric');
local_std = sqrt(imfilter(X .^ 2, filt, 'symmetric'));
%% calculate binary image
X_bin = X >= (local_mean + k_threshold * local_std);
%% plot
figure; ax = zeros(4,1);
ax(1) = subplot(2,2,1); imshow(X); title('original image');
ax(2) = subplot(2,2,2); imshow(X_bin); title('binary image');
ax(3) = subplot(2,2,3); imshow(local_mean); title('local mean');
ax(4) = subplot(2,2,4); imshow(local_std); title('local std');
linkaxes(ax, 'xy');

A: I would like to say upfront it is not Niblack algorithm but rather an implementation that gives better result. I don't know where this implementation will fail but I tried to binarize the above image and the result is as below.

I divided the image up into 25*25 pixels block and then used a global set mean of 90 and global set mean of 20. And then applied Otsu's binarization on small windows.
set_mean = 90
set_sd = 20
mean_block = np.mean(block)
sd_block = np.std(block)
if sd_block > set_sd:
    ret, block = cv2.threshold(block, 0, 255, cv2.THRESH_OTSU)
elif sd_block < set_sd:
    if mean_block > set_mean:
        block[:] = 255 #white
    else:
        block[:] = 0 #black
return block

If the small window's standard deviation(SD) is greater than the set one, then otsu's thresholding is used, else based on whether the mean is greater or smaller than set mean, the pixels in the window are set to complete black or white.

A: You can process the whole image:
Assuming you have three matrices: img_in, object, background
flag = img_in >  mean + k * standard_deviation;
img_out = flag .* object + (1 - flag) .* background;


text:
Q: Getting single records back from joined tables that may produce multiple records I've got a student table and an enrollment table; a student could have multiple enrollment records that can be active or inactive.
I want to get a select that has a single student record and an indicator as to whether that student has active enrollments.
I thought about doing this in an inline UDF that uses the student ID in a join to the enrollment table, but I wonder if there's a better way to do it in a single select statement.
The UDF call might look something like:
Select Student_Name,Student_Email,isEnrolled(Student_ID) from Student

What might the alternative - with one SQL statement - look like?

A: select  Student_Name,
        Student_Email,
        (select count(*)
         from Enrollment e
         where e.student_id = s.student_id
        ) Number_Of_Enrollments
 from Student e

will get the number of enrollments, which should help.

A: Why not join to a secondary select? Unlike other solutions this isn't firing a subquery for every row returned, but gathers the enrollment data for everyone all at once. The syntax may not be quite correct, but you should get the idea.
SELECT
    s.student_name,
    s.student_email,
    IsNull( e.enrollment_count, 0 )
FROM
    Students s
LEFT OUTER JOIN (
        SELECT
            student_id,
            count(*) as enrollment_count
        FROM
            enrollments
        WHERE
            active = 1
        GROUP BY
            student_id
    ) e
ON s.student_id = e.student_id

The select from enrollments could also be redone as a function which returns a table for you to join on.
CREATE FUNCTION getAllEnrollmentsGroupedByStudent()
RETURNS @enrollments TABLE
(
    student_id       int,
    enrollment_count int
) AS BEGIN
    INSERT INTO
        @enrollments
    (
        student_id,
        enrollment_count
    ) SELECT
        student_id,
        count(*) as enrollment_count
    FROM
        enrollments
    WHERE
        active = 1
    GROUP BY
        student_id

    RETURN
END

SELECT
    s.student_name,
    s.student_email,
    e.enrollment_count
FROM
    Students s
JOIN
    dbo.getAllEnrollmentsGroupedByStudent() e
ON  s.student_id = e.student_id

Edit:
Renze de Waal corrected my bad SQL!

A: Try someting like this:
SELECT Student_Name, Student_Email, CAST((SELECT TOP 1 1 FROM Enrollments e WHERE e.student_id=s.student_id) as bit) as enrolled FROM Student s

I think you can also use the exists statement in the select but not positive

A: try to avoid using udfs or subqueries, they are performance killers. banjolity seems to havea good solution otherwise because it uses a derivd table instead of a UDF or subselect.

A:   select students.name,
decode(count(1), 0, "no enrollments", "has enrollments")
     from students, enrollments
     where
       students.id = enrollments.sutdent_id and
       enrollments.is_active = 1 group by students.name

Of course, replace the decode with a function your database uses (or, a case statement).


text:
Q: repeat a Julia iterator indefinitely I'm looking for a way to repeat indefinitely a sequence.
Something comparable to
julia> repeat(1:3, outer=2)
9-element Array{Int64,1}:
 1
 2
 3
 1
 2
 3

but with outer being infinite and with result being an iterator (not an Array)
I tried
for i in repeatedly([1:3])
    @show i
end

with repeatedly for IterTools
but it raises an error.

A: On version 0.6 and up, you can use Base.Iterators.cycle. For example:
julia> using Base.Iterators

julia> collect(take(cycle(1:3),10))
10-element Array{Int64,1}:
 1
 2
 3
 1
 2
 3
 1
 2
 3
 1


text:
Q: MySQL read-buffer-size overflow What will happen if a low value was assigned in my.cnf to any of the per-thread buffers, when it fills?
I'm thinking of possible scenarios:

*

*MySQL will gracefully call realloc for additional block with the same size.

*A buffer overflow, causing thread to terminate

*Unexpected behaviour, like incorrect sort (if sort-buffer-size is filled during the process)


text:
Q: Pull out href's with beautifulsoup attrs I am trying something new with pulling out all the href's in the a tags. It isn't pulling out the hrefs though and cant figure out why.
import requests
from bs4 import BeautifulSoup

url = "https://www.brightscope.com/ratings/"
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')

for href in soup.findAll('a'):
    h = href.attrs['href']
    print(h)

A: You should check if the key exists, since it may also not exist an href between <a> tags.
import requests
from bs4 import BeautifulSoup

url = "https://www.brightscope.com/ratings/"
page = requests.get(url)
print(page.text)
soup = BeautifulSoup(page.text, 'html.parser')

for a in soup.findAll('a'):
    if 'href' in a.attrs:
        print(a.attrs['href'])


text:
Q: Discord permission check not working dsicord js For some reason when i try to use my command it keep giveing me this error. the error and the code is listed below. i tried fixing it nothing seems to fix it
const Discord = require("discord.js");

module.exports = {
    name: 'clear',
    aliases: ['purge'],
    discription: "clears messages",
    async execute(message, args, client) {
        if (!message.member.hasPermission('MANAGE_MESSAGES')) return message.reply('You do not have permissions to use this command')
        if (!args[0]) return message.reply(`Please specify a amount of messages to delete (1-99)`)
        if (isNaN(args[0])) return message.reply(`Please enter a number`)
        if (parseInt(args[0]) > 99) return message.reply(` The max amount of messages you may delete is 99`)

        await message.channel.bulkDelete(parseInt(args[0]) + 1)
            .catch(err => console.log(err))
        message.channel.send(`deleted ${args[0]} messages`).then(m => m.delete({ timeout: 5000 }))
    }
}

PS C:\Users\lolzy\OneDrive\Desktop\discordbot> node .
Cbs slave is online!
(node:10108) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hasPermission' of undefined

A: try this:
const Discord = require("discord.js");

module.exports = {
    name: 'clear',
    aliases: ['purge'],
    discription: "clears messages",
    async execute(client, message, args) {
        if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel,send('You do not have permissions to use this command')
        if (!args[0]) return message.reply(`Please specify a amount of messages to delete (1-99)`)
        if (isNaN(args[0])) return message.reply(`Please enter a number`)
        if (parseInt(args[0]) > 99) return message.reply(` The max amount of messages you may delete is 99`)

        await message.channel.bulkDelete(parseInt(args[0]) + 1)
            .catch(err => console.log(err))
        message.channel.send(`deleted ${args[0]} messages`).then(m => m.delete({ timeout: 5000 }))
    }
}


text:
Q: Why does setState take a closure? What's the benefit of having setState() accept a function just to immediately call it and then request rebuild? In particular, what's the advantage over having users explicitly call a "rebuild" type function?

A: When Flutter had a "markNeedsBuild" function, developers ended up just sort of calling it at random times. When the syntax switched to setState(() { ... }), developers were much more likely to use the API correctly. They are functionally equivalent from the machine's point of view, but they seem to evoke different code from developers.
If you follow the convention of only mutating member variables inside a setState closure, you'll avoid a situation you're refactoring some code and accidentally remove the call to setState, or call setState unnecessarily. And if your State is unmounted, Flutter can fail an assertion so you know something is wrong as soon as you begin trying to mutate members, instead of at the end.
Eventually there will probably be an analyzer warning enforcing that setState is always called when mutating members of a State, so any member variable mutation that happens outside of initState or a setState callback will be flagged as suspect.
If you're just getting started with state in Flutter, check out the Flutter widgets tour. I've found that a lot of cases where I was calling setState can be handled more elegantly with FutureBuilder, StreamBuilder, AnimatedWidget, or AnimatedBuilder, so don't forget to consider those alternatives if you find yourself calling setState a lot.
Adam Barth and Yaroslav Volovich contributed to this question/answer.

A: To complete Colin's answer, it also ensures that you call setState at the right moment when dealing with asynchronous function.
Mutating your state outside of the callback can lead to an easy mistake:
function() async {
  setState(() {});
  myState = await future;
}

This causes a problem because if your future doesn't finish synchronously, the build method will be called before the state is mutated.
By using the callback you are forced to do the following:
function() async {
  final value = await future;
  setState(() {
    myState = value;
  });
}

This time, it doesn't cause problems because the future is awaited before the setState.
Can't I make an async callback and still have the issue?
No. Because setState method internally check that the callback does not return a future. And if it does, it will throw.
So the following is impossible:
setState(() async {
  myState = await future;
});


text:
Q: Need to store data in app for sorting I am working on an app which will give you all the businesses in a certain location.
when the user does a search on "naperville" , the app will receive a json file with:
business names, type of business, phone #, zip code
the user can then do further sorting on this information, such as: give me only restraunts.
what is the best approach to store this data in the app? My idea is using 3 hashmaps , example:
Hashmap1: "business name" is key and "type of business"  is value
Hashmap2: "business name" is key and "phone #"  is value
Hashmap3: "business name" is key and "zip code"  is value
This way, I can link all the information just like in a database table."business name" works as a primary key.
because I am a new programmer, I don't know what is the best approach…
if my approach is not good, can you recommend something better ?

A: You should define an object Business containing name, type, phoneNumer, etc.
Have a single HashMap mapping name to Business or even a non mapping collection like a List or a Set depending on the behaviour you need.
You will probably want a more sophisticated search function though, for example based on distance from a certain point, etc. For those sort of things you are much better off looking for existing tools to handle it rather than trying to write your own.


text:
Q: SCSS change atribute of element based on sibling's child Is there some way how to check if sibling's child has some class and stay in current element?
E.g.:

If element "child" has class "expand" I wanna change e.g color of all elements "element".

A: Currently the only way to do it with SCSS is with :has(), which as mentioned is not well supported yet. At the time of answering, it's only Firefox, Firefox for Android and Samsung Internet that do not support it (according to MDN).
It would look like this:
.element:has(.expand) {
  color: red;
}

A: You can't do that directly in SCSS because it's a preprocessor language with no access to the DOM. To accomplish this, you would need to use JavaScript.


text:
Q: Show the element if it has a class whose name is tested I got a class name after I clicked a element in the document. And then I want to select all elements that has this selected class. For example;
$('.tabs1 li a').hover(function(){

var clicked = $(this).attr("class");

// this doesnt work
$('a[class="clicked"]').css("display","block");

});

A: You can build a class selector from the class name:
var clicked = $(this).attr("class");
$("a." + clicked).css("display", "block");

A: It's true that the class attribute can have multiple values. Like others, I'm guessing to an extent what the poster wants, but this at least allows for multiple classes (and accounts for spaces). If the poster's wanting to isolate just one of the classes, maybe that's another question or subquestion:
$('.tabs1 li a').hover(function(){
    var clicked = $(this).attr("class");
    clicked = clicked.replace(/(\s)+/g, '.');
    // this should work
    $('a.' + clicked).css({"display":"block", "background": "green"});
});

http://jsfiddle.net/szpJb/2/


text:
Q: ClassNotFoundException on Guava I'm getting a error
java.lang.ClassNotFoundException: com.google.common.net.InternetDomainName

when trying to run the following code:
private String getTopPrivateDomain(String url) {
   return InternetDomainName.from(url).topPrivateDomain().toString();
}

I have downloaded guava-18.0.jar and I have triple-checked that it exists in my build-path. I have also imported com.google.common.net.*. I get no errors or warnings in Eclipse and the program compiles fine, but it throws the above exception when the method is run.
I don't understand why it cannot find that class when it's clearly imported and in the build-path?

A: The jar isn't in the classpath location when it's being ran, but it is configured in Eclipse. If you're using Tomcat or something like that it'll need to be in a /lib directory


text:
Q: Git commit 500 files at a time? I have thousands of files that I need to commit but I'm having problems committing them all at once. How can I commit 500 files at a time automatically? The first 500 files should have the commit message "Initial commit part 1", the next 500 should say "Initial commit part 2", and so on. I am using Windows, if that matters.

A: I don't see anything in the git documentation about adding a certain number of files. If that's possible, that would be cool.
What you could do is break up your commit into smaller commits, in a couple of different ways that might be more meaningful than an arbitrary number.
You could commit all the files with a certain extension:
$ git add *.rb
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   a.rb
        new file:   b.rb
        new file:   y.rb
        new file:   z.rb

You could commit files by directory:
$ git add first_dir/

Or (least meaningful), you could commit all the files from the first half of the alphabet (following up with the second half):
$ git add [a-j]*
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   a.rb
        new file:   b.rb

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        y.rb
        z.rb

There are lots of ways to break up a big commit-- whichever is most logical for your files is what I'd recommend.

A: If you are looking to use a command line style commit I recommend looking at janos' answer here. This should do it all in a single commit but it would give you a good base if want them to be separated. This site has a good description of how to use git commands if you do need them to be separate commits.
However if you use the desktop client you should be able to commit all of them at once, I know I have done a single commit of around 1000 files using it.


text:
Q: How to deploy a spring boot application jar from Jenkins to an EC2 machine I'm seeing so many different sources how to to achieve CI with Jenkins and EC2 and strangely none seem to fit my needs.
I have 2 EC2 ubuntu instances. One is empty and the other has Jenkins installed on it.
I want to perform a build on the Jenkins machine and copy the jar to the other ubuntu machine. Once the jar is there i want to run mvn spring-boot:run
That's is - a very simple flow which i can't find a good source to follow that doesn't include slaves, dockers etc..

A: AWS Code Deploy lets you use a Jenkins and deploy it on your EC2 instances.
Quick google search gave me this very detailed instruction on how to setup code pipeline with AWS Code Deploy.
The pipeline uses GitHub -> Jenkins -> EC2 flow, as you need it.

A: Set up jenkins to do a build then scp the artifact to the other machine
There's an answer here how to setup ssh keys for jenkins to publish via ssh about setting up the keys for ssh


text:
Q: Create separate session for rails admin login I'm using Rails 4.2.1 and Devise and rails_admin and I'm quite new to Rails.
I need to add rails admin to my project. I need a separate login For rails admin. (I don't want to add a new column user for that. As admin and normal users are different) For that I added a new model Admin. I used devise for creating views and models. But now I need to add routes in routes for admin user having only sign in feature(No need for registration). Now I have all those features(registration,...). I also need a separate session apart from the user session. As I logout user, adminuser is also logging out.

A: To get seperate session please make changes in devise.rb
config.sign_out_all_scopes = false


text:
Q: TypeScript is not ignoring node_modules library I am working on a react project, react version 15.4.2 .. it's an existing project and I need to have it on the same react version. I also have a tsconfig file. I tried to use react material ui:
npm install material-ui@v1.0.0-beta.47 --save

When I try to start the server, I get errors such as:

[17:00:59] Error - typescript -
  node_modules\csstype\index.d.ts(14427,101): error TS1005: ')'
  expected. [17:00:59] Error - typescript -
  node_modules\csstype\index.d.ts(14439,89): error TS1005: ',' expected.
  [17:00:59] Error - typescript -
  node_modules\csstype\index.d.ts(14451,89): error TS1005: ',' expected.
  [17:00:59] Error - typescript -
  node_modules\csstype\index.d.ts(14463,65): error TS1005: '(' expected.
  [17:00:59] Error - typescript -
  node_modules\csstype\index.d.ts(14463,107): error TS1005: ')'
  expected. [17:00:59] Error - typescript -
  node_modules\csstype\index.d.ts(14475,74): error TS1005: ',' expected.
  [17:00:59] Error - typescript -
  node_modules\csstype\index.d.ts(14487,55): error TS1005: '(' expected.
  [17:00:59] Error - typescript -
  node_modules\csstype\index.d.ts(14487,92): error TS1005: ')' expected.
  [17:00:59] Error - typescript -
  node_modules\csstype\index.d.ts(14499,77): error TS1005: ',' expected.
  [17:00:59] Error - typescript -
  node_modules\csstype\index.d.ts(14512,67): error TS1005: '(' expected.

Here's my tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "forceConsistentCasingInFileNames": true,
    "module": "commonjs",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "typeRoots": [
      "./node_modules/@types"
    ],
    "types": [

    ],
    "lib": [
      "es5",
      "es6",
      "dom",
      "es2015.collection"
    ]
  },
  "exclude": [
    "./node_modules/*"
    ]
}

I tried everything, using exclude, or adding es6 as a lib, and even using an empty types array in tsconfig.
Any idea?


text:
Q: How clean a part of the console? I have a problem, I to need clean part of the screen instead of all.
For example:
#include <iostream>
using namespace std;
int main ()
{
    string name, city;
    int age;
    cout<<"Enter your name"<<endl;
    cin>>name;
    cout<<"Enter your age"<<endl;
    cin>>age;
    cout<<"Enter your city"<<endl;
    cin>>city;
    cin.get();
    cin.get();
    return 0;
}

Suppose the user enter a number in the city variable, I can create a condition If to clean the screen, but I don't want to clean everything, only the last part.

A: You can't change unix-shell ui from C++
(actually you can but trust me you don't want to deal with it)
if you want to write some UI using C/C++ check GTK.
and for your particular case I guess cleaning all the screen and repainting some texts will be enough.

A: You can clear the last line only, in most teminals, by printing the character '\r'.  This is the ASCII carriage return, which historically made the head of a teletype machine move back to the left.
Another option is to clear the screen with '\L' and reprint the parts you want to stay on the screen.  Unless you're on a very slow connection, there won't be noticeable flicker.


text:
Q: R dplyr heatmap dealing with missing values so I have run into a minor issue with drawing heat maps using geom_tile() and dplyr package. I assume that it is a simple solution, but I have not been able to find the answer anywhere yet. Apologies if there is one out there and I just missed it.
So the following code is for a trivial example:
Trivial <- tibble(
  Name1 = c("a","b","c"),
  Name2 = c("x","y","z"),
  Value = c(1,2,3)
)
Trivial %>%
  ggplot(aes(Name1, Name2)) +
    geom_tile(aes(fill = Value)) +
    scale_fill_gradient(low = "white", high = "green")

The heat map produced by this shows grey/blank space where there is no information for those combinations of Name1 and Name2. Is there a way of instead of showing blank space I could fill it with white (or any other colour)? Alternatively, could I put a "NA" on the plot to show that those blank spaces are indeed meant to be blank?
I have tried using the na.value argument in scale_fill_gradient, but it does not work. I assume since there are no NAs in the table. However, I think that could be a way forward. I will keep experimenting, but any help would be greatly appreciated!
Thank you!

A: Or you can just add them_classic().
Trivial %>%
    ggplot(aes(Name1, Name2)) +
    geom_tile(aes(fill = Value)) +
    scale_fill_gradient(low = "gray", high = "green") +
    theme_classic()

I just used low= "gray" because background is white.
You can change also the background :
Trivial %>%
    ggplot(aes(Name1, Name2)) +
    geom_tile(aes(fill = Value)) +
    scale_fill_gradient() +
    theme_classic() +
    theme(panel.background = element_rect(fill = "white", colour = "white"))

A: You can use expand() from tidyr to get all combinations of Name1 and Name2 and then fill all NA with 0 and then plot the heatmap:
library(tidyr)
Trivial %>% expand(Name1, Name2) %>%
  left_join(Trivial, by = c("Name1", "Name2")) %>%
  mutate( Value = ifelse(is.na(Value), 0, Value)) %>%
  ggplot(aes(Name1, Name2)) +
  geom_tile(aes(fill = Value)) +
  scale_fill_gradient(low = "white", high = "green")

The result looks like this:


text:
Q: CSS - IE7 ignoring margin on first list item? If you go to the first blog item (Mona) and expand it using the '+' icon. The image thumbnails are aligned 24px from the left using a margin. This works in every browser but IE7 which ignores the margin on the first list item.
http://www.dririser.co.uk/index.php
CSS
.artistMeta li {
float: left;
margin: 0 0 24px 24px;
position: relative;
width: 160px;
}

There is a similar question on here but the there was no real answer and I can't use their solution.
Why is ie7 ignoring the left-margin on my first list item (only)?
Any ideas?

A: just a quick test.. not sure if it will work.. but try adding a display:block on your li and don't use the shorthand for the margin, instead use margin-left and margin-bottom...
it seems to me that IE is not refreshing the style of the elements, because when i inspect the elements, the navigator adds the correct margins...
If that doesn't work.. you might want to put the style inside the tag (since you're using JS to add the images), i know it's not elegant, but i guess that could force the navigator to set the style on the li
and if that doesn't work.. then i've no idea what could be wrong =P. I hope this helps...
Good Luck!

A: The problem IE7 is having here isn't in your CSS file, it's in your javascript in global.js. Specifically the following line ...
$(".artistMeta > li:nth-child(3n+1)").addClass("articleSlideOdd");

As per the convention in CSS, JQuery starts the child count at 1 for nth-child (as in the first child is nth-child(1)), where as, ie7 is expecting it to start at 0. So with ie7 3n+1 matches the 2nd, 5th, 8th item and so on.
Looks like JQuery isn't handling ie7 properly, so you'll need two statements to cover ie7, and everything else.


text:
Q: how change color of cite my code is \cite{chang2001}.
and
@article{chang2001,
  title={Training v-support vector classifiers: theory and algorithms},
  author={Chang, Chih-Chung and Lin, Chih-Jen},
  journal={Neural computation},
  volume={13},
  number={9},
  pages={2119--2147},
  year={2001},
  publisher={MIT Press}
}

and the result is color blue, i need color black

and configuration is
\usepackage[utf8]{inputenc}

\renewcommand{\refname}{Bibliografía} % Bibliografía en español
    \addcontentsline{toc}{chapter}{Bibliografía} % Agrega la bibliografía al Índice.
    \bibliographystyle{apalike} % formato APA

    \bibliography{perifericos/bibliografia}

A: *

*Package hyperref has an option hidelinks to hide the links from the user (no visual markup).

*The color of link categories can be changed with options linkcolor, filecolor, urlcolor, citecolor, ..., if option colorlinks is used. The color of rectangles around links are changed with linkbordercolor, linkfilecolor, ..., see the hyperref manual.

A: Try this:
\usepackage{color}

\usepackage{hyperref}
\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    urlcolor=red,
    linktoc=all,
    citecolor=black
           }


text:
Q: Does it make a difference to change the order of JOIN ON condition? Assume that I have a table EMPLOYEES that has 100,000 rows.
And I have DEPENDENTS table which has 200,000 rows.
I can obtain a list of all dependents with their relation from employees table (EMPLOYEES has a column EMP_ID which is a foreign key in DEPENDENTS with the name PARENT_EMP_ID).
SELECT
    D.FIRST_NAME,
    D.LAST_NAME,
    E.EMPLOYEE_NAME AS DEPENDENT_OF
 FROM
    DEPENDENTS D
    LEFT JOIN EMPLOYEES E ON D.PARENT_EMP_ID = E.EMP_ID

My question is:
Would it make any difference if I joined the table like this:
...
FROM DEPENDENTS D
LEFT JOIN EMPLOYEES E ON D.PARENT_EMP_ID = E.EMP_ID

versus:
...
FROM DEPENDENTS D
LEFT JOIN EMPLOYEES E ON E.EMP_ID = D.PARENT_EMP_ID

Notice, that I have changed the order of the condition, preserving the order of the tables themselves since I need all rows from dependents (not caring if I get duplicates from EMPLOYEES table).

A: Any logical join would be converted to one of the below physical join..

*

*nested loops

*hash join

*merge join

For all the above physical joins,each is implemented differently and changing clause like the way you changed doesn't matter
for the below join you have..
E.EMP_ID = D.PARENT_EMP_ID

if we assume ,SQL picked hash join for your query..in this case sql chooses table which has less rows as the build table and it will use this table to probe into other table..
even though you change joins ,it doesn't matter

A: NO,there will be no change at all because the elements of table DEPENDENTS are being compared to the elements of table EMPLOYEES keeping DEPENDENTS table as the base table in both the cases, so the order of the condition does not matter.But if the order of the base table is changed than the results will differ for both the cases.


text:
Q: How to set toolbar title and subtitle in centre In my case I want to set toolbar title and subtitle in centre. I have already one solution to set custom layout in toolbar. Is that any other solution to set toolbar title and subtitle without using custom layout?
Solution 1:
<android.support.v7.widget.Toolbar
    android:id="@+id/custom_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/actionBarSize"
    android:background="@android:color/holo_red_dark">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="abc"
        android:textColor="@android:color/white"
        android:textSize="20sp"
        android:layout_marginRight="?android:attr/actionBarSize"
        android:gravity="center"/>

    </android.support.v7.widget.Toolbar>

I don't want to use custom layout to set toolbar title and subtitle.I appreciate your effort, in advance.

A: <android.support.v7.widget.Toolbar
    android:id="@+id/custom_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/actionBarSize"
    android:background="@android:color/holo_red_dark">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="abc"
        android:textColor="@android:color/white"
        android:textSize="20sp"
        android:layout_marginRight="?android:attr/actionBarSize"
        android:gravity="center"/>

</android.support.v7.widget.Toolbar>


text:
Q: How do I add a menu item to the "Drop down menu" of auiToolbar in wxPython? Toolbar Picture How can I do that? Please show me an code example.
I tried to add menu items through wxFormBuilder, but wxFormBuilder crashes when generating Python code, just after adding items to "Drop down menu".


text:
Q: Differences between iPhone OS v2 and v4? Can any one say difference between the iPhone OS 2+ till 4 and what's the main difference in the OS as well as the development in xcode..
Thanks

A: For the difference between the versions go to http://developer.apple.com/iphone/library/navigation/index.html#section=Resource%20Types&topic=Release%20Notes and see the Documents called iOS x.x API Diffs

A: In Release notes section of iOS Reference Library you can find "API diffs" docs for every iOS version starting from 2.1.

A: The answer of this question should be very much in detail but may be following my answer in other post will help you to understand how apple world is working:
Are there any Hardware Requirements to test iPhone Apps on your iPhone


text:
Q: Baikal Folder not Found I tried to install baikal. Works perfectly, configuration, the website perfect. But when I try to get my books I get this error:
2016/12/24 10:21:40 [error] 6440#0: *7 "/var/www/mail/dav/html/dav.php/addressbooks/index.html" is not found (20: Not a directory), client: 46.223.1.8, server: dav.mailgermania.de, request: "GET /dav.php/addressbooks/ HTTP/1.1", host: "dav.mailgermania.de", referrer: "https://dav.mailgermania.de/dav.php"

This is my nginx config
server {
  listen 80;
  listen [::]:80;
  server_name dav.mailgermania.de
  server_tokens off;
  root /var/www/mail/dav/html;
  return 301 https://$host$request_uri;
}
server {
  listen 443;
  listen [::]:443;
  server_name dav.mailgermania.de
  server_tokens off;
  ssl on;
  ssl_certificate /etc/ssl/mail/mail.crt;
  ssl_certificate_key /etc/ssl/mail/mail.key;
  ssl_prefer_server_ciphers on;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-  GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
  ssl_dhparam /etc/ssl/mail/dhparams.pem;
  add_header Strict-Transport-Security max-age=15768000;
  ssl_session_timeout 30m;
  client_max_body_size 25m;
  root /var/www/mail/dav/html;
  index index.html index.htm index.php;

  add_header X-Frame-Options "SAMEORIGIN";
  add_header Content-Security-Policy "frame-ancestors 'self';";
  add_header X-Content-Type-Options nosniff;
  add_header X-XSS-Protection "1; mode=block";

  rewrite ^/.well-known/caldav /dav.php redirect;
  rewrite ^/.well-known/carddav /dav.php redirect;

  charset utf-8;

  location ~ /(.ht|Core|Specific) {
    deny all;
    return 404;
  }

  location ~ .php$ {
    include fastcgi_params;
    fastcgi_split_path_info ^(.+.php)(/.+)$;
    fastcgi_pass unix:/var/run/php-mail-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param HTTPS on;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_read_timeout 630;
    fastcgi_keep_conn on;
  }
}

I do not know what this error means, maybe you could help me?
Thanks for help
Update
I changed my php block like this:
  location ~ ^(.+\.php)(.*)$ {
try_files $fastcgi_script_name =404;
include        /etc/nginx/fastcgi_params;
fastcgi_split_path_info  ^(.+\.php)(.*)$;
fastcgi_pass   unix:/var/run/php5-fpm.sock;
fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
fastcgi_param  PATH_INFO        $fastcgi_path_info;
fastcgi_index index.php;
fastcgi_param HTTPS on;
fastcgi_read_timeout 630;
fastcgi_keep_conn on;
}

Now it works. Thanks.

A: You want to add a try_files block to your PHP handling location:
location ~ .php$ {
  try_files $uri $uri/ $uri/index.php;
  ...
}

This will give nginx a list of different things to try as it tries to locate the correct URI to run.


text:
Q: How to structure Meteor app and load into Meteor shell I'm having a number of issues putting together a very simple piece of code as I learn Meteor. See the comments, which are questions.
server/main.js
import { Meteor } from 'meteor/meteor';

import { Post } from './schema'
// Why is this required to make Post available in Meteor.startup?
// Isn't there auto-loading?

Meteor.startup(() => {
    console.log(Post)
    // This works, but why isn't Post available to meteor shell?
});

server/schema.js
import { Post } from './models/post'
export { Post }

server/models/post.js
import { Class } from 'meteor/jagi:astronomy';
// Why can't this be imported elsewhere, like main.js?

const Posts = new Mongo.Collection('posts');
const Post = Class.create({
  name: 'Post',
  collection: Posts,
  fields: {
    title: { type: String },
    userId: String,
    publishedAt: Date
  },
});

export { Post }

In addition to these questions, how can I load my app into meteor shell? Post is undefined there, even though it's defined in Meteor.startup. I tried using .load with an absolute path, but this breaks my app's imports, which use relative paths.
As for which errors I'm confused about:

*

*When I try and use import inside Meteor.startup(), I get an error that the keyword import is undefined. I'm using the ecmascript package.

*When I don't import { Class } in the same file where I use Class, I get an unknown keyword error.

*If I don't import { Post } in main.js, then Post is undefined.

*Not able to load app into Meteor shell.

A: To access exported objects in Meteor shell, use require:
> require('server/schema.js').Posts.findOne();

To access objects exported by packages, use the package name:
> require('react').PropTypes;

The reason you can't access an object that's imported by another js file is that each file has its own scope here. When Meteor builds your app, it doesn't just concatenate js files like many other build systems do, and that's really a good thing.
Basically a Javascript object gets created for every js file you write. Anything you export in a js file becomes a field in this object which you can access by using require. And import is just a nicer version of the same thing.


text:
Q: Render view from nancy bootstrapper? Is it possible to render a view outside of a NancyModule? For example, I want to be able to render a view in an error pipeline like so:
public class MyBootstrapper: DefaultNancyBootstrapper
{

    protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
    {
        pipelines.OnError += ((ctx, e) =>
        {

            if (context.Request.Headers.Accept.Any(c => c.Item1.Equals("text/html")))
            {
                // Render view using e here
            }

        });
    }
}

A: Solved it by extracting the ViewFactory from the container:
public class MyBootstrapper: DefaultNancyBootstrapper
{

    protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
    {
        pipelines.OnError += ((ctx, e) =>
        {

            if (context.Request.Headers.Accept.Any(c => c.Item1.Equals("text/html")))
            {
                 IViewFactory viewFactory = container.Resolve<IViewFactory>();
                 return viewFactory.RenderView("Error", new {Message = ex.Message}, new ViewLocationContext() { Context = context, ModuleName = "", ModulePath = "" });
            }

        });
    }
}

No idea if the blank ModuleName & ModulePath will break anything, but it seems to work.


text:
Q: Model objects are null in jsp I am using Spring Framkework 4.1.6.RELEASE.
I have a Rest Controller and an ordinary controller.
The ordinary controller adds an object to the model, but this object is not there in the jsp.
What am I doing wrong?
I tried two different methods:
@Controller
@RequestMapping(value = "/mymapping")

public class StatusController {

    private Log LOG = LogFactory.getLog(StatusController.class);

    @RequestMapping(method = GET)
    public ModelAndView myMethod1(final HttpServletRequest aRequest, final HttpServletResponse aResponse) {

        ModelAndView tempMAV = new ModelAndView("myjsp");
        tempMAV.addObject("test","test");
        return tempMAV;
    }

    @RequestMapping(method = GET, value="2")
    public String method2(Model model) {
        model.addAttribute("test","test");
        return "myjsp";
    }
}

In method 1 the jsp is displayed but the variable "test" is not filled.
test: ${test}

With method 2 I get a 404, the jsp myjsp is not found because the path
http://localhost:{...mypath...}/mymapping/WEB-INF/jsp/myjsp.jsp

does not exist.
In my pom.xml I added:
<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>javax.servlet.jsp.jstl-api</artifactId>
</dependency>

My servlet contains:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

My jsp starts with:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:c="http://java.sun.com/jsp/jstl/core" version="2.0">
<jsp:directive.page language="java"
    contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>My Title</title>
</head>
<body>

<p> test: ${test}</p>

edit
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

<display-name>My display name</display-name>
<filter>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<!-- Expose request to current thread (required for session and request-scoping) -->
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

<servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            WEB-INF/config/spring-mvc-servlet.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

</web-app>

When I change my servlet content to:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
        </map>
    </property>
    <property name="viewResolvers">
        <list>
            <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
                <property name="viewClass"
                    value="org.springframework.web.servlet.view.JstlView" />
                <property name="prefix" value="/WEB-INF/jsp/" />
                <property name="suffix" value=".jsp" />
            </bean>
        </list>
    </property>
</bean>

then at least method 2 works again, which means it shows the jsp, but still the variable test is not filled.

A: In your Config change the prefix to "/WEB-INF/jsp/":
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

You shoud access to your controller before:
@Controller
@RequestMapping(value = "/mymapping")
public class StatusController {

    private Log LOG = LogFactory.getLog(StatusController.class);

    @RequestMapping(value = "/method1", method = GET)
    public ModelAndView myMethod1(final HttpServletRequest aRequest, final HttpServletResponse aResponse) {

        ModelAndView tempMAV = new ModelAndView("myjsp");
        tempMAV.addObject("test","test");
        return tempMAV;
    }

    @RequestMapping(value = "/method2",method = GET)
    public String method2(Model model) {
        model.addAttribute("test","test");
        return "myjsp";
    }
}

To access to method1 Try with the following URL:
http://localhost:port/contextPath/mymapping/method1

A: For your 2nd Controller method, do it this way :
@RequestMapping(value = "/method2",method = GET)
    public String method2(Model model) {
        model.addAttribute("test",new ObjectName());
        return "myjsp";
    }

You must understand that addAttribute is used for binding, so you can add Model classes and other stuff. Try it out.

A: GUISSOUMA Issam suggested to use UrlBasedViewResolver:
<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

This helped to make method2 work.
Additionally, I added the following code to my web.xml, which made the variables be filled:
<servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
        <param-name>fork</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>xpoweredBy</param-name>
        <param-value>false</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>/WEB-INF/jsp/*</url-pattern>
</servlet-mapping>

What I still don't unterstand is why I need to add the JspServlet configuration to the web.xml in this specific case. In two other projects of ours I saw the same controller methods etc. without the declaration of JspServlet in web.xml and it does work without it.


text:
Q: How can I clear previous values of the combobox Private Sub ComboBox1_SelectedIndexChanged_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

    lblbrand.Text = ComboBox1.SelectedValue.ToString()
    strb = lblbrand.Text

    connetionString = "Data Source=HRS\SQLEXPRESS;AttachDbFilename='E:\My project\forms\1\1\mobile shop management.mdf';Integrated Security=True"
    con = New SqlConnection(connetionString)
    con.Open()
    command = "select Model_id from mob where Brand ='" & lblbrand.Text & "'"
    cmd = New SqlCommand(command, con)
    Dim rd As SqlDataReader = cmd.ExecuteReader()
    If rd.HasRows = True Then
        While rd.Read()
            ComboBox2.Items.Add(rd("Model_id"))
        End While
    End If

End Sub

A: Simple:
ComboBox2.Items.Clear()


text:
Q: EF4 inheritance and Stored procedures I implemented inheritance with a discriminator field so all my records are in the same table. My basetype is Person (also the name of the table) and Driver and Passenger inherit from it. I receive instances of the correct type (Driver and Passenger) when I perform a query on the object context to Person. example:
var q = from d in ctx.Person
        select d;

But I also create a function that calls a stored procedure and mapped the output of the function to the type Person. But now I get a list of Person and not Drivers or Passengers when I execute this method.
Anybody an idea how to solve this or is this a bug in EF4?

A: AFAIK, you can't use discriminator mapping (e.g TPH) when dealing with stored procedure mappings.
The stored procedure must be mapped to a complex type or custom entity (e.g POCO), the mapping cannot be conditional.
What you could do is map it to a regular POCO, but then project that result set into the relevant derived type (manual discrimination).
E.g:
public ICollection<Person> GetPeople()
{
   var results = ExecuteFunction<Person>(); // result is ObjectResult<Person>
   ICollection<Person> people = new List<Person>();

   foreach (var result in results)
   {
      if (result.FieldWhichIsYourDiscriminator == discriminatorForDriver)
      {
         people.Add((Driver)result);
      }

      // other discriminators
   }

}

If your always expecting a collection of one type (e.g only Drivers), then you wouldn't need the foreach loop, you could just add the range. The above is in case you are expecting a mixed bag of different people types.
Would be interested to see other answers, and if there is a better way though - but the above should work.


text:
Q: How to use VBA to copy 5 sheets paste to 1 new workbook by appending I am a beginner of VBA. I try to copy 5 sheets paste into 1 workbook named "Import". Each sheet contains about 1000-2000 rows and I want to append 5 sheets in "Import" sheet.
The problem is this needs to do every week and every time rows of each sheet varies. I don't know how to use VBA to get this done.
Thanks for attention and help.
Aladin


text:
Q: Generate zip file with xml content on the fly I would like to generate an xml file on the fly and compact it in a zip file.
I need to use the XmlDocument and the Ionic library (for compression).
As I could understand the method ZipFile.AddEntry should do this task,but for some reason the xml file is being generated with empty content inside the zip file. If instead of send it to MemoryStream I save it on disk, I can see the xml nodes.
Any idea, what I'm doing wrong?
        MemoryStream memoryStream = new MemoryStream();

        XmlDocument xmlDoc = new XmlDocument();
        XmlNode rootNode = xmlDoc.CreateElement("users");
        xmlDoc.AppendChild(rootNode);

        XmlNode userNode = xmlDoc.CreateElement("user");
        XmlAttribute attribute = xmlDoc.CreateAttribute("age");
        attribute.Value = "42";
        userNode.Attributes.Append(attribute);
        userNode.InnerText = "John";
        rootNode.AppendChild(userNode);

        userNode = xmlDoc.CreateElement("user");
        attribute = xmlDoc.CreateAttribute("age");
        attribute.Value = "39";
        userNode.Attributes.Append(attribute);
        userNode.InnerText = "Jen";
        rootNode.AppendChild(userNode);

        //if (File.Exists(@"c:\temp\Teste\z.xml")) {
        //    File.Delete(@"c:\temp\Teste\z.xml");
        //}
        //xmlDoc.Save(@"c:\temp\Teste\z.xml"); -- it works

        xmlDoc.Save(memoryStream);

        if (File.Exists(@"c:\temp\Teste\z.zip")) {
            File.Delete(@"c:\temp\Teste\z.zip");
        }

        using (ZipFile zip = new ZipFile(@"c:\temp\Teste\z.zip")) {
            //zip.AddFile(@"C:\Temp\a.txt"); -- it works
            zip.AddEntry("z.xml", memoryStream);
            zip.Save();
        }

Thanks.


text:
Q: How can we adapt the knitr to out own directories? The following codes do not run:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
```

Because the second line generates the following error:
Error: No root directory found in C:/Users/asus/Desktop/RTEST or its parent directories.
Root criterion: contains a file matching "[.]Rproj$" with contents matching "^Version: " in the first line

How can I fix this code?


text:
Q: Vector calculations. How to get the new coordinates of an x,y point that is rotated 45 deg cw from centre? Although the logic of math is a fun challenge to work on, my years in math are far behind me. I therefore need help.
Context:
I am building a software to fly an underwater rectangular prizm like robot called an ROV. This requires me to control the 4 thrusters, which are located at each corner with a 45deg angle to the center.
I need to control these thrusters with a joystick.
The joystick gives us an x,y position that I need to program to apply thrust and direction on the right thruster.
Where I need help is on how to get the new coordinates of the joystick's x,y point that are rotated 45 deg cw from the axes' center. This will give me the actual amount of thrust to apply on each thrusters.
See my illustration bellow for a better understanding:

I think the answer lies in vectoring formulas.
Any help would be gratefully appreciated.
Regards,
E.

A: Let's write $e_x$ and $e_y$ for the unit vectors in $x$ resp. $y$ direction, and $e_{x'}$, $e_{y'}$ for the unit vectors in the new directions. We have as we obtain $x$ from $x'$ by rotating in positive direction $45^°$, that
$$ e_{x} = \cos(45^°)e_{x'} + \sin(45^°)e_{y'} = \frac 1{\sqrt 2}e_{x'}+ \frac 1{\sqrt 2}e_{y'} $$
Along the same lines
$$ e_{y} = -\frac 1{\sqrt 2} e_{x'} + \frac 1{\sqrt 2} e_{y'} $$
Now for the point $p = xe_x + ye_y$ we have
\begin{align*}
   p &= xe_x + ye_y\\
     &= \frac x{\sqrt 2}e_{x'} + \frac x{\sqrt 2}e_{y'}
    - \frac y{\sqrt 2}e_{x'} + \frac y{\sqrt 2}e_{y'}\\
     &= \frac{x-y}{\sqrt 2} \cdot e_{x'} + \frac{x+y}{\sqrt 2} \cdot e_{y'}
\end{align*}
Hence, the point has $(x',y')$-coordinates $2^{-1/2}(x-y, x+y)$.


text:
Q: JSF PrimeFaces paginate DataTable on server-side What I'm trying to do is filling DataTable with a paginated response body. Is it possible to call a page of response body on a specific DataTable page?
For instance:
When I head to page 3, it should be filled with the below request's response
http://localhost:8090/relationsByApplication/1?page=3
Repository
public interface MemberRepository extends PagingAndSortingRepository<MemberModel, String>{
        public Page<MemberModel> findByApplicationId(long applicationId, Pageable page);}

Service
public List<MemberModel> getRelationsByApplicationId (long applicationId,Pageable page) {
    return memberRepository.findByApplicationId(applicationId,page).getContent();}

Controller
@RequestMapping("/relationsByApplication/{id}")
    public List<MemberModel> getRelationsByApplicationId(@PathVariable long id, Pageable page) {
        return memberService.getRelationsByApplicationId(id, page);}

I assigned response of (http://localhost:8090/relationsByApplication/1) to relations List yet DataTable only shows 1 page/20 elements which response's first page has.
How can I achieve to fill that DataTable according to it's page number and filtering a column on whole pages not only the selected one?
xhtml
<p:dataTable id="relationTable" var="rel" value="#{index.relations}"
                    widgetVar="relTable" rows="20" paginator="true"
                    paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                                            emptyMessage="No relation found with given criteria"
                    filteredValue="#{index.filteredRelations}" resizableColumns="true"
                    draggableColumns="true" scrollable="true" scrollHeight="300">

                    <p:column headerText="Name" style="width:200px;"
                        filterBy="#{rel.name}"
                        sortBy="#{rel.name}" filterMatchMode="contains">
                        <h:outputText value="#{rel.name}" />
                    </p:column>
</p:dataTable>

Any help would be appreciated.


text:
Q: What weapons count for the "kill an enemy with every type of weapon" Abstergo challenge? Under the Fighter category, there's a challenge to kill an enemy with every type of weapon, and a count of nine.
What weapons count toward the completion of the challenge?

A: Any plausible killing weapon, so it would be

*

*Duel Swords

*Pistols

*Hidden Blades

*Rope Dart

*Heavy Axe(dropped by the Heavy British Soldiers)

*Sword (dropped by the soldiers)

*Musket (dropped by the soldiers)

*Swivel Gun

*Throwing knife (dropped by agile guards)


text:
Q: How to read a spark saved file in java code I am new to Spark. I have a file TrainDataSpark.java in which I am processing some data and at end of it I am saving my spark processed data to a directory called Predictions with below code
predictions.saveAsTextFile("Predictions");

In same TrainDataSpark.java i am adding below code part just after above line.
OutputGeneratorOptimized ouputGenerator = new OutputGeneratorOptimized();
final Path predictionFilePath = Paths.get("/Predictions/part-00000");
final Path outputHtml = Paths.get("/outputHtml.html");
ouputGenerator.getFormattedHtml(input,predictionFilePath,outputHtml);

And I am getting NoSuchFile exception for /Predictions/part-00000 . I have tried all possible paths but it fails. I think the java code searches for the File on my local system and not hdfs cluster. Is there a way to get file path from cluster so I can pass it furthur? OR is there a way to load my Predictions file to local instead of cluster  so as the java part runs with out error?

A: This can happen if you are running Spark on a cluster. Paths.get looks for the file in the local file system on every node separately, while it exists on hdfs. You  can probably load the file using sc.textFile("hdfs:/Predictions") (or sc.textFile("Predictions")).
If, on the other hand, you'd like to save the local file system, you'r gonna need to collect the RDD first and save it using regular Java IO.

A: I figured it out this way...
String predictionFilePath ="hdfs://pathToHDFS/user/username/Predictions/part-00000";
String outputHtml = "hdfs://pathToHDFS/user/username/outputHtml.html";

URI uriRead = URI.create(predictionFilePath);
URI uriOut = URI.create(outputHtml);

Configuration conf = new Configuration ();

FileSystem fileRead = FileSystem.get (uriRead, conf);
FileSystem fileWrite = FileSystem.get (uriOut, conf);

FSDataInputStream in = fileRead.open(new org.apache.hadoop.fs.Path(uriRead));
FSDataOutputStream out = fileWrite.append(new org.apache.hadoop.fs.Path(uriOut));

/*Java code that uses stream objects to write and read*/
OutputGeneratorOptimized ouputGenerator = new OutputGeneratorOptimized();
ouputGenerator.getFormattedHtml(input,in,out);


text:
Q: How many ways can $N$ different people select from $k$ different options such that no two people select the same option and $k>N$? How many ways can $N$ different people select from $k$ different options such that no two people select the same option and $k>N$?
Concrete example: suppose we have $N = 6$ distinct people and $k = 10$ different bus stops. How many ways can the 6 people choose from the 10 bus stops such that no two people get off on the same stop?
I'm thinking that the answer might be $10\choose 6$ since we must choose 6 different people for 10 possible bus stops, but I'm not sure if this is the correct way of going about this.
Followup question: Say $N = 6$ distinct people are on an elevator with $k = 10$ floors and each must push a button for their floor. How many ways can the buttons be chosen such that no two people can choose the same button? (The order in which the lights are chosen doesn't matter)
This questions sounds similar to the one above so would the answer here be $10\choose 6$ as well (or whatever the correct answer to the above question is)?

A: The first person has $k$ choices. The next person has $k-1$ choices (any option not chosen by the previous person) and so on so that the number of ways is
$$
k(k-1)\dotsb (k-N+1)=N!\binom{k}{N}.
$$


text:
Q: builtins.ModuleNotFoundError: No module named 'itemadapter' I am trying to run to spider on scrapyhub and getting this error. But this spider working well on local machine. I already change the name of spider project and spider module.
      File "/usr/local/lib/python3.8/site-packages/scrapy/crawler.py", line 103, in _create_engine
        return ExecutionEngine(self, lambda _: self.stop())
      File "/usr/local/lib/python3.8/site-packages/scrapy/core/engine.py", line 70, in __init__
        self.scraper = Scraper(crawler)
      File "/usr/local/lib/python3.8/site-packages/scrapy/core/scraper.py", line 71, in __init__
        self.itemproc = itemproc_cls.from_crawler(crawler)
      File "/usr/local/lib/python3.8/site-packages/scrapy/middleware.py", line 53, in from_crawler
        return cls.from_settings(crawler.settings, crawler)
      File "/usr/local/lib/python3.8/site-packages/scrapy/middleware.py", line 34, in from_settings
        mwcls = load_object(clspath)
      File "/usr/local/lib/python3.8/site-packages/scrapy/utils/misc.py", line 50, in load_object
        mod = import_module(module)
      File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1014, in _gcd_import

      File "<frozen importlib._bootstrap>", line 991, in _find_and_load

      File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked

      File "<frozen importlib._bootstrap>", line 655, in _load_unlocked

      File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible

      File "<frozen zipimport>", line 259, in load_module

      File "/app/__main__.egg/internbit/pipelines.py", line 10, in <module>

    builtins.ModuleNotFoundError: No module named 'itemadapter'

A: Just install it:
pip install itemadapter

BTW, itemadapter is a scrapy module rather than a built-in module.