text:
Q: reading multiline python code using python I have a Python file which I am reading using another python file. I have a line.
CP.TEST.AppendList(Name='MANHOLE', Values=[ 1, 2, ],
        var='MV')
CP.TEST.AppendList(Name='CANHOLE', Values=[ 3, 4, ],
        var='LV')

I am searching this line using
if 'LV' in line:
     print line

Thus, I am getting output as :
            var='LV')

But, I want to get complete line which contains that string. There are many of such multiline python code in my files.
How I can retrieve such python multi lines in codes using python?
Forexample, in this code, I need output as
CP.TEST.AppendList(Name='MANHOLE', Values=[ 1, 2, ],
        var='LV')

using value 'LV'

A: You need to concatenate the single lines which have coded in multiple lines  but they all end with ','(if your following PEP 8 in code)
EG:
CP.TEST.AppendList(Name='CANHOLE', Values=[ 3, 4, ],
        var='LV')

convert it temporarily to:
CP.TEST.AppendList(Name='CANHOLE', Values=[ 3, 4, ],var='LV')

And search now
with open('colorlabel.py','r') as file:
    temp=''
    for i in file:
        if i.strip().endswith(','):
            temp+=i
        else:
            temp+=i
            if 'lv' in temp:
                print '  >>',temp
            temp=""

A: To understand that multiple lines of code are actually a single line of python code, you'll need something that understands python.
In python, you can get at the compiler from code. The "compile" command can take text and return a code object, or throw an error if the code is not syntactically correct:
try:
  compile(candidate_code, 'fake filename', 'exec')
  # got here? candidate_code compiles
except:
  # got here? candidate_code doesn't compile

Compiling is completely tolerant of missing definitions for symbols. However, it doesn't like to see extra indentation.
Using this, we can step through the lines of code, looking for multiline statements (groups of lines that successfully compile) and testing any that do compile for the target string. We have to keep compiling all lines up to the current line (otherwise if your statement is indented, it wont compile) and keep track of how many lines we are actually testing (using numcandidatelines). An alternate approach might be simply to detect and strip off extra indentation.
def findPythonLines(aContainsStr, lines):
  numcandidatelines = 0
  for index, line in enumerate(lines):
    numcandidatelines += 1

    try:
      candidate_code = "\n".join(lines[:index+1])
      candidate_statement = "\n".join(lines[index+1-numcandidatelines: index+1])

      compile(candidate_code, 'fake filename', 'exec') # or 'exec'

      # if we get here, this is a new possible result
      if aContainsStr in candidate_statement:
        return candidate_statement
      else:
        # no dice. Well, we need to look for the next candidate
        numcandidatelines = 0
    except:
      pass

  return None

# say input.txt contains the following:
# x = 10
#
# while (x
#       > 0):
#   g()
#
#   y = f(Name='MANHOLE', Values=[ 1, 2, ],
#       var='LV')
#
#   x -= 1

with open ("input.txt", "r") as myfile:
    full_code_lines=myfile.readlines()

print "result: %s" % findPythonLines("'LV'", full_code_lines)

# prints out the following:
#
# result:
#    y = f(Name='MANHOLE', Values=[ 1, 2, ],
#          var='LV')


text:
Q: Visual C# Creating a text file on the desktop access denied my code when the form loads:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (!File.Exists(path))
{
    // Create a file to write to.
    using (StreamWriter sw = File.CreateText(path))
    {
        sw.WriteLine("test");
    }

}

This is the error I constantly recieve: http://gyazo.com/bd623e67a24408ac3e71b5cc79a30f94

A: What your code is doing right now is attempting to create a file with the same exact name as the Desktop folder. To create a new file, you'll need to append a file name to the end of your path string. Try something like this:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (!File.Exists(path + @"\test.txt"))
{
    // Create a file to write to.
    using (StreamWriter streamWriter = File.CreateText(path + @"\test.txt"))
    {
        streamWriter.WriteLine("test");
    }
}

The @ symbol in the strings makes the compiler ignore any escape characters in the string, treating them as a string literal. This code will check if a file named test.txt exists on your Desktop. If not, it creates one and writes "test" to it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to svn merge a list of revisions contained in a file? I would like to merge in a branch 2 a quite long list of revisions from branch 1. This list is contained in a text file, like, say :
1
3
78
… //a long list of revisions here...
324

Is there an elegant solution, better than doing in my branch2 working copy :
svn merge -c1 -c3 -c78 … -c324 branch1

?
I know that I shouldn't get to this point, but life is life !
EDIT : the format of the text file can easily change

A: I figured a solution with bash :
commande="svn merge http://svn.sfrdev.fr/sfr/applications/bol-entreprise/trunk/"; for line in $(cat ~/listOfRevs); do commande="$commande -c $line"; done;echo $commande;eval $commande

listOfRevs is a file containing all the revision numbers, one per line :
r2
r5
…
rN


text:
Q: Rich parse messages with push notifications service I'm using Parse service in an application I'm developing, push notifications are now working, I can send perfectly ...
But I want to implement some actions in determidos cases example: Send url to be opened as soon as the user clicks on the notification, make a call, open the map with a planned route, and more.
I wonder if this is possible, and if we had someone who already knows the way I should go.
Thanks!

A: You can certainly send additional information to trigger an event inside your app, such as url opens, opening maps, etc.
First, you need to send a payload with your push notification that tells the app what to do. You can learn about that here:
https://parse.com/docs/push_guide#options/Android
Second, you need to create a handler inside your Android app that recognizes your push payload and knows what to do with it. You can find the appropriate start under "Responding with a Custom Activity" here:
https://parse.com/docs/push_guide#receiving-responding/Android


text: Q: how to send formatted text in mail of richtextBox I have text with different fonts but when I email it using richTextBox.text or richtextbox.rtf. I don't get text with colors. please tell me how to do that


text:
Q: Passing multi-dimensional array in fortran subroutines I am trying to understand a Fortran code written by someone else. The code is doing what it is supposed to do so I am assuming that it works fine. A subroutine called "fft" is being called from another subroutine called "convol". Inside "convol", an array is declared like this:
real, dimension fri(n+1,n,nh,2,0:1)
call fft(fri)

Inside "fft", the declaration is like this:
subroutine wrft3b(fri)
real, dimension fri(2,n+1,n,nh,0:1)

I don't understand why the array lengths are not consistent and still the code is working. Any clues what might be happening here?

A: The important thing is that the length is the same. If the interface is not explicit, this will not throw an error for the contiguous explicit-shape array. Only the elements of the array will have different indexes (determined by the column-major order), that in the calling program.


text:
Q: When you write a Powershell function how long does it last in memory? When you write a Powershell function how long does it last in memory. So I have developed a custom function and ran it to create the function, does this function remain on my machine permanently so all I need to do is call the function? If i turned my machine on and off and re-booted can I call the function etc. Does another user need to run the function first before they can use it?

A: The function exists only in the session where it's code is executed. As soon as you close the Powershell process it's gone. But you can just load up the function definition again and it's back. If you want to have a function in every powershell session available create a module and add it to you userprofile (here is how).
function foo {write-host "I am alife"}
foo

A: Powershell functions last as the powershell session itself, so when you define a function in the console, you can still call it as this console is running, once you close it, you will have to define the function again.
However, Powershell has specific scripts in the system that runs whenever Powershell session is started, these scripts are called Powershell profiles.
So in your case, if you put the function in Powershell profile, it will be defined directly when you open your Powershell session and it will be permanently defined.
Look here to see about powershell profile
This code will put your function in the profile:
New-Item -Type Directory -Path "$home/Documents/WindowsPowerShell"
"<Your Function Here>" | Out-File -Force -FilePath $profile.CurrentUserAllHosts

Now whenever you open a new Powershell console (or any powershell process runs), your function will be loaded (even after you reboot your system).
If you have a powershell file (.ps1) that contains many functions, you can simply copy its content to $Profile.CurrentUserAllHosts, or put this code in $Profile.CurrentUserAllHosts to import your file as Powershell starts.
Import-Module "<Your File (.ps1) Path Here>"

Update
I forgot to tell you that you have to change your Powershell privacy policy to unrestricted, otherwise you will get error telling you that running script is disabled on this system.


text:
Q: Subsitute decimal point in floating point number with comma Python For a given string, how can we substitute the decimal point in a floating point number with a comma?
For example: 12.33 should become 12,33
Please note that I can not simply replace all the . with , since the text also contains full stops to separate two sentences.
I need this for a text cleaning purpose.

A: One option is to use 2 capturing groups and assert what is on the left and on the right is not a non whitespace char.
(?<!\S)(\d+)\.(\d+)(?!\S)

In parts

*

*(?<!\S) Negative lookbehind, what is directly on the left is not a non whitespace char

*(\d+) Capture group 1, match 1+ digits

*\. Match dot literally

*(\d+) Capture group 2, match 1+ digits

*(?!\S) Negative lookbehind, what is directly on the right is not a non whitespace char

Regex demo
In the replacement use group 1 and group 2 and place the comma between the groups
\1,\2

For example
import re

text = "Test 12.33 test"
new_text = re.sub(r'(?<!\S)(\d+)\.(\d+)(?!\S)', r'\1,\2', text)
print(new_text)

Output
Test 12,33 test

A: I think you can use finditer to find all the positions of matches in the text.
Then replace them one by one.
import re

text = '''This is a dummy text. I want the `.` of 12.12 to go away.
I want to replace it with a `,`. Lets see if it works.'''

p = re.compile(r"\d\.\d")
for m in p.finditer(text):
    text = text[:m.start() + 1] + ',' + text[m.start() + 2:]

print(text)

The output is
This is a duppy text. I want the `.` of 12,12 to go away.
I want to replace it with a `,`. Lets see if it works.

A: Apply this simple regex substitution expression
re.sub(r'(\d+)\.(\d*)', r'\g<1>,\g<2>',search_string)

A: I was able to solve this problem using the following regular expression:
decmark_reg = re.compile('(?<=\d)\.(?=\d)')


text:
Q: determining the next random number pseudorandom number generator? I have given 3 numbers let's say basic example x_0=5, x_1=6 and x_2=2 and modulus p is 7,
x_n=(ax_n-1+c)modp where p=7, I am trying to generate linear equations to solve but I am kind of lost
I do this
6=(a5+c)mod7 therefore 7*x+7=5a+c
2=(6a+c)mod7 therefore 7*y+2=6a+c

now I can subtract them and have 3 unknown x,y and a but two equations to solve,
I do not understand how to generate two equations with two unknows
I really appreciate your help
I read this but I could not understand
Number of samples to predict the next number in a pseudorandom number generator

A: If you start from $$5a+c \equiv 6 \pmod 7$$ $$ 6a+c \equiv 2 \pmod 7$$ then you can solve these in a similar way to ordinary simultaneous equations. Here subtraction gives $$a \equiv 2-6 \equiv 3 \pmod 7$$ and so substituting into the first equivalence $$c \equiv 6-5\times 3 \equiv 5 \pmod 7$$
You can check that $x_n\equiv 3x_{n-1}+ 5 \pmod 7$ for your initial values.  The full cycle is $5,6,2,4,3,0,5,\ldots$ while $1$ is a fixed point


text:
Q: Get the value of custom Datepicker and save it to firebase database My problem is I want to insert datepicker's value to firebase but Idk how to do it.
I already made an custom date picker but the use of it is to make an placeholder "birth date"
This is my xaml;
<frame //some property here>
<stacklayout  //some property here>
<frame  //some property here>
<image  //some property here/>
<grid>
<local:BirthdayDatePickerControl x:Name="entryField_DateOfBirth" >

                                </local:BirthdayDatePickerControl >
</grid>
</frame>
</stacklayout>
</frame>

This is my code(Myproj):
Datepickerctrl.cs
public class DatePickerCtrl:DatePicker
{
public static readonly BindableProperty EnterTextProperty = BindableProperty.Create(propertyName: "Placeholder", returnType: typeof(string), declaringType: typeof(DatePickerCtrl), defaultValue: default(string));
public string Placeholder { get; set; }
}

this file or code also is save to (Myproj)
BirthdayDatePickerControl.cs:
public class BirthdayDatePickerControl : DatePicker
     {

             public static readonly BindableProperty EnterTextProperty = BindableProperty.Create(propertyName: "Placeholder", returnType: typeof(string), declaringType: typeof(BirthdayDatePickerControl), defaultValue: default(string));
             public string Placeholder { get; set; }

     }

This is my code(Myproj.android):
[assembly: ExportRenderer(typeof(BirthdayDatePickerControl), typeof(BirthdayDatePickerRenderer))] // this line is outside of my namespace in BirthdayDatePickerRenderer.cs

BirthdayDatePickerRenderer.cs
public class BirthdayDatePickerRenderer : DatePickerRenderer
     {
         public BirthdayDatePickerRenderer(Context context) : base(context)
         {

         }

         protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.DatePicker> e)
         {
             base.OnElementChanged(e);
             if (Control != null)
             {
                 Control.Text = "Birth Date";
             }
         }
     }

My expected output is still I can place an placeholder to my datepicker UI, and also get that data  from datepicker and same it to firebase.
I tried some trial and error
This is what I've done
async public void signButton_Clicked(System.Object sender, System.EventArgs e)
        {

/*

some code here like assigning firstname or lastname and etc.
*/
  string dateOfBirth = entryField_DateOfBirth.ToString();

   CUSTOMER customer = new CUSTOMER();

   customer.CusBirthOfDate = dateOfBirth;
    var Savedata = await customerRepo.Save(customer);

         }

A: I think you have done most of the work. Just make a small change to the Button Clicked handler:
async public void signButton_Clicked(System.Object sender, System.EventArgs e)
{
    ...

    var date = entryField_DateOfBirth.Date.ToString().Split(" ")[0]; //get the date

    ...
}

If you want to set the default placeholder of Datepicker to "Birth Date", you should still use a custom render, otherwise xamarin forms Datepicker cannot recognize this kind of string. For more info, you could refer to Xamarin.Forms DatePicker.
Hope it works for you.


text:
Q: Probability conditioned on disjunction of events This seems elementary, but I cannot see a quick proof:
For events $A, B, C$ we have
$$
P(A \mid B \cup C) \leq \max(P(A \mid B), P(A \mid C))
$$
Is this right?

A: It is incorrect. Consider this counter-example: $A=\{1,2\}$, $B=\{1,3\}$, $C=\{2,3\}$ and $P(\{1\})=P(\{2\})=P(\{3\})=\frac{1}{3}$.


text:
Q: Combinatorics Problem with Chess 8 black and 8 white pawns (totally 16 pawns) are placed at random on a chess board (64 squares with 8 rows and 8 columns). What is the probability that there is at least one row which has exactly 3 black pawns and 3 white pawns?
I thought that with this problem, the denominator would be the C(16,64)*C(8,16) for the numerator - I just do not know how to divide the cases.

A: Let $A_i$ represent the event that row $i$ has exactly three black and three white pawns.
We are asked to count $|A_1\cup A_2\cup\dots\cup A_8|$
By inclusion-exclusion this is
$$=|A_1|+\dots+|A_8|-|A_1\cap A_2|-|A_1\cap A_3|-\dots-|A_7\cap A_8|+|A_1\cap A_2\cap A_3|+\dots$$
By symmetry, we notice that $|A_1|=|A_2|=\dots=|A_8|$ and that $|A_1\cap A_2|=|A_1\cap A_3|=\dots=|A_7\cap A_8|$ etc... so the above simplifies to:
$$=8|A_1|-28|A_1\cap A_2|+|A_1\cap A_2\cap A_3|+\dots$$
Counting $|A_1|$:

*

*Arrange $3$ black and $3$ white pawns in the first row.

*Arrange the remaining $5$ black and $5$ white pawns in the remaining rows.

 This can be done in $\binom{8}{3}\binom{5}{3}\binom{56}{5}\binom{51}{5}$ ways

Counting $|A_1\cap A_2|$

*

*Arrange $3$ black and $3$ white pawns in the first row.

*Arrange $3$ black and $3$ white pawns in the second row.

*Arrange the remaining $2$ black and $2$ white pawns in the remaining rows.
Now, notice that it is impossible to have exactly three black and three white pawns in more than two rows at a time as that would require at least nine black pawns, which is more than our eight black pawns we have available.  This implies that all terms consisting of intersections of three or more of our events are empty and contribute zero to the overall sum.
Finish the arithmetic and take the appropriate ratio and reach a final answer.


text:
Q: Makefile rule to conditionally run script and then copy files I have a Makefile, I'm trying to create a rule that will build RPMs if they don't already exist (based on looking at particular directory) otherwise just copy those RPMs to some other directory.
Essentially what I'd like to do is:
if somedir/build does NOT has RPMs:
  somedir/build.sh

cp -R somedir/build/* destination

I've been toying with using $(shell if [[ -d somedir/build ]] ....) but not having much luck.

A: This is working:
someproject_rpms:
    @if [[ -d somedir/build ]] ; then \
        count=$$(find somedir/build -name "*.rpm" -type f | wc -l); \
        if [[ $$count -eq 0 ]]; then \
            $$(cd somedir && ./build.sh); \
        fi \
    else \
        $$(cd somedir && ./build.sh); \
    fi; \
    find somedir/build -name "*.rpm" -type f -exec cp {} somedestination \;

Not the prettiest, but it works.

A: You should use so-called "sentinel" files. These are empty files, that are used only for their timestamp, and the timestamp signifies the completion of some action, typically creating a bunch of other files, whose names we may or may not know.  The two files named rpms are the sentinel files, and here is your solution Makefile:
destination/rpms: somedir/build/rpms Makefile
    find $(<D) -name *.rpm -exec cp {} $(@D) \;
    touch $@

somedir/build/rpms: $(PACKEES) Makefile
    somedir/build.sh
    touch $@

PACKEES right now is empty, but you should set it to be all the files you want to have packed into any of your rpms, in other words, all the files that build.sh reads.  If you insist on using one build.sh script to build all your rpms at once (which is not a good idea), the above is the best you are going to get :)


text:
Q: Getting access violation error in wmp.dll when assigning property of WMPLib_TLB.TWindowsMediaPlayer I started getting this error since November 2019. Windows security updates are to blame. The bug was caught on Windows 7 and 10. Any ideas how to fix it?
compiled with      : Delphi 10.2 Tokyo
madExcept version  : 4.0.18
callstack crc      : $78649ba9, $ab93b801, $94e2a1f8
exception number   : 1
exception class    : EAccessViolation
exception message  : Access violation at address 78649BA9 in module 'wmp.dll'. Read of address 00000008

ClntMainThread ($3e90):
78649ba9 +000 wmp.dll
76c8e79b +01b oleaut32.dll                        VariantClear
010df1b2 +0ca Clnt.exe Vcl.OleCtrls               TOleControl.CreateControl
010e0443 +01b Clnt.exe Vcl.OleCtrls               TOleControl.GetOleObject
01fbb0e5 +021 Clnt.exe WMPLib_TLB        7917  +1 DoCreate
01fbb15c +014 Clnt.exe WMPLib_TLB        7921  +1 TWindowsMediaPlayer.CreateControl
01fbb177 +00f Clnt.exe WMPLib_TLB        7926  +1 TWindowsMediaPlayer.GetControlInterface
01fbb226 +02e Clnt.exe WMPLib_TLB        7937  +1 TWindowsMediaPlayer.Get_settings
01fbc2e2 +15e Clnt.exe frVideoPlayer      107 +28 TVideoPlayerFrame.CreateMediaPlayer

This is the code. Self is a TFrame:
WMPlayer := TWindowsMediaPlayer.Create(Self);
FWMPlayer.Align := alClient;
FWMPlayer.Parent := Self;
if Assigned(FWMPlayer.settings) then //<- line 107 of the callstack
  FWMPlayer.settings.autoStart := False;


text:
Q: Show time and date in ubuntu 12.04 I'm using Gnome classic in Ubuntu 12.04. I inadvertently deleted some files, and after that  I'm not able to find the settings that would allow me to display the date and time.
 How  can I make the date and time appear?

A: You may have deleted the indicator-datetime package. Make sure it's installed, then logout/login.


text:
Q: Adding multiple CKEditor instances in jquery I'm experimenting with various WYSIWYG javascript text areas.  If I try to put a CKEditor on every <textarea> on my screen with jquery, the editors all show up fine, but they don't save.  I've tried:
$(function() {
$('.editors').ckeditor();
});

and
$(function() {
$('.editors').each(function(index, element){
    $(element).ckeditor();
});
});

In both instances, every text area has a CKEditor on it, but it doesn't save.  If I manually add all the editors with
$(function() {
CKEDITOR.replace('contactText');
CKEDITOR.replace('edit_footer_text');
CKEDITOR.replace('termsText');
});

or
$(function() {
$('#contactText').ckeditor();
$('#edit_footer_text').ckeditor();
$('#termsText').ckeditor();
});

All three fields have editors, and they save.
I'm trying to put some code in the standard template for this project so that if we want editors on the text areas, they just have to add the class 'editors' to them, so that's why I'm looking for jQuery solutions.  This did work with tinymce:
$(function() {
     $('.editors').tinymce({
           script_url : '/common/tiny_mce/tiny_mce.js',
               // General options
               mode : "textareas",
              theme : "advanced",
         })
});

A: Actually, jQuery Adapter for CKEditor, does not update the form element by default, you need  to replace the editor with the current id.
$(function() {
$('.editors').each(function(){
    CKEDITOR.replace( $(this).attr('id') );
});
});

Reference


text:
Q: What is the probability of $100$ biased coins flipping heads Variation to this problem
What if I tossed $100$ different coins with a different bias towards the head?
(For example, the biases are $p_1, p_2, \ldots, p_{100}$ and the coin are not necessarily tossed in order of the subscripts of $p$.)
What would be the probability that heads is flipped exactly $65$ times?
I couldn't even get the number of ways in which $65$ heads are got, any help here?

A: By analogous reasoning to proving the formula for the pmf of a Binomial random variable, we get $$\sum_{\substack{S\subseteq[100]\\|S|=65}}\prod_{i\in S}p_{i}\prod_{i\in[100]\setminus S}(1-p_{i}),$$ where the sum is over all subsets $S$ of $[100]=\{1,2,\ldots,100\}$ with size $65.$ It's not terribly clear how useful this formula will be, but if you had some bounds on the $p_{i},$ you might be able to use this to prove that the probability lies in some interval.
For instance, if all $p_{i}\in[1/2,3/4],$ then $\prod_{i\in S}p_{i}\in[(1/2)^{65},(3/4)^{65}],$ and $\prod_{i\in[100]\setminus S}(1-p_{i})\in[(1/4)^{35},(1/2)^{35}]$, giving a product in $[(1/2)^{65}(1/4)^{35},(3/4)^{65}(1/2)^{35}]$ for all $S\subseteq[100].$ Then the probability lies in the interval $[\binom{100}{65}(1/2)^{135},\binom{100}{65}(3/4)^{65}(1/2)^{35}]\approx[2.514\times 10^{-14},1]$, which admittedly is not super helpful, but with tighter bounds, this could be improved.


text:
Q: Tensorflow: InvalidArgumentError with MNIST, [55000] vs. [10000] I'm working through the code from this presentation http://www.youtube.com/watch?v=vq2nnJ4g6N0&t=20m28s and am getting this error: InvalidArgumentError (see above for traceback): Incompatible shapes: [55000] vs. [10000]
I've already worked through a few errors regarding tensor shape/dimensions, but have no idea how to specifically understand this let alone correct it.
I'm new to tf and any advice is much appreciated, here is the code:
# 1 ~ import tf + data
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

#2 ~ paras + init
X = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

init = tf.initialize_all_variables()

#3 ~ model + correct answers
Y = tf.nn.softmax(tf.matmul(X, W) + b)
Y_ = tf.placeholder(tf.float32, [None, 10]) # one-hot encoding

#4 ~ loss function
cross_entropy = -tf.reduce_sum(Y_ * tf.log(Y))

#5 ~ correct answer + % accuracy
is_correct = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1)) # one-hot decoding
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))

#6 ~ optimizer and training step
optimizer = tf.train.GradientDescentOptimizer(0.003) # learning-rate
train_step = optimizer.minimize(cross_entropy)

#7 ~ session and training loop
sess = tf.Session()
sess.run(init)

for i in range(1000):
    # load a batch of images and correct answers
    batch_X, batch_Y = mnist.train.next_batch(100)
    train_data = {X: batch_X, Y_: batch_Y}

    # train
    sess.run(train_step, feed_dict=train_data)

    # success?
    a,c = sess.run([accuracy, cross_entropy], feed_dict=train_data)

    # success on test data?
    test_data = {X: mnist.train.images, Y_: mnist.test.labels}
    a,c = sess.run([accuracy, cross_entropy], feed_dict=test_data)

The total error output is:
Traceback (most recent call last):
      File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1021, in _do_call
    return fn(*args)
  File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1003, in _run_fn
    status, run_metadata)
  File "/Users/joelmcleod/anaconda3/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 469, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [55000] vs. [10000]
     [[Node: Equal = Equal[T=DT_INT64, _device="/job:localhost/replica:0/task:0/cpu:0"](ArgMax, ArgMax_1)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "deep_nn1.py", line 71, in <module>
    a,c = sess.run([accuracy, cross_entropy], feed_dict=test_data)
  File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 766, in run
    run_metadata_ptr)
  File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 964, in _run
    feed_dict_string, options, run_metadata)
  File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1014, in _do_run
    target_list, options, run_metadata)
  File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1034, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [55000] vs. [10000]
     [[Node: Equal = Equal[T=DT_INT64, _device="/job:localhost/replica:0/task:0/cpu:0"](ArgMax, ArgMax_1)]]

Caused by op 'Equal', defined at:
  File "deep_nn1.py", line 47, in <module>
    is_correct = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1)) # one-hot decoding
  File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/gen_math_ops.py", line 728, in equal
    result = _op_def_lib.apply_op("Equal", x=x, y=y, name=name)
  File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 759, in apply_op
    op_def=op_def)
  File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2240, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/joelmcleod/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1128, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Incompatible shapes: [55000] vs. [10000]
     [[Node: Equal = Equal[T=DT_INT64, _device="/job:localhost/replica:0/task:0/cpu:0"](ArgMax, ArgMax_1)]]

A: You are feeding training data (number of rows: 55,000) instead of testing data (number of rows: 10,000) in this line:
test_data = {X: mnist.train.images, Y_: mnist.test.labels}

Just fix it with:
test_data = {X: mnist.test.images, Y_: mnist.test.labels}


text:
Q: How to append mysql access to iptables On one of my servers, I can see this:
ACCEPT     tcp  --  distinct_server_ip               anywhere            tcp dpt:mysql

By doing
sudo iptables -L | grep distinct_server_ip

And with
iptables -L -n -v | grep 3306

432K   26M ACCEPT     tcp  --  *      *       mydistinctip       0.0.0.0/0           tcp dpt:3306
90  5400 ACCEPT     tcp  --  *      *       mydistinctip2       0.0.0.0/0           tcp dpt:3306

I would like to enable the same in another server, could you please help me with the command I have to use?
I was thinking on something like:
iptables -A INPUT -p tcp -s distinct_server_ip --sport 1024:65535 -d this_server_ip --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT

A: iptables is highly dependent on the order of your rules. Your question isn't entirely clear so I'll go over both possibilities of you may be aiming to do.
On ServerA, if you want to allow ServerB to connect to it:
iptables -A INPUT -p tcp -s ServerB --dport 3306 -j ACCEPT

And, for egress rules on ServerB (not recommended), if you want to allow it to connect to ServerA:
iptables -A OUTPUT -p tcp -d ServerA --dport 3306 -j ACCEPT

Huge caveat: You may have something in the INPUT or OUTPUT chain that may prevent these rules from ever being processed. To advise on that, we would need to see all your rules.

A: You can't do that simply, because iptables accepts only a single ip its rules (the same don't stand for ports, they can be multiple generated by the mport module, which is loaded by iptables on the need automatically).
There is a possibility, that you simply duplicate your rules. It is not always practical, although very simple.
Or you could emulate the multi-ip behavior were to create a new table to filter your given list of ip-s. For example:
Chain MY_WISHLIST (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  *      *       1.2.3.4/19       0.0.0.0/0
    0     0 ACCEPT     all  --  *      *       1.2.0.0/17        0.0.0.0/0
    0     0 ACCEPT     all  --  *      *       1.3.0.0/16        0.0.0.0/0
    0     0 ACCEPT     all  --  *      *       1.4.128.0/20      0.0.0.0/0
    0     0 ACCEPT     all  --  *      *       1.5.152.0/21      0.0.0.0/0
    0     0 ACCEPT     all  --  *      *       1.6.0.0/15        0.0.0.0/0

...and you can refer this chain from anywhere:
0 0 MY_WISHLIST        tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           multiport dports 2,3,5,7,11,13,17,19

Finally, there is a new development around the linux kernel/networking things, and that is ipset. Ipset handles exactly this actual flaw (?) of iptables, it will be the 4th firewalling command line tool for linux (after ipfwadm, ipchains and our current iptables).


text:
Q: Read nText using RecordSet I've a column with name FIELD1 of datatype ntext.
How can I read an nText field using a CRecordset object?
CRecordset oRecSet(&oCDb);
drc = oRecSet.Open(CRecordset::forwardOnly, csSQLStr);
oRecSet.GetFieldValue(_T("FIELD1"), vrColValue);

Using default field value, I'm not getting the contents.

A: Figured out a work around.
Since my data in nText fields were relatively small, I typecasted the nText field to nvarhcar(MAX) and used.


text:
Q: inst.setState.bind is not a function, problemas con State en react estoy simplemente tratando de cambiar un state por medio de handlers en react pero al ejecutar las funciones el state no cambia.
aqui tengo las funciones, el state y los objetos por donde mando los props
cabe destacar que uso webpack con babel loader
    export default class Game extends React.Component{
    constructor(){
        super()
        this.state={
            pause: null
        }

    }
    PauseShow(){
        this.setState={ pause: "block" }
        console.log("pauseshow")
    }
    PauseHide(){
        this.setState={ pause: "none" }
        console.log("pausehide")
    }
    render(){

        return(

                <Player idc="Game" src="assets/Fly_Me_to_the_Aegis_Seven_Moon.mp3"/>
                <GameOutput/>
                <GameData pauseMethod={this.PauseShow.bind(this)}/>
                <GameInput />
                <GamePause display={this.state.pause} pauseMethod={this.PauseHide.bind(this)}/>

        )
    }
}

Aquí llamo al un handler que pasé por props
    export default class GameData extends React.Component{
    constructor(){
        super()
    }
    render(){
        return(

                <button onClick={this.props.pauseMethod}>pause</button>

        )
    }
}

He aquí el error completo, ocurre al presionar el boton y accionar el handler

backend.js:8730 Uncaught TypeError: inst.setState.bind is not a function
      at getData (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8730:49)
      at walkNode (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8576:57)
      at chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15
      at Array.forEach (native)
      at walkNode (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8578:20)
      at chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15
      at Array.forEach (native)
      at walkNode (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8578:20)
      at chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15
      at Array.forEach (native)

A: estas cambiando el estado de la manera incorrecta.
tu código es este:
this.setState={ pause: "block" }

cámbialo a esto:
this.setState=({ pause: "block" })

A: El problema que tienes es el siguiente:
tu codigo:
this.setState={ pause: "block" }
codigo correcto:
this.setState({ pause: "block" })


text:
Q: Python gui - make invisible label visible
Possible Duplicate:
In Tkinter is there any way to make a widget not visible?

I have a label looks like:
Lab = Label(text = "Update ID")
Lab.pack(side = LEFT)

I want this label invisible but would like to make it visible when particular button is clicked.
I have a button looks like:
Button1 = Button(buttons, text = "Update Item", command = self.Update_item)
          Button6.pack(side = LEFT, padx = 5, pady = 3)

I want the label invisible but would like to make it visible when 'Button1' is clicked.
Any feedbacks would be appreciated.

A: There are a couple ways to accomplish this. For one, you can use the lift and lower attributes to change the stacking order. For example, if the label is a child of a frame and y ou lower it, it will go "behind" the frame and thus become invisible. T
A second option is to completely remove the label from the display. You can use  grid_remove if you are using the grid geometry manager. The nice thing about this method is that grid remembers where the widget was, so to restore it you can call widget.grid() and all of the previous options (sticky, row, column, etc) will be used.
There is also pack_forget() and grid_forget(), but they have the disadvantage of truly forgetting about the widget. It is removed from the display and the information about where it was placed is forgotten. This means you must re-apply all of the proper options to get the widget to appear in the same place.


text:
Q: Image not getting displayed in datalist I am binding images to datalist. Taking the image name from database and giving the path.
My code is:
<asp:DataList ID="dlImages" runat="server" RepeatColumns="4">
            <ItemTemplate>
               <asp:ImageButton ID="ImageButton1" Height="200px" Width="200px" ImageUrl='<%# Eval("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}.jpg") %>'  runat="server" />
            </ItemTemplate>
        </asp:DataList>

On .cs page:
ds = gc.GetDataToListBinder("select DISTINCT PageOrderID,PageName from ScreenMaster order by PageOrderID")
            dlImages.DataSource = ds.Tables(0)
            dlImages.DataBind()

I am facing 2 problems :

*

*When imagename has space in between it adds %20 in between
Eg. if imagename is "API Message", it takes it as: "API%20Message"

I tried On this Problem:
Added ImageUrl='<%#Server.HtmlDecode(Eval("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}.jpg"))'
But I got error:
XML literals and XML properties are not supported in embedded code within ASP.NET

*

*If there is not space Eg.image name is "Charges" , Then also its not showing it in datalist.

When i ran project, and right clicked on it and view source, then its showing me correct path as:
src="D:\Sagar\Kinston\WebSite\ScreenMasterImages\Charges.jpg"

but not showing image.
Please help me with above code.
Where i have made mistake?
What else i should add in it?

A: Keep it easy and simple.
When trying things like that with URL, to know exactly what to write down, try typing it in your address bar so you'll be able to find the exact syntax needed in order to make it work correctly.
I've done this tons of time and work for me... So you could try something like :
<asp:DataList ID="dlImages" runat="server" RepeatColumns="4">
    <ItemTemplate>
        <asp:ImageButton ID="ImageButton1" Height="200px" Width="200px"
               ImageUrl='<%# String.Format("{0}{1}.jpg", "~\ScreenMasterImages\", Server.HtmlDecode(Eval("PageName"))) %>'
               runat="server" />
    </ItemTemplate>
</asp:DataList>


text:
Q: pywinauto 32-bit userwarning I am trying to use pywinauto to automate TomCat to start and stop every time I update the class files. However, when I try and run it it gives me the following warning:
UserWarning: 32-bit application should be automated using 32-bit Python (you use 64-bit Python)
I am pretty sure I have the 64-bit version of my desired program (Even reinstalled to make sure). Is there any way to skip this warning so the program can execute? Or is this not possible? (Tomcat is even installed in program files instead of program files(x86).) If the case is that I have to use the 32-bit version of python to do this, how can I install pywinauto for both the 32-bit and 64-bit version of python? I tried running it with 32-bit version of python but it says the "pywinauto" module is not recognized, even though I ran pip install pywinauto.
EDIT: The program "worked" despite the warning message. It just informed me that I should use 32-bit python. Even though the code for tomcat did not work( I have no idea why, even used SWAPY to make sure code is correct, but it would still not work).
Here is some code that did not execute as expected (i.e nothing happened)
def tomCatAuto():
    app = Application().Connect(title=u'Apache Tomcat 8.0 Tomcat8 Properties', class_name='#32770')
    window = app.Dialog
    button = window.OK
    button.Click()

A: To make sure the program is really 64-bit you may open the Task Manager and take a look at "*32" suffix presence in the process name. If it's shown, the process is really 32-bit (probably it's a bug in TomCat installer?).
To install pywinauto for non-default Python on your system you need to specify full path to the pip.exe like so:
C:\Python27_32\scripts\pip.exe install pywinauto

EDIT:
I see Tomcat7w.exe process is really 32-bit. So you need to run 32-bit Python to automate it. Also make sure Python+pywinauto is running as Administrator.
P.S. 64-bit Python+pywinauto may work for 32-bit process (that's why there is a warning only, not error). Sometimes users have problems with a TreeView control when the process is of incorrect bitness.


text:
Q: DataTable draw daterange from vaadin-date-picker in polymer I am try to implements datatables filter inside polymer from this link https://jsfiddle.net/bindrid/2bkbx2y3/6/
But when I apply into polymer I found some issue when push to datatables a plugin method. in polymer I use vaadin-date-picker as datepicker, and here's my code :

*

*HTML
<template>
<form class="form-inline m-b">

        <vaadin-date-picker id="min" placeholder="Start"></vaadin-date-picker>
        <vaadin-date-picker id="max" placeholder="End"></vaadin-date-picker>

</form>

            STAD

*Script :
class DataTableD extends Polymer.Element {
    static get is() {
        return 'data-table-d';
    }

    ready() {
        super.ready();

        var min     = this.$.min;
        var max     = this.$.max;

        //push method into search
        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
            alert("min . ." + min) //min . .[object HTMLElement]
            var startDate = new Date(data[0].replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"));
            if (min == null && max == null) {alert("startDate . ." + startDate);}
            if (min == null && startDate <= max) {alert("startDate . ." + startDate);}
            if (max == null && startDate >= min) {alert("startDate . ." + startDate);}
            if (startDate <= max && startDate >= min) {alert("startDate . ." + startDate);}

            return false;

        });
        // Event listener to the two range filtering inputs to redraw on
        min.addEventListener('value-changed', function() {
            window.setTimeout(function() {
                max.value = min.value;
                max.open();
            }, 500);

            this.$.mainTable.draw();
        });

    }

    _initializeDatatable() {
        if ( ! this.$mainTable) {
            // Make the jQuery object of the mainForm and arrivalTable.
            this.$mainTable = $(this.$.mainTable);
        }

        this._dataTable = this.$mainTable.DataTable({
        });
    }
}
window.customElements.define(DataTableD.is, DataTableD);

hope someone can share the idea to make it works, thx
===========================

A: Here below I tried to illustrate another way to filter :
DEMO

HTMLImports.whenReady( ()=> {

class DataTableD extends Polymer.Element {
    static get is() {
        return 'data-table-d';
    }
    static get properties() {
       return {
          minDate:{type:String },
          maxDate:{type:String }
    }}
    static get observers(){
       return ['_checkMinMaxDate(minDate, maxDate)']
    }
    ready() {
        super.ready();
    }

  _checkMinMaxDate(min,max) {
    console.log("Min-max:", min,max, this.items, this.xitems);
    var minn = min==="" ? "1000/01/01":min;
    var maxx = max==="" ? "2050/01/01":max;
    var newItems =  this.items.filter( (el)=> {
         return el.Startdate <= maxx &&
         el.Startdate >= minn ;
});
    this.set('xitems', newItems);

  }
}
window.customElements.define(DataTableD.is, DataTableD)

})

  <base href="https://cdn.rawgit.com/download/polymer-cdn/2.6.0.2/lib/">

  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="https://cdn-origin.vaadin.com/vaadin-core-elements/master/vaadin-date-picker/vaadin-date-picker.html">
  <link rel="import" href="https://cdn-origin.vaadin.com/vaadin-core-elements/master/vaadin-grid/all-imports.html">

<data-table-d id="tableDat" items="{{items}}"></data-table-d>

<dom-module id="data-table-d">
<template>

        <vaadin-date-picker id="min" placeholder="Start" value="{{minDate}}" on-change="_checkMinMaxDate"></vaadin-date-picker>
        <vaadin-date-picker id="max" placeholder="End" value={{maxDate}}  on-change="_checkMinMaxDate"></vaadin-date-picker>

         <vaadin-grid aria-label="Companies" items="[[xitems]]" multi-sort>

               <vaadin-grid-column>
                 <template class="header">
                   <vaadin-grid-filter path="Name"> </vaadin-grid-filter>
                   <vaadin-grid-sorter path="Name">Name</vaadin-grid-sorter>
                 </template>

                <template>[[item.Name]]</template>
               </vaadin-grid-column>

               <vaadin-grid-column>
                <template class="header">
                   <vaadin-grid-filter path="Position"> </vaadin-grid-filter>
                   <vaadin-grid-sorter path="Position">Position</vaadin-grid-sorter>
                 </template>

                <template>[[item.Position]]</template>
               </vaadin-grid-column>

              <vaadin-grid-column>
                <template class="header">
                   <vaadin-grid-filter path="Office"> </vaadin-grid-filter>
                   <vaadin-grid-sorter path="Office">Office</vaadin-grid-sorter>
                 </template>

                <template>[[item.Office]]</template>
               </vaadin-grid-column>

               <vaadin-grid-column>
                <template class="header">
                   <vaadin-grid-filter path="Age"> </vaadin-grid-filter>
                   <vaadin-grid-sorter path="Age">Age</vaadin-grid-sorter>
                 </template>

                <template>[[item.Age]]</template>
               </vaadin-grid-column>

               <vaadin-grid-column>
                <template class="header">
                   <vaadin-grid-filter path="Startdate"> </vaadin-grid-filter>
                   <vaadin-grid-sorter path="Startdate">Start date</vaadin-grid-sorter>
                 </template>

                <template>[[item.Startdate]]</template>
               </vaadin-grid-column>

               <vaadin-grid-column>
                <template class="header">
                   <vaadin-grid-filter path="Salary"> </vaadin-grid-filter>
                   <vaadin-grid-sorter path="Salary">Salary</vaadin-grid-sorter>
                 </template>

                <template>[[item.Salary]]</template>
               </vaadin-grid-column>

             </vaadin-grid>

</template>
</dom-module>

                Name
                Position
                Office
                Age
                Startdate
                Salary

                Name
                Position
                Office
                Age
                Start date
                Salary

                Tiger Nixon
                System Architect
                Edinburgh
                61
                2011/04/25
                $320,800

                Garrett Winters
                Accountant
                Tokyo
                63
                2011/07/25
                $170,750

                Ashton Cox
                Junior Technical Author
                San Francisco
                66
                2009/01/12
                $86,000

                Cedric Kelly
                Senior Javascript Developer
                Edinburgh
                22
                2012/03/29
                $433,060

                Airi Satou
                Accountant
                Tokyo
                33
                2008/11/28
                $162,700

                Brielle Williamson
                Integration Specialist
                New York
                61
                2012/12/02
                $372,000

                Herrod Chandler
                Sales Assistant
                San Francisco
                59
                2012/08/06
                $137,500

                Rhona Davidson
                Integration Specialist
                Tokyo
                55
                2010/10/14
                $327,900

                Colleen Hurst
                Javascript Developer
                San Francisco
                39
                2009/09/15
                $205,500

                Sonya Frost
                Software Engineer
                Edinburgh
                23
                2008/12/13
                $103,600

                Jena Gaines
                Office Manager
                London
                30
                2008/12/19
                $90,560

                Quinn Flynn
                Support Lead
                Edinburgh
                22
                2013/03/03
                $342,000

                Charde Marshall
                Regional Director
                San Francisco
                36
                2008/10/16
                $470,600

                Haley Kennedy
                Senior Marketing Designer
                London
                43
                2012/12/18
                $313,500

                Tatyana Fitzpatrick
                Regional Director
                London
                19
                2010/03/17
                $385,750

                Michael Silva
                Marketing Designer
                London
                66
                2012/11/27
                $198,500

                Paul Byrd
                Chief Financial Officer (CFO)
                New York
                64
                2010/06/09
                $725,000

                Gloria Little
                Systems Administrator
                New York
                59
                2009/04/10
                $237,500

                Bradley Greer
                Software Engineer
                London
                41
                2012/10/13
                $132,000

                Dai Rios
                Personnel Lead
                Edinburgh
                35
                2012/09/26
                $217,500

                Jenette Caldwell
                Development Lead
                New York
                30
                2011/09/03
                $345,000

                Yuri Berry
                Chief Marketing Officer (CMO)
                New York
                40
                2009/06/25
                $675,000

                Caesar Vance
                Pre-Sales Support
                New York
                21
                2011/12/12
                $106,450

                Doris Wilder
                Sales Assistant
                Sidney
                23
                2010/09/20
                $85,600

                Angelica Ramos
                Chief Executive Officer (CEO)
                London
                47
                2009/10/09
                $1,200,000

                Gavin Joyce
                Developer
                Edinburgh
                42
                2010/12/22
                $92,575

                Jennifer Chang
                Regional Director
                Singapore
                28
                2010/11/14
                $357,650

                Brenden Wagner
                Software Engineer
                San Francisco
                28
                2011/06/07
                $206,850

                Fiona Green
                Chief Operating Officer (COO)
                San Francisco
                48
                2010/03/11
                $850,000

                Shou Itou
                Regional Marketing
                Tokyo
                20
                2011/08/14
                $163,000

                Michelle House
                Integration Specialist
                Sidney
                37
                2011/06/02
                $95,400

                Suki Burks
                Developer
                London
                53
                2009/10/22
                $114,500

                Prescott Bartlett
                Technical Author
                London
                27
                2011/05/07
                $145,000

                Gavin Cortez
                Team Leader
                San Francisco
                22
                2008/10/26
                $235,500

                Martena Mccray
                Post-Sales support
                Edinburgh
                46
                2011/03/09
                $324,050

                Unity Butler
                Marketing Designer
                San Francisco
                47
                2009/12/09
                $85,675

                Howard Hatfield
                Office Manager
                San Francisco
                51
                2008/12/16
                $164,500

                Hope Fuentes
                Secretary
                San Francisco
                41
                2010/02/12
                $109,850

                Vivian Harrell
                Financial Controller
                San Francisco
                62
                2009/02/14
                $452,500

                Timothy Mooney
                Office Manager
                London
                37
                2008/12/11
                $136,200

                Jackson Bradshaw
                Director
                New York
                65
                2008/09/26
                $645,750

                Olivia Liang
                Support Engineer
                Singapore
                64
                2011/02/03
                $234,500

                Bruno Nash
                Software Engineer
                London
                38
                2011/05/03
                $163,500

                Sakura Yamamoto
                Support Engineer
                Tokyo
                37
                2009/08/19
                $139,575

                Thor Walton
                Developer
                New York
                61
                2013/08/11
                $98,540

                Finn Camacho
                Support Engineer
                San Francisco
                47
                2009/07/07
                $87,500

                Serge Baldwin
                Data Coordinator
                Singapore
                64
                2012/04/09
                $138,575

                Zenaida Frank
                Software Engineer
                New York
                63
                2010/01/04
                $125,250

                Zorita Serrano
                Software Engineer
                San Francisco
                56
                2012/06/01
                $115,000

                Jennifer Acosta
                Junior Javascript Developer
                Edinburgh
                43
                2013/02/01
                $75,650

                Cara Stevens
                Sales Assistant
                New York
                46
                2011/12/06
                $145,600

                Hermione Butler
                Regional Director
                London
                47
                2011/03/21
                $356,250

                Lael Greer
                Systems Administrator
                London
                21
                2009/02/27
                $103,500

                Jonas Alexander
                Developer
                San Francisco
                30
                2010/07/14
                $86,500

                Shad Decker
                Regional Director
                Edinburgh
                51
                2008/11/13
                $183,000

                Michael Bruce
                Javascript Developer
                Singapore
                29
                2011/06/27
                $183,000

                Donna Snider
                Customer Support
                New York
                27
                2011/01/25
                $112,000

EDIT
How to pass data outside Polymer
_checkMinMaxDate(min,max) {

    this.dispatchEvent(new CustomEvent('date-changed', { bubbles: true, composed: true, detail: {items:this.items, startDate:min, endDate:max }}));
}

outside of the Polymer:
window.addEventListener('date-changed', (e)=> {
     console.log(e.detail.items) // your items
     console.log(e.detail.startDate) // Date to start
     console.log(e.detail.endDate) // Date to end.
})


text:
Q: web-services-enhancements: ASP.NET - Missing nodes at SOAPEXTENSION I want to manipulate the soapbody before sending it.
I have inherited SoapExtension in myExtension class.
But, when i see the soapbody, some of the nodes were missing.
Code snippet:
public override void ProcessMessage(SoapMessage message)
        {
            StreamReader readStr;
            StreamWriter writeStr;
            string soapMsg1;
      //  System.Diagnostics.Debugger.Break();

        XmlDocument xDoc = new XmlDocument();
        // a SOAP message has 4 stages.  Weare interested in .AfterSerialize
        switch (message.Stage)
        {
            case SoapMessageStage.BeforeSerialize:
                break;

            case SoapMessageStage.AfterSerialize:
                {
                    // Get the SOAP body as a string, so we can manipulate...
                    String soapBodyString = getXMLFromCache();

.
.
.
.
Can anybody tell me the reason why they are missing ....
Thanks in advance,
Suresh

A: The problem is not with buffer/caching the object.
ex:
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool MOCEventStatusSpecified {
    get {
        return this.mOCEventStatusFieldSpecified;
    }
    set {
        this.mOCEventStatusFieldSpecified = value;
    }
}

This should be made true if we are sending the mOCEventStatus field. Otherwise, mOCEventStatus field won't appear in the output xml.


text:
Q: Transforming text to rows using R or Excel with multiple columns I have a dataset as mentioned below
CELL ID         VALUE 1 VALUE 2

54900, 41049    -111.55 -81.9
13238, 14960     -89.4 -74.32
56990, 41327     -106.99    -98.27
56285, 6436      -68.87 -74.41
17297,49055     -106.63 -95.84

I want to transform this data like this.
CELL ID VALUE 1 VALUE 2

54900 -111.55   -81.9
41049 -111.55   -81.9
13238 -89.4 -74.32

14960 -89.4 -74.32

... and so on ... I can use either excel or R

A: Probably you want something like the following:
df
      CELL_ID  VALUE1 VALUE2
1 54900,41049 -111.55 -81.90
2 13238,14960  -89.40 -74.32
3 56990,41327 -106.99 -98.27
4  56285,6436  -68.87 -74.41
5 17297,49055 -106.63 -95.84

ids <- strsplit(as.character(df$CELL_ID), split=',')

data.frame(CELL_ID = unlist(ids), VALUE1 = rep(df$VALUE1, sapply(ids, length)), VALUE2 = rep(df$VALUE2, sapply(ids, length)))

   CELL_ID  VALUE1 VALUE2
1    54900 -111.55 -81.90
2    41049 -111.55 -81.90
3    13238  -89.40 -74.32
4    14960  -89.40 -74.32
5    56990 -106.99 -98.27
6    41327 -106.99 -98.27
7    56285  -68.87 -74.41
8     6436  -68.87 -74.41
9    17297 -106.63 -95.84
10   49055 -106.63 -95.84


text:
Q: Changing port when running Jetty using jetty-runner I'm executing the following command line:
java -jar C:\WorkArea\jetty-runner.jar c:\name.war --port 9090

I'm expecting it to run on port 9090 but it keeps on running using port 8080 which is the default.
What am I missing?
When running through eclipse itself, it is using 8888 so it's not taking this info from there, where/how else can I control the port?
Thanks

A: The documentation of the Jetty Runner suggests that the port option should be passed before the WAR file:
java -jar C:\WorkArea\jetty-runner.jar --port 9090 c:\name.war


text:
Q: What do the inflection points of complex functions look like when plotted? The inflection points of real continuous functions have a relatively clear visual interpretation - they are the points when the function's graph moves from convex to concave, or vice-versa. Conversely, the critical points of a holomorphic function can also be visualised informatively. They're the ramification points, or the points around which the winding number is non-zero, and so on a domain-colouring plot of the function they are easily identified as the points where the plot moves locally through the full spectrum, or as the convergence points of the lines of equal phase. However, I have not come across a visual intuition for the inflection points of holomorphic functions, and would be interested in any suggestions.
This came up in teaching high school mathematics to a few advanced students, where I wanted to emphasise the importance of the inflection point in the study of cubic functions. Obviously, the original reason complex numbers attracted popular interest was the usefulness of passing to a complex domain to explain the properties, and find the roots, of real-valued cubic polynomials, so I was interested in what the inflection point of a complex cubic would 'look like'

A: Here are a few quick plots in Mathematica.
Later, may update with more details.


text:
Q: Error en acceso a recursos desde servidor publico Tengo el siguiente problema, es un poco extraño.
Dispongo de un servidor con Ubuntu Server 18, el cual cuenta con una IP publica contratada con el ISP.
El servidor funciona correctamente desde la red externa al router, es decir, al acceder desde otra red que no sea la de la empresa, todo funciona correctamente, se puede acceder desde SSH, la pagina web, los repositorios, entre otros. Pero desde la red local no es posible acceder a dichos recursos, aunque el servidor responde el ping.
64 bytes from 18X.1XX.XXX.XXX: icmp_seq=0 ttl=62 time=36.324 ms
Al acceder por SSH, se genera el siguiente error, Connection reset by 18X.1XX.XXX.XXX port 22 y en la traza del servidor, se puede ver el mismo error. Por otro lado, la pagina no carga correctamente, las bases de datos son inaccesibles, es decir, como si todo estuviera bloqueado.
Unicamente pasa cuando estoy conectado en la red local, de lo contrario todo funciona correctamente, ya valide el Netplan, con el ISP el Passthrough y esta correcto, el Firewall lo desactive por un momento, pero nada, no sé que puede ser.
Nota: El servidor no esta por DMZ

Agradezco cualquier ayuda.

A: Si estas por una red interna, ¿le has añadido esa red interna al servidor?
Lo suyo seria que dentro de la LAN todas las conexiones sean por una 192.168.x.x en vez de que salga fuera.
Ten en cuenta que para poder hacer eso tienes que tener configurado el servidor para que responda a IPs de la red LAN, tendrás que modificar:

*

*firewalld (en caso de que lo tengas): https://linuxconfig.org/how-to-open-allow-incoming-firewall-port-on-ubuntu-18-04-bionic-beaver-linux

*Apache: Deberías de tener algo así:
<VirtualHost *:80>
    ServerName  xxx.com
    ServerAlias www.xxx.com
    DocumentRoot /var/www/xxx

    <Directory "/var/www/xxx">
        DirectoryIndex index.html index.php
        AllowOverride All
        Allow from All
        Options FollowSymLinks
        Require all granted

    </Directory>

    LogLevel notice
    CustomLog "/var/log/httpd/xxx.access.log" combined
    ErrorLog "/var/log/httpd/xxx.error.log"
</VirtualHost>

Y si quieres poder conectarte a la base de datos con algun gestor tipo SqlYog o MySQLWorkBench también tendrás que modificar el servicio de MySQL:
Editar /etc/mysql/mysql.conf.d/mysqld.cnf y dentro de [mysqld] poner:
bind-address = 0.0.0.0

El problema de esto es que quedaría abierto el puerto a todo internet. Lo mejor en ese caso es ponerlo a localhost y que quien se quiera conectar lo haga mediante un túnel SSH.
https://linube.com/ayuda/articulo/240/como-conectar-un-servidor-mysql-de-forma-remota
Revisa todo esto, lo mejor es que la IP pública solo se use fuera de la red y que dentro una una IP privada.
Si tienes dudas me comentas.


text:
Q: How to push into an array of object using the spread operator to a specific element I have an array  as such
const arr = [a={} , b={}]

Now I know the spread operator is not for mutation or pushing but it is very easy to do so with.
I want this button to add elements to a when it's pressed
 <Button
title= {this.props.title}
 onPress={ this.roomNumberPressed }
 />

so the end results be something like :
arr = [a={1,2,3} , b={3,4,5}]

A:
I want this button to add elements to a when it's pressed

As you said in your question, spread notation isn't for adding to existing objects. Your options are:

*

*Use spread to create a new object and assign that new object to a:
a = {...a, ...theNewPropertiesToAdd};

*Use Object.assign to add new properties to the existing a:
Object.assign(a, theNewPropertiesToAdd);

Note I've just used a above because your const arr = [a={}, b={}] is a syntax error, and I can't tell whether you mean const arr = [{}, {}] (in which case a above is arr[0]), or const arr = {a: {}, b: {}} (in which case a above is arr.a [and arr isn't an array]).


text:
Q: How to use super() in this complex multiple inheritance situation? I'm writing a library that provides subclasses of each of two existing base classes with extra functionality.
Rather than explain the arrangement in words, here's a diagram:

And minimal code:
class Base0:
    pass

class Base1(Base0):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.foo = something()

class Base2(Base0):
    pass

class Mixin:
    def __init__(self, bar):
        self.bar = bar
        # More code

class Child1(Base1, Mixin):
    def __init__(self, *args, **kwargs):
        Base1.__init__(self, *args, **kwargs)
        Mixin.__init__(self, some_function_of(self.foo))

class Child2(Base2, Mixin):
    def __init__(self, *args, **kwargs):
        Base2.__init__(self, *args, **kwargs)
        Mixin.__init__(self, something_else())

The Base classes are outside my control. I wrote the Mixin and Child classes. Users of my library will subclass the Child classes, so it's very important that the inheritance be sane and correct.
What I'd like to do is use super().__init__ in the Child classes rather than explicitly invoking the Base and Mixin initializers. The reason this is nontrivial is that in Child1, the value passed to the Mixin initializer can't be determined until after the Base1 initializer has run.
What is the simplest/sanest way to set this up?


text:
Q: Filter data from array Angular 2 I have 2 arrays and I want to filter data based on column value. I am using below code but It is not working.
const result = data.map(data1 => {
            return Object.assign({}, data1, this.data2.filter(data2 => data2.Id !== data1.Id)[0]);
        });

Data 1 :
[
  {
    "id": 2,
    "name": "data 2",
  },
  {
    "id": 3,
    "name": "data 3",
  }
]

Data 2 :
[
  {
    "id": 2,
    "name": "data 2"
  },
  {
    "id": 3,
    "name": "data 3"
  },
  {
    "id": 4,
    "name": "data 4"
  }
]

It should return below output.
[
{
    "id": 4,
    "name": "data 4"
}
]

How do I solve this ?

A: What you're looking for is a difference of 2 arrays of objects, see: Difference between two array of objects in JavaScript
You can also go by pure ids like this:
let ids = data1.map(item => item.id);
let filteredData = data2.filter(item => ids.indexOf(item.id) === -1);


text:
Q: Differences between Mac and Windows CSS When I view this page on Chrome on Mac, the h1 text is on one line and scales correctly with the viewport on desktop screens. However, in Chrome on Windows machines, the h1 text breaks to two lines. I'm not sure what differences there are between OS/browser default styles, but I would like to always correctly scale the text size to be on one line for desktop (with the gold bar behind). I am using Foundation 6 for some responsive classes
Mac Screenshot
View Mac Screenshot
Windows Screenshot
View Windows Screenshot
HTML

    <video loop muted autoplay>
        <source src="/img/home/tu-web-header.webm" type="video/webm">
        <source src="/img/home/tu-web-header.mp4" type="video/mp4">
        Your browser does not support the video tag.
    </video>
    <video loop muted autoplay class="hide-for-medium">
        ## <source src="/img/home/tu-web-header.webm" type="video/webm">
        <source src="/img/home/tu-web-header-vertical.mp4" type="video/mp4">
        Your browser does not support the video tag.
    </video>

ON
 PURPOSE

            Schedule Your Visit
            Make Your Deposit

CSS
    #video-header-container {
        position: relative;
        height: calc(100vh - 70px);
    }
    @media (min-width: 1024px) {
         #video-header-container {
            height: calc(100vh - 165px);
         }
    }
    #video-header-container::before {
        content:"";
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.2);
    }
    #video-header-container video {
        position: absolute;
        background: var(--tu-purple);
        width: 100%;
        height:100%;
        -o-object-fit: cover;
        object-fit: cover;
    }

    #video-header-text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    #video-header-text h1 {
        font-family: var(--font-sans);
        font-weight: bold;
    }
    #video-header-text h1::before {
        content:'';
        background-color: var(--tu-gold);
        position: absolute;
        top: .45em;
        height: .5em;
        left: -5rem;
        right: -5rem;
        z-index: -1;
    }
    @media (max-width: 1023px) {
        #video-header-text h1 {
            font-size: 3.75rem;
        }
        #video-header-text h1::before {
            left: 3rem;
            right: 3rem;
        }
        #video-header-text h1::after {
            content:'';
            background-color: var(--tu-gold);
            position: absolute;
            bottom: .4em;
            height: .5em;
            left: -2rem;
            right: -2rem;
            z-index: -1;
        }
    }
    @media (min-width: 1024px) {
        #video-header-text h1 {
            font-size: max(4.75rem, min(7.4vw, 7.5rem));
            font-size: clamp(4.75rem, 7.49vw, 7.5rem);
        }
    }


text:
Q: Does this pattern of summing polygonal numbers to get a square repeat indefinitely? I am using the table of polygonal numbers on this site:
http://oeis.org/wiki/Polygonal_numbers
The first row of the table gives the value of $n=0,1,2,3,...$. The first column gives the polygonal numbers $P_{N}(n)$ starting with $N=3$.
Here's the pattern, the sum is done by adding elements of the same column starting with the triangular numbers.
$$1+1+1+1=4=2^2$$
$$3+4+5+6+7=25=5^2$$
$$6+9+12+15+18+21=81=9^2$$
$$10+16+22+28+34+40+46=196=14^2$$
...
The squares on the right hand side are given by $n+T_{n}$. The sum of index $(n+1)$ has one more element than that of $n$.
1-Does this pattern repeat indefinitely? (I suspect the answer is yes but I can't prove it)
2-Do we know why we have such a pattern?
Edit 03-05-2019
Following the suggestion of Eleven-Eleven, I looked for other patterns similar to the one above. I found one that is even simpler. This time we skip the triangular numbers when we calculate the sum. We start with the squares and sum up enough terms to get another square.
$$1=1^2=T_{1}^2$$
$$4+5=3^2=9=T_{2}^2$$
$$9+12+15=6^2=36=T_{3}^2$$
$$16+22+28+34=10^2=100=T_{4}^2$$
$$25+35+45+55+65=15^2=225=T_{5}^2$$
We see the same pattern as above. The square with index $(n+1)$ requires the addition of one more term than the square with index $n$. The number of elements to sum up to get the square $T_{n}^2$ is simply $n$.
Can this be stated as the following theorem?
The square of a triangular number $T_{n}$ can be expressed as the sum of $n$ polygonal numbers excluding the triangular number itself.

A: Let the first term be a triangular number $n(n+1)/2$, the common difference between successive terms be $n(n-1)/2$, and the number of terms be $n+3$.  Then the average of all terms is
$\dfrac{n(n+1)}{2}+\dfrac{n+2}{2}×\dfrac{n(n-1)}{2}=\dfrac{n^2(n+3)}{4}$
Multiplying this by the number of terms $n+3$ then gives a sum of $(n(n+3)/2)^2$.

A: This is a much more drawn out approach using summations.  It doesn't have the elegance of Oscar's solutions, but it still works.  You have that with $T_k$ being the $k$-th Triangular number (here $T_0=0$)
$$\sum_{k=1}^{4+0}{[T_1+(k-1)T_0]}=(T_1+1)^2$$
$$\sum_{k=1}^{4+1}{[T_2+(k-1)T_1]}=(T_2+2)^2$$
$$\sum_{k=0}^{4+2}{[T_3+(k-1)T_2]}=(T_3+3)^2$$
This suggests that
$$\sum_{k=1}^{m+4}{[T_{m+1}+(k-1)T_{m}]}=(T_{m+1}+(m+1))^2$$
Since summation is linear, we have
\begin{eqnarray*}\sum_{k=1}^{m+4}{[T_m+(k-1)kT_{m-1}]}&=&T_{m+1}\sum_{k=1}^{m+4}1+T_m\sum_{k=1}^{m+4}{(k-1)}\\&=&T_{m+1}(m+4)+T_m\sum_{k=1}^{m+3}{k}
\end{eqnarray*}
Using the formula for the $m$-th Triangular number, we have
$$=\left[\frac{(m+1)(m+2)}{2}\right](m+4)+\left[\frac{m(m+1)}{2}\right]\left[\frac{(m+3)(m+4)}{2}\right]$$
Factoring and simplifying gives
$$\frac{(m+1)(m+4)}{2}\left[(m+2)+\frac{m(m+3)}{2}\right]=\frac{(m+1)^2(m+4)^2}{4}$$
Now, the right hand side
\begin{eqnarray*}[T_{m+1}+(m+1)]^2&=&T_{m+1}^2+2(m+1)T_{m+1}+(m+1)^2\\&=&\frac{(m+1)^2(m+2)^2}{4}+2(m+1)^2\frac{(m+2)}{2}+(m+1)^2
\end{eqnarray*}
Factoring out an $(m+1)^2$,
\begin{eqnarray*}\frac{(m+1)^2(m+2)^2}{4}+2(m+1)^2\frac{(m+2)}{2}+(m+1)^2&=&(m+1)^2\left[\frac{(m+2)^2}{4}+\frac{4(m+2)}{4}+\frac{4}{4}\right]\\&=&\frac{(m+1)^2}{4}\left[(m^2+4m+4)+(4m+8)+4\right]\\&=&\frac{(m+1)^2}{4}(m^2+8m+16)\\&=&\frac{(m+1)^2(m+4)^2}{4}
\end{eqnarray*}
Since both expressions equal $\frac{(m+1)^2(m+4)^2}{4}$, we are done.
EDIT:
For the new problem, note the first term in each line is a successive square and as above, the common difference is a triangular number.  Thus we have to prove, in general,
$$\sum_{k=1}^n[n^2+(k-1)T_{n-1}]=T_n^2$$
The left hand side then can be written as
\begin{eqnarray*}\sum_{k=1}^n[n^2+(k-1)T_{n-1}]&=&\sum_{k=1}^n n^2+T_{n-1}\sum_{k=1}^n(k-1)\\&=&n^3+T_{n-1}\sum_{k=1}^{n-1}k\\&=&n^3+\frac{(n-1)n}{2}\cdot\frac{(n-1)n}{2}\\&=&n^2\left(n+\frac{(n-1)^2}{2^2}\right)\\&=&\frac{n^2}{2^2}(n+1)^2\\&=&\left[\frac{n(n+1)}{2}\right]^2\\&=&T_n^2
\end{eqnarray*}
And we're done.

A: I'm adding another answer because I wanted to try and use the formula for polygonal numbers as given here in an attempt to better answer the original question by the OP.  In both cases above we exploited the arithmetical sequence properties and only used Triangular numbers.  Can we get the same result strictly using the polygonal number formula
$$P(s,n)=\frac{n^2(s-2)-n(s-4)}{2}$$
where $n$ represents the sequence number and $s$ represents the number of sides in a polygonal number.  So, lets look at an example.  In the second row, the OP has that
$$3+4+5+6+7=25=(T_2+2)^2$$
Well, $3,4,5,6,$ and $7$ are the second triangular, square, pentagonal, hexagonal, and heptagonal numbers, so $n=2$ and $s$ is indexed... therefore, we have
\begin{eqnarray*}\sum_{k=1}^5{P(k+2,2)}&=&\sum_{k=1}^5{\left[\frac{4((k+2)-2)-2((k+2)-4)}{2}\right]}\\&=&\sum_{k=1}^5{\left[\frac{4k-2(k-2)}{2}\right]}\\&=&\sum_{k=1}^5\left(k+2\right)\\&=&\sum_{k=1}^5{k}\\&=&T_5
\end{eqnarray*}
Now, this can be generalized.  The claim is
$$\sum_{k=1}^{m+3}{P((k+2),m)}=\left(T_m+m\right)^2$$
Proof:
\begin{eqnarray*}\sum_{k=1}^{m+3}{P((k+2),m)}&=&\sum_{k=1}^{m+3}\left[\frac{m^2((k+2)-2)-m((k+2)-4)}{2}\right]\\&=&\sum_{k=1}^{m+3}\left[\frac{m^2k-mk+2m}{2}\right]\\&=&\frac{m^2}{2}\sum_{k=1}^{m+3}{k}-\frac{m}{2}\sum_{k=1}^{m+3}{k}+m\sum_{k=1}^{m+3}1\\&=&\frac{(m-1)m}{2}\sum_{k=1}^{m+3}k+m(m+3)\\&=&\frac{(m-1)m}{2}\frac{(m+3)(m+4)}{2}+\frac{4m(m+3)}{4}\\&=&\frac{m(m+3)}{4}\left[(m-1)(m+4)+4\right]\\&=&\frac{m(m+3)}{4}\left(m^2+3m\right)\\&=&\frac{m^2(m+3)^2}{2^2}\\&=&\left[\frac{m(m+3)}{2}\right]^2\\&=&\left[\frac{m(m+1+2)}{2}\right]^2\\&=&\left[\frac{m(m+1)+2m}{2}\right]^2\\&=&\left(T_m+m\right)^2
\end{eqnarray*}


text:
Q: How to make screensaver to appear and disappear based on time? I have a screensaver script and it shows a screensaver after some time (e.g. 10 sec). How to make to stop screensaver after some time when it's started (e.g. after 5 sec) and then repeat again the same every (e.g. 10sec) but to calculate time from when it stop.
var screensaver_active = false;

function show_screensaver() {
  $('#screensaver').fadeIn();
  screensaver_active = true;
  screensaver_animation();
}

function stop_screensaver() {
  $('#screensaver').fadeOut();
  screensaver_active = false;
}

function getRandomColor() {
  var letters = '0123456789ABCDEF'.split('');
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.round(Math.random() * 15)];
  }
  return color;
}

setInterval(function() {
  show_screensaver();
  stop_screensaver();
}, 10000);

function screensaver_animation() {
  if (screensaver_active) {
    $('#screensaver').animate({
      backgroundColor: getRandomColor()
    }, 400, screensaver_animation);
  }
}

A: Try calling stop function within start function like this
function show_screensaver() {
$('#screensaver').fadeIn();
screensaver_active = true;
screensaver_animation();
setTimeout(function(){stop_screensaver();},5000);
}
function stop_screensaver() {
  $('#screensaver').fadeOut();
  screensaver_active = false;
setTimeout(function(){show_screensaver();},10000);
}


text:
Q: How do I control domain computer idle lock timeout via GPO? Everything I find online makes reference to screen savers, but we don't use screen savers... our displays go to sleep, therefore, I don't want to "force" a screen saver, etc...
I'd simply like to specify how long a domain joined computer should be idle before it locks the user...
Update:
My computer locks after X minutes of inactivity... no screen saver starts, I simply see the windows lock screen.  This seems to involve neither a screen saver, nor a display sleep.

A: This is commonly done with the screen saver + require password on wake up. I beleive this is found under User Configuration \ Policies \ Administrative Templates \ Control Panel \ Personalisation in Server 2k8.
Thats how I have done it in large environments anyway. Make sure you specify a screen saver explicitly in your GPO since this doesn't work if no screensaver is specified.


text:
Q: Windbg command's each result as parameter in script I intend to search opcodes in specific memory area in process's dump.
I want to have some conditions while searching.
like:
$$><<>script.wds #call 00400000 L? 01000000
for(00400000 ~ 01000000)
{
    // this condition is if argument's opcode which is address is not in this area
   .if(arg1's opcode !in 00400000 ~ 01000000)
      .print arg1
}

A: You can use a combination of #, .foreach and $spat.
Lets say you want to find the few first call opcodes in notepad!WinMain. You could do something like this:
0:000> .foreach (addr {# call notepad!WinMain L20}) { .if ($spat("addr", "notepad!*:")) {.echo addr} }
notepad!WinMain+0xa:
notepad!WinMain+0x19:
notepad!WinMain+0x20:
notepad!WinMain+0x33:
notepad!WinMain+0x39:
notepad!WinMain+0x45:

And now the explanation.
# call notepad!WinMain L20 searches for the string "call" in the disassembly on the specified range. This is the output:
0:000> # call notepad!WinMain L20
notepad!WinMain+0xa:
01002940 ff1514110001    call    dword ptr [notepad!_imp__GetCommandLineW (01001114)]
notepad!WinMain+0x19:
0100294f ff151c120001    call    dword ptr [notepad!_imp__GetSystemMetrics (0100121c)]
notepad!WinMain+0x20:
01002956 ff1510110001    call    dword ptr [notepad!_imp__GetProcAddress (01001110)]
notepad!WinMain+0x33:
01002969 ffd0            call    eax
notepad!WinMain+0x39:
0100296f e874f2ffff      call    notepad!SkipProgramName (01001be8)
notepad!WinMain+0x45:
0100297b e8e51b0000      call    notepad!NPInit (01004565)

The .foreach (var {cmd}) {commands} executes cmd, splits the output at whitespaces, and executes {commands} once for each of the tokens it got with "var" being replaced with that token.
Without the .if we'd get something like:
0:000> .foreach (addr {# call notepad!WinMain L20}) {.echo addr}
notepad!WinMain+0xa:
01002940
ff1514110001
call
dword
ptr
[notepad!_imp__GetCommandLineW
(01001114)]
notepad!WinMain+0x19:
0100294f
ff151c120001
call
dword
ptr
[notepad!_imp__GetSystemMetrics
 .
 .
 .

Finally we add the .if to check whether our token starts with "notepad!" and ends with ":". Note that we have to test for the colon at the end. Otherwise we might get "notepad!SkipProgramName" and "notepad!NPInit". Even testing for "notepad!WinMain*" isn't enough, since it might be the target of local jumps.

Now, if you want to pass this address to any command, you have to get rid of the colon at the end of the addr alias the .foreach command created. I'm not sure there's even a way to do it, so we do one last trick. Every time we find and addr that fits the pattern we set a flag, and at every iteration we check the flag. If the flag is raised, we use the current token. Since the output of # is of the form
Symbol:
address opcode_byte opcode_mnemonic argument ...

The token following the symbol that matches our pattern is a clean address.
For example, the following command disassembles two opcode for each call found:
0:000> .foreach (addr {# call notepad!WinMain L20}) { .if (@$t0==1) { u addr L2; r @$t0=0;}; .if ($spat("addr", "notepad!*:")) { r @$t0 = 1} }
notepad!WinMain+0xa:
01002940 ff1514110001    call    dword ptr [notepad!_imp__GetCommandLineW (01001114)]
01002946 68d8130001      push    offset notepad!`string' (010013d8)
notepad!WinMain+0x19:
0100294f ff151c120001    call    dword ptr [notepad!_imp__GetSystemMetrics (0100121c)]
01002955 50              push    eax
notepad!WinMain+0x20:
01002956 ff1510110001    call    dword ptr [notepad!_imp__GetProcAddress (01001110)]
0100295c 33f6            xor     esi,esi
notepad!WinMain+0x33:
01002969 ffd0            call    eax
0100296b ff7514          push    dword ptr [ebp+14h]
notepad!WinMain+0x39:
0100296f e874f2ffff      call    notepad!SkipProgramName (01001be8)
01002974 50              push    eax
notepad!WinMain+0x45:
0100297b e8e51b0000      call    notepad!NPInit (01004565)
01002980 85c0            test    eax,eax

(The pseudo-register $t0 is the flag.)
And now, after this horror is done I join Thomas in suggesting you use PyKd if you want to go even a further beyond that.
The mere fact that we can do this using WinDbg's awful awful scripting language doesn't mean that we should.

A: I'm not exactly sure if I understood what you need, but I think it is similar to the following.
Create a script which does what you want, using pseudo registers, e.g.
.for(r @$t2=@$t0; @$t2<@$t1; r @$t2=@$t2+1) {.printf "%d, ", @$t2}

Set up the "parameters" in pseudo registers
0:000> r @$t0 = 0x4
0:000> r @$t1 = 0x10

Then run the script:
0:000> $$>< script.wds
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,

Considering the whole task, I'd not recommend doing that in plain WinDbg and use some higher level abstraction such as PyKD, because

*

*it's not easy to get the opcode from an ASM statement

*you might want to search in !addresses only that are PAGE_EXECUTE

*WinDbg scripts are often cryptic and not very maintainable

A: your query is unclear do you want to do something like this
0:000> .shell -ci ".echo"  type c:\foo.txt
# ${$arg1} ${$arg2} ${$arg3}.shell: Process exited

running the above script by providing three arguments you can search for
any instruction in the range you provide
the argument 1 is call so i want to search for call instructions
arg 2 is an expression  therefor windbg will be evaluated to an address like 0x12340000
arg 3 again is an expression evaluated to size
result as follows
0:000> $$>a< c:\foo.txt call windbg L900
windbg+0x1009:
01341009 e8340170e8      call    e9a41142
windbg+0x10b5:
013410b5 e834010000      call    windbg+0x11ee (013411ee)
windbg+0x1171:
01341171 e8000060e8      call    e9941176


text:
Q: Objective-C equivilent of Python's __getattr__ / __setattr__ methods Is there a default method of NSObject to simulate something similar to Python's getattr / setattr?
I want to get and set the members of an instance having only the name of the member.
I want to accomplish something like this:
/* someUnknownInstance is defined elsewhere, and has an instance variable named "x", with an initial value of 5 */
...
id myInstance = someUnknownInstance;  /* myInstance.x = 5 */
NSNumber myInstanceVariable = [myInstance getAttr:@"x"];  /* myInstanceVariable = 5 */
[myInstance setAttr:@"x" value:(myInstanceVariable + 1)];  /* myInstance.x = 6 */

A: The semi easy way..
Class _class_ = [myInstance class];
objc_property_t property = class_getProperty(_class_, "x");
// property is NULL when there is no such property
if (property) {
    // because ObjC has internal members name scheme, leading '_' = "_x"
    const char * publicname = property_getName(property);
    // the public property name
    NSString *publicKey = [NSString stringWithCString:publicname encoding:NSASCIIStringEncoding];
    // getter
    int i = [[myInstance valueForKey:publicKey] intValue];
    // setter
    [myInstance setValue:@(i+1) forKey:publicKey];
}

The crazy way.. lots of code for just adding + 1 to property "x".
#import <objc/runtime.h>
#import <string.h>

static void* getIvarPointer(id object, char const *propertyname) {
    Ivar ivar = class_getInstanceVariable(object_getClass(object), propertyname);
    if (!ivar) return 0;
    return (uint8_t*)(__bridge void*)object + ivar_getOffset(ivar);
}

-(void)goCrazyWithObjcRuntime:(id)myInstance {

    /// search class of id for specific property name and add 1

    Class _class = [myInstance class];

    objc_property_t property = class_getProperty(_class, "x");

    if (property) {

        Boolean isInt = false;
        const char * attr = property_getAttributes(property);

        // lets iterate the attributes of the property
        char *attribs = strdup(attr);
        char *pt = strtok(attribs,",");
        while (pt != NULL) {
             if (strcmp(pt, "N" ) == 0) printf("nonatomic ");
             else if (strcmp(pt, "Ti") == 0) {
                 printf("integer ");
                 isInt = true;
             }
             else if (strcmp(pt, "R" ) == 0) printf("readonly ");
             else if (strcmp(pt, "C" ) == 0) printf("copy ");
             else printf("other property description:%s", pt);
            pt = strtok(NULL, ",");
        }

        // the public propertyname
        const char * name = property_getName(property);
        NSLog(@"public propertyname:'%s' with attributes:'%s'",name, attr);

        // transform public property name back to internal class member
        char objcInternalPrefix[4] = "_";
        char *backingPropertyName = strncat(objcInternalPrefix, name, strlen(name));

        // getter, catch the Ivar
        int *ptr = getIvarPointer(myInstance, backingPropertyName);
        NSLog(@"x=%d",*ptr);

        // setter, beware math without type check here
        // Get a pointer to the instance variable.  Returns NULL if not found.
        int *intPtr = getIvarPointer(myInstance, backingPropertyName);
        if (intPtr) {
            // Now, add 1.
            if (isInt) {
                *intPtr = *intPtr + 1;
            }
        }

    }
}


text:
Q: How can I invoke a callback given to a yield in javascript v8 generator code? I'm attempting to understand javascript generators in node.js v8, without using any third party libraries.
I want to try having a generator that invokes an asynchronous callback (something like a web request) and returns the value that is called back.
My code (using Node v0.11.12) looks like:
var callbackWrapper = function (){
  return function(callback) {
    callback(null, 5);
  };
};

var result = null;
var generator = (function *(){
  result = yield callbackWrapper();
})();

var nextIteration = generator.next();

At the end of this code, nextIteration.value is a function, and result is still null.
It was my understanding that if yield is given a method with a callback, it invokes that callback.
My goal is to somehow get the value, 5, that is called back.
What is the way to do this?  Do I have to pass some function to nextIteration.value and invoke it?

A: Let's clarify some things.

It was my understanding that if yield is given a method with a callback, it invokes that callback.

yield does not invoke anything. The purpose of yield is, well, to yield... When you define a generator you define an entity which yields values. It has nothing to do with async code. We can, however, leverage an important property of generators to handle async code.
Generators, by their definition, yield values. Here's the important part - between one yield to another the generator is suspended. In other words, it waits until it is asked to yield the next value. The internal state of the generator is kept in memory (on the stack) until the generator is exhausted (no more values to yield).
Another important property of generators is that we can send values back, thus changing their internal state.
So if we can suspend generators (make them wait) and we can send values back; we can essentially make them wait for some async operation to complete and then send the result back.

What is the way to do this? Do I have to pass some function to nodeIteration.value and invoke it?

Basically you need to wrap you code with a generator. Every time you start an async operation you make the generator wait by using yield. When the async operation completes you resume your generator by sending the result back with next(result).
I wrote an extensive post to explain this issue, which I'm sure will help you understand. Take a look: http://eyalarubas.com/javascript-generators-and-callbacks.html

A: Generators don't handle node style callbacks on their own. Instead it's returning the function that you wrapped inside of the callbackWrapper thunk. As yield only returns a value and then pauses execution at that point in time.
Generators weren't really designed for control flow but you can build on top of them to create control flow libraries like co, suspend, etc..
Basically what these libraries do (I'm oversimplifying here), is take your generator function and recursively call it until it tells them that it has finished.
Each of these libraries handles the internal yields in different ways, for example co turns everything it can handle into thunks internally. While suspend uses node-style callbacks for everything internally.
At each yield they check to see what was yielded to them a thunk, promise, generator, or whatever constructs that library handles, and abstracts the control out based on when they are completed.
You can build a structure around generators to handle asynchronous thunked functions but it's not for the feint of heart. Basically it would go something like this (Note: don't use this other than for playing around as its missing all the normal checks, error handling, etc..):
function controlFlow(genFunc){
  // check to make sure we have a generator function otherwise explode

  var generator; // reference for an initialized generator

  // return a funcion so that execution time can be postponed
  return function(){
    runGen(genFunc());
  }

  function runGen(generator){
    var ret = generator.next();

    // here the generator is already finished we we'll return the final value
    if(ret.done){
      return ret.value
    }

    // here we'll handle the yielded value no matter what type it is
    // I'm being naive here for examples sake don't do this
    if(typeof ret.value === 'function'){
      // oh look we have a regular function (very faulty logic)
      // we wouldn't do this either but yeah
      ret.value(function(err, result){
        console.log(result);
      });
    }

   // oh we got another item like an array or object that means parallelism or serialization depending on what we got back
   // turn array, object, whatever into callback mechanisms and then track their completion
   // we're just going to fake it here and just handle the next call
   runGen(generator);
  }
}

function thunked(callback){
  return function(){
    callback(null, 5);
  };
};

function regular(callback){
  console.log('regular function call');
  callback(null, 'value');
};

controlFlow(function *(){
  yield thunked(function(err, result){
    console.log(err);
    console.log(result);
  });
  yield regular;
  yield thunked(function(err, result){
    console.log('Another Thunked');
  });
  yield regular(function(err, result){
    console.log(err);
    console.log(result);
  });
})();

A: result won't get assigned until you send a value back to the generator by calling next again with the value you want to assign to result. In your example that would look like this:
nextIteration.value(function (error, value) {
  generator.next(value);
});


text:
Q: R: Using nested foreach to fill a multidimensional array I am stuck with parallelizing a nested for-loop, which populates a multidimensional array. I am trying to use foreach but have little experience/problems with combining the results/populating the multidimensional array. The conventional approaches with c, cbind, etc. did not yield the correct results and I could not transfer solutions to similar questions to mine.
For the minimal example, the array is:
data<-array(list(),c(3,4,5))

The initial nested loops:
for ( i in 1:3) {
 for ( j in 1:5) {
#here would be a set of functions and large/timely operations which lead to the results A-D and can be parallelized. The results are matrices of different sizes.
    resultA=matrix(c(1:6)*1,nrow=3)
    resultB=matrix(c(1:63)*1,nrow=3)
    resultC=matrix(c(1:12)*1,nrow=3)
    resultD=matrix(c(1:15)*1,nrow=3)
    data[[i,1,j]]=resultA
    data[[i,2,j]]=resultB
    data[[i,3,j]]=resultC
    data[[i,4,j]]=resultD
  }
}

With foreach try no. 1 with %:% and %do%:
library(foreach)

foreach ( i = 1:3) %:%
  foreach ( j = 1:5) %do% {
    resultA=matrix(c(1:6)*1,nrow=3)
    resultB=matrix(c(1:63)*1,nrow=3)
    resultC=matrix(c(1:12)*1,nrow=3)
    resultD=matrix(c(1:15)*1,nrow=3)
    data[[i,1,j]]=resultA
    data[[i,2,j]]=resultB
    data[[i,3,j]]=resultC
    data[[i,4,j]]=resultD
  }

This variant will write the array correctly and output a list from the foreach function. Here I lack the experience to set or define a correct .combine function.
With foreach try no. 2 with %:% and %dopar%:
library(foreach)
library(doParallel)
cl <- makeCluster(2)
registerDoParallel(cl)

foreach ( i = 1:3) %:%
  foreach ( j = 1:5) %dopar% {
    resultA=matrix(c(1:6)*1,nrow=3)
    resultB=matrix(c(1:63)*1,nrow=3)
    resultC=matrix(c(1:12)*1,nrow=3)
    resultD=matrix(c(1:15)*1,nrow=3)
    data[[i,1,j]]=resultA
    data[[i,2,j]]=resultB
    data[[i,3,j]]=resultC
    data[[i,4,j]]=resultD
  }
stopCluster(cl)

Unsurprisingly, the array is not populated in this variant, and I still lack the skill to set or define a correct .combine function.
I would appreciate any suggestions to solve the problem of combining the results A-B into the desired array. Avoiding the nested for-loops entirely could be the next step; however, I am mainly interested in getting the nested foreach and parallel processing running.


text:
Q: Array declaration in Java
Possible Duplicate:
Difference between int[] array and int array[]

Is int[] arr; functionally the same as int arr[];?

A: Yes. You can put the braces in either place when declaring an array.
Bonus: you can even put 'em here:
int []arr

A: Yes, the functionality is the same. You can have the braces anywhere.
int[] a,b,c[];

is equivalent to
int a[],b[],c[][];

A: It's just the matter of style. You can pick the style you like. They perform exactly the same. Some claim that if you write "int[] array", it will be clearer that it's an array of integer rather than writing "int array[]".

A: It is, it's just to appease C++ developers they include int arr[]. (Or at least what I told in school)

A: Yes it's the same. int[] arr is more convenient though.


text:
Q: How to create the pair without assembly in UniswapV2Factory I'm going to deploy the Uniswap contract on my customized Ethereum.
Could I replace  fancy footwork in the factory by Solidity code?
I need to update this code assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt)} into general solidity code.
I tried this, but not working well.

A: I found the solution
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
  pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}

I updated above code into
UniswapV2Pair newPair = new UniswapV2Pair();
IUniswapV2Pair(pair).initialize(token0, token1);

A: Uniswap version 1 uses library contracts with hardcoded pair contract addresses.

*

*First deploy the factory contract

*Then call Factory.pairCodeHash - the hardcoded hex string of the init code

*Replace the pair code hash in the source code, compile the rest of the contracts

More tips in this Python module.


text:
Q: Identical items removal from lists beginner python user,
I have to write a function that takes as parameters two lists L1 and L2 and returns a list L3 of elements that are common to L1 and L2. For example: L1=[5,4,6,3,4], L2=[9,4,3,11], then the function returns [4,3] (an element is listed once).
Now, I am able to append the elements (find my code below) which is the easy part, but I can't seem to not include the already appended elements.
def common(L1,L2):

   L3=[]
   for i in range (len(L1)):
       for j in range (len(L2)):
          if L1[i]==L2[j]:
             L3.append(L1[i])

L1=[5,4,6,3,4]
L2=[9,4,3,11]
print(common(L1,L2))

If I try to include a nested loop for L3 and a condition in the if statement, nothing gets printed.

A: You can use the in operator to check and see if each element in L1 is in L2, but not in L3. (It also checks the entire list, so you don't have to write your own nested loop.)
L3 = []
for x in L1:
    if x in L2 and x not in L3:
        L3.append(x)


text:
Q: How to release wire from a Eaton Moeller M22-CK10 NO contact block? I am attempting to rewire a fan to a M22-CK10 contact block.
The device is shown below:

My first thought was to push in the metal contacts above the red wire on the left.
When that didn't work I tried pushing the contact holding the let red wire.  I experimented with the empty socket on the left but there was no sign of the clamp opening.  There is a green contact button on the rear that doesn't seem to do anything either when I press it.
There doesn't seem to be anything else, I don't want to destroy the contact block and it feels if I force it further I will.
Does anyone know if there is a simple way to release the wire from the contact block?

A: They show how to insert the wire , but not extract.
call aftersales support emergency line.

Since the strands are folded after insertion, it improves restraint, but makes it harder to remove without leaving in broken strands. Rotating the wire gently in the strand wind direction may allow it to be removed without breaking the wire or junction.