text:
Q: Can we create react native app without "create-react-native-app" cli? Do we always need this "create-react-native-app" utility or we can set up manually? I wanted to know if there is any other way to setup for working with react-native.

A: Yes, you can.
$ npm install -g react-native-cli
$ react-native init AwesomeProject
$ cd AwesomeProject
$ react-native run-ios/android

Explanation:
$ npm install -g react-native-cli installs a global npm package from Facebook to create a native project.
$ react-native init AwesomeProject will create a blank app with the data structure.
$react-native run-ios/android will compile your application and install on your device.


text:
Q: Hide/Show table rows based on checkbox and data element I want to hide the rows in my table, as i checked on check box and that data element is not true in the table.

*

*Another experiment

: Can i also do the order by using the data element and sort by drop down list, look on tr tags(price, name, rating) ?

<input type="checkbox" value="EMI"/>EMI
<input type="checkbox" value="COD"/>COD
<input type="checkbox" value="Return-Policy"/>Return Policy
<input type="checkbox" value="Discount"/>Discount

<select id="sortby">
<option value="price:asc">Price: Low to High</option>
<option value="price:desc">Price: High to Low</option>
<option value="rating:desc">Store Rating</option>
<option value="rating:desc">A-Z</option>
<option value="rating:desc">Z-A</option>
</select>

            COD: YES
            EMI: No
            Return Policy: 30 days
            Price: 45000
            Discount : 300

            COD: YES
            EMI: No
            Return Policy: 30 days
            Price: 42000
            Discount : 300

            COD: NO
            EMI: YES
            Return Policy: 30 days
            Price: 48000
            Discount : Not Available

            COD: YES
            EMI: YES
            Return Policy: 30 days
            Price: 45000.50
            Discount : Not Avaialable

Jquery
$(".filter-list").change(function(){
    $("#productsprice").children('tbody').children('tr').each(function(){
        var match = false;
        $(this).attr('data-cod').each(function() {
            if($(this).text() == $(".filter-list").val()) match = true;
        });

 // if data tag in
 found as not 1(true). toggle the hidden class to that rows and so on for each rows
    });
});

Fiddle : http://jsfiddle.net/9TTPS/9/

A: No need to reinvent the wheel.  If you want true table filter/sort functionality you should use a grid library like SlickGrid or jqGrid

redpajama_set_name: RedPajamaStackExchange


text:
Q: Noise Removal by Averaging Multiple Images in c# I tried code for two images but it fails after that limit..and not getting proper solution as well for collection of images you can visit
Click Here For collection of images
In these Images numbers on that images in green color are noise
please help me to find these solution
I have tried Following Code
    public Bitmap GetAveragedBitmap()
    {

        int numberOfImages = _imageCollection.Count;
        Bitmap bmpresult = null;

        if (numberOfImages > 1)
        {
            Stopwatch clock = new Stopwatch();
            clock.Start();
            BitmapData[] bmpData = new BitmapData[numberOfImages];
            Bitmap[] bit = new Bitmap[numberOfImages];
            int width = 0;
            int height = 0;

            for (int index = 0; index < numberOfImages; index++)
            {
                bmpData[index] = _imageCollection[index].LockBits(new Rectangle(0, 0, _imageCollection[index].Width, _imageCollection[index].Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                if (index > 0)
                {
                    if (bmpData[index].Width > width)
                    {
                        width = bmpData[index].Width;
                    }
                    if (bmpData[index].Height > height)
                    {
                        height = bmpData[index].Height;
                    }
                }
                else
                {
                    width = bmpData[0].Width;
                    height = bmpData[0].Height;
                }

                _imageCollection[index].UnlockBits(bmpData[index]);

            }//end of for loop
            for (int index = 0; index < numberOfImages; index++)
            {
                bit[index] = new Bitmap(_imageCollection[index], width, height);

            }

            bmpresult = new Bitmap(width, height);
            BitmapData[] data = new BitmapData[numberOfImages];
            for (int index = 0; index < numberOfImages; index++)
            {
                data[index] = bit[index].LockBits(new Rectangle(0, 0, bit[index].Width, bit[index].Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            }
            data[1].Reserved = 1;
            BitmapData dataResult = bmpresult.LockBits(new Rectangle(0, 0, bmpresult.Width, bmpresult.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            unsafe
            {
                int[] remain = new int[numberOfImages];
                byte*[] ptr = new byte*[numberOfImages];
                long totalIntensity = 0;

                for (int index = 0; index < numberOfImages; index++)
                {
                    ptr[index] = (byte*)data[index].Scan0;
                    remain[index] = data[index].Stride - data[index].Width * 3;
                }
                byte* ptrResult = (byte*)dataResult.Scan0;
                //for resultant image
                int remainResult = dataResult.Stride - dataResult.Width * 3;

                for (int i = 0; i < height; i++)
                    for (int j = 0; j < width * 3; j++)
                    {
                        for (int index = 0; index < numberOfImages; index++)
                        {
                            totalIntensity += (int)(ptr[index][0]);
                            ptr[index]++;
                        }
                    }
                    totalIntensity= totalIntensity/ numberOfImages;
                int average = (int)totalIntensity / (numberOfImages * height * width);
                //reset the pointer
                for (int index = 0; index < numberOfImages; index++)
                {
                    ptr[index] = (byte*)data[index].Scan0;
                }

                for (int i = 0; i < height; i++)
                {
                    for (int j = 0; j < width * 3; j++)
                    {

                        int result = 1;
                        for (int k = 0; k < numberOfImages; k++)
                        {

                            result = (ptr[k][0] * 1 * result);

                        }

                        ptrResult[0] = (byte)(result / average);

                        for (int index = 0; index < numberOfImages; index++)
                        {
                            ptr[index]++;
                        }
                        ptrResult++;

                    }
                    for (int index = 0; index < numberOfImages; index++)
                    {
                        ptr[index] += remain[index];
                    }

                    ptrResult += remainResult;

                }

                //  }//end of for loop

            }//end of unsafe

            for (int index = 0; index < numberOfImages; index++)
            {
                bit[index].UnlockBits(data[index]);
            }
            bmpresult.UnlockBits(dataResult);
            clock.Stop();
            Debug.WriteLine("Time for average " + clock.ElapsedMilliseconds.ToString());

        }
        return bmpresult;

    }

A: I have done this,
I went for ideas to AForge framework and luckily there is filter AForge.NET Framework Morph Class that creates average from two images. I think the original intent was to morph two different images as an effect, but if you uses two shots of same scene you get noise reduction.
I would assume you would like 2-n averaging so I suggest you take the source of the Merge filter as a starting point and create your customized version for multiple images.
Here is source : GitHub.com | AForge.NET / Merge.cs
PS. You might need to downloaded whole AForge project source to find where to put your implementation better.


text:
Q: BitBucket cannot push, "fatal: The remote end hung up unexpectedly" When trying to push to my new BitBucket repository, I keep getting this error:
Counting objects: 28, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (28/28), done.
Writing objects: 100% (28/28), 10.82 MiB | 7.29 MiB/s, done.
Total 28 (delta 1), reused 0 (delta 0)
error: RPC failed; curl 56 SSL read: error:140943FC:SSL
routines:ssl3_read_bytes:sslv3 alert bad record mac, errno 0
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly
Everything up-to-date

I get the same error in SourceTree as well.  I tried messing with the config file to increase buffer size as shown below:
git config --global http.postBuffer 524288000

I would like to just push from the command prompt.  I should also note that some folders were able to push to repository but others were not.
Wondering what to do.  I noticed there is another post about this issue here, but I wanted to state my case where I have tried all of these and to no avail.

A:
I don't want to use SSH as I am on Windows 10 without a server to use SSH from

You still could push through ssh though: git for windows has openssh included in its distro. Maybe your server does not have the right to use ssh for outbound transaction? I know I cannot use ssh on any server in my company.
Check if the issue persists, as there was a recent incident report for Atlassian Bitbucket affecting Git via HTTPS.
That "bad record mac" ssl error is about "Message Authentication Code", and suggests an upgrade of ssl library on the server side (as part of the incident resolution).
Make sure to use the latest git for Widows 2.8.3.

A: I was doing a git-tf migration when I got this issue, and being primarily a TFS user I didn't really know where to start with this one.
The quick fix that allowed me to perform the sync/check-in was to temporarily turn off "This is a private repository" from within the BitBucket project settings.


text:
Q: Getting the result into a variable I have the following example code. I'm able to see the correct result in the console from the print function.
  // Define a model for linear regression.
  const model = tf.sequential();
  model.add(tf.layers.dense({units: 1, inputShape: [1]}));
  model.add(tf.layers.dense({units: 4, inputShape: [1]}));
  model.add(tf.layers.dense({units: 10, inputShape: [1]}));

  model.add(tf.layers.dense({units: 1, inputShape: [1]}));

  // Prepare the model for training: Specify the loss and the optimizer.
  model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

  // Generate some synthetic data for training.
  const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
  const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

  // Train the model using the data.
  model.fit(xs, ys).then(() => {
    // Use the model to do inference on a data point the model hasn't seen before:
    // Open the browser devtools to see the output
    answer = model.predict(tf.tensor2d([3], [1, 1]));
    answer.print()

  });

What I'd like to be able to do is to put answer into a number var so that I can use it elsewhere. The answer I get is:
Tensor [[4.9999123],]

But I'd like to get the 4.9999 into a variable so that I can round it up to 5 and print it on screen (in html).

A: I found the answer to be:
    answer.data().then((d)=>{
      console.log(d[0])
    })

answer has a data method which returns a promise. You can get the data from the promise.
I searched stackoverflow which lead me to this question:
Get data from 2D tensor with tensorflow js
Rocksetta kindly posted a link to their code on the following site:
https://hpssjellis.github.io/beginner-tensorflowjs-examples-in-javascript/beginner-examples/tfjs02-basics.html

A: The easiest way is to use answer.dataSync(), but it will block the main thread.   If you are comfortable with async / await, answer.data() is the solution.

A: Sometimes

The easiest way is to use answer.dataSync(), but it will block the
  main thread. If you are comfortable with async / await, answer.data()
  is the solution.

works fine but other times
answer.dataSync()

returns an array. When faced with the array then you need to try
answer.dataSync()[0]

or some other array number. Same issue with
await answer.data()[0]

A: Here's my favorite way:
var answerdata = await answer.data()
var answerArray = Array.from(answerdata);

answerArray will be flattened, but it's fast and simple. You're usually in an async function anyways if you're loading a Keras model or doing a variety of other async things.

A: To get the value of a Tensor into normal JavaScript variable, one can use two built-in functions of TensorflowJs: one is synchronous dataSync() and the other is asynchronous data().
dataSync() will block the UI thread. So whenever possible the asynchronous data() should be preferred.

const x = tf.tensor1d([45, 48]);
x.print();
/* Async way */
(async () => {
  const val = await x.data()
   // get the first element
  console.log(val[0])
})()
/* Sync way */
const val = x.dataSync()[0]
console.log(val)
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"> </script>
  </head>

  <body>
  </body>
</html>


text:
Q: How to use ImagePicker to select image and display in Ionic Native I'm developing an Ionic app, and one task is to select a profile via camera or gallery, and I use Ionic Native ImagePicker to select picture and crop, it can select and crop, but not display in front html page, my code is as below:
openImagePickerCrop(){
  this.imagePicker.hasReadPermission().then(
    (result) => {
      if(result == false){
        // no callbacks required as this opens a popup which returns async
        this.imagePicker.requestReadPermission();
      }
      else if(result == true){
        this.imagePicker.getPictures({
          maximumImagesCount: 3
        }).then(
          (results) => {
            for (var i = 0; i < results.length; i++) {

              this.crop.crop(results[i], {quality: 100}).then(
                newImage => {
                  this.imgResponse.push('data:image/jpeg;base64,' + newImage);
                  console.log("Image selected - " + newImage);
                },
                error => console.error("Error cropping image", error)
              );

            }
          }, (err) => console.log(err)
        );
      }
    }, (err) => {
      console.log(err);
    });
  }

And this is my html code:
<ion-item class="input-item">
          <ion-label position="floating">Photo</ion-label>

          <ion-card-content>
            <ion-button color="medium" size="large" (click)="openImagePickerCrop()">
              <ion-icon slot="icon-only" name="camera"></ion-icon>
            </ion-button>
          </ion-card-content>
      </ion-item>

Where am I doing wrong, pls help.
Update:
To check if it's due to the crop function, I have updated functions as below:
openImagePicker(){
this.imagePicker.hasReadPermission().then(
  (result) => {
    if(result == false){
      // no callbacks required as this opens a popup which returns async
      this.imagePicker.requestReadPermission();
    }
    else if(result == true){
      this.imagePicker.getPictures({
        maximumImagesCount: 1
      }).then(
        (results) => {

          for (var i = 0; i < results.length; i++) {
            this.imgResponse.push('data:image/jpeg;base64,' + results[i]);
            console.log("Image selected - " + results[i]);
          }
        }, (err) => console.log(err)
      );
    }
  }, (err) => {
    console.log(err);
  });
}

But still not working, and the console doesn't capture anything.


text:
Q: Program failed for outputting brute force results on decryption method def asciiShift(character, aShift):
  asciiNum = ord(character) + (int(aShift))%26
  return asciiNum

def stringShift(string, shift):
  k=0
  newstring = ''
  string_len = len(string)
  while k<string_len:
    newstring = newstring + string[int(((int(shift)%int(string_len))+k))%int(string_len)]
    k=k+1
    if k==string_len:
      break
  return newstring

def encrypt(message, aShift, sShift):
  i=0
  length = len(message)
  asciiChars = []
  while i<length:
    asciiChars.append(asciiShift(message[i].upper(), aShift))
    i=i+1
    if i==length:
      break
  string = ''
  j=0
  while j<length:
    string = string + str(chr(asciiChars[j]))
    j=j+1
  shifted_string = stringShift(string, sShift)
  print(shifted_string)

def decrypt(message):
  x=0
  mlength = len(message)
  mstring = ''
  while x<mlength:
    d=0
    while d<mlength:
      mstring = mstring + message[int(x+d)%(mlength)]
      d=d+1
    e=0
    mstring = mstring.upper()
    mlist = []
    while e<mlength:
      mlist.append(ord(mstring[e]))
      e=e+1
    f=0
    while f<26:
      g=0
      newstring = ''
      while g<mlength:
        newstring = newstring + chr(mlist[g] + f%26)
        g=g+1
      print(newstring)
      f=f+1
    x=x+1
    if x==mlength:
      break

  # todo list
  # shift string around (use.upper())
  # convert shifted string to ascii number list
  # add numbers from 0-25 to the ascii number list
  # print out the results

typeConfirm = input("Encrypt or Decrypt? (E/D): ")
if typeConfirm[0].upper() == 'D':
  decryptBool = True
elif typeConfirm[0].upper()== 'E':
  decryptBool = False
else:
  print("You probably said an incorrect choice or read the question incorrectly. Exiting program for now...")
  exit()

if decryptBool == True:
  decrypt_msg = input("What is the encoded message?: ")
  decrypt(decrypt_msg)
else:
  message = input("What is your message?: ")
  aShift = input("ASCII shift?: ")
  sShift = input("String shift?: ")

  a=0
  b=len(message)
  while a<b:
    if message[a] == '~':
      print("Sorry, the encryptor doesn't support any special characters (other than the ones on a normal keyboard, or these characters that are on a keyboard: '~', '{', and '}' only these 3 characters in the quotation marks don't work. Sorry for the inconvenience!")
      exit()
    elif message[a] == '{':
      print("Sorry, the encryptor doesn't support any special characters (other than the ones on a normal keyboard, or these characters that are on a keyboard: '~', '{', and '}' only these 3 characters in the quotation marks don't work. Sorry for the inconvenience!")
      exit()
    elif message[a] == '}':
      print("Sorry, the encryptor doesn't support any special characters that aren't on a normal office keyboard. However, these characters that are on a keyboard don't work: '~', '{', and '}' only these 3 characters in the quotation marks don't work. Sorry for the inconvenience!")
      exit()
    a=a+1
    if a==b:
      break
  encrypt(message, aShift, sShift)

I made this code so far, however for some reason, the decrypter doesn't work with the outputs of the encrypter. (As in, the brute force doesn't output the input at all)
For context, the purpose of this program would be to encrypt a string by converting all the characters to ascii code, and adding a number to it. Then, the new number would be turned back into a character, and the string would be shifted by a certain amount. For ex, "ABC" shift 1 -> [66, 67, 68] -> "BCD" shift 2 -> "DBC"
If someone could help point out why it isn't working (or if there's a better solution, ex. "you wrote this area wrong", or "the encryptor result is faulty", etc.), it would be much appreciated!

A: Since you indicated you just want to start out with performing a brute force algorithm to decrypt an encrypted phrase or word, the intuitive solution seemed to be to create complimentary functions for the ASCII shift and string shift functions that perform a shift in the opposite direction for the decryption function.  Then, build the decryption function such that it is almost a duplicate of the encryption function except it loops through the possible shifting utilizing the complimentary functions.
Following is a revised version of your code you can experiment with.
def asciiShift(character, aShift):
  asciiNum = ord(character) + (int(aShift))%26
  return asciiNum

def asciiShiftx(character, aShift):
  asciiNum = ord(character) - (int(aShift))%26
  return asciiNum

def stringShift(string, shift):
  k=0
  newstring = ''
  string_len = len(string)
  while k<string_len:
    newstring = newstring + string[int(((int(shift)%int(string_len))+k))%int(string_len)]
    k=k+1
    if k==string_len:
      break
  return newstring

def stringShiftx(string, shift):
  k=0
  newstring = ''
  string_len = len(string)
  while k<string_len:
    newstring = newstring + string[int(((int(shift * -1)%int(string_len))+k))%int(string_len)]
    k=k+1
    if k==string_len:
      break
  return newstring

def encrypt(message, aShift, sShift):
  i=0
  length = len(message)
  asciiChars = []
  while i<length:
    asciiChars.append(asciiShift(message[i].upper(), aShift))
    i=i+1
    if i==length:
      break
  string = ''
  j=0
  while j<length:
    string = string + str(chr(asciiChars[j]))
    j=j+1
  shifted_string = stringShift(string, sShift)
  print(shifted_string)

def decrypt(message):
  for z1 in range(26):
    for z2 in range(26):
      i=0
      lengthx = len(message)
      asciiChars = []
      while i<lengthx:
        asciiChars.append(asciiShiftx(message[i].upper(), z1))
        i=i+1
        if i==lengthx:
          break
      string = ''
      j=0
      while j<lengthx:
        string = string + str(chr(asciiChars[j]))
        j=j+1
      shifted_string = stringShiftx(string, z2)
      print('ASCII shift: ', z1, 'String shift: ', z2, shifted_string)

typeConfirm = input("Encrypt or Decrypt? (E/D): ")
if typeConfirm[0].upper() == 'D':
  decryptBool = True
elif typeConfirm[0].upper()== 'E':
  decryptBool = False
else:
  print("You probably said an incorrect choice or read the question incorrectly. Exiting program for now...")
  exit()

if decryptBool == True:
  decrypt_msg = input("What is the encoded message?: ")
  decrypt(decrypt_msg)
else:
  message = input("What is your message?: ")
  aShift = input("ASCII shift?: ")
  sShift = input("String shift?: ")

  a=0
  b=len(message)
  while a<b:
    if message[a] == '~':
      print("Sorry, the encryptor doesn't support any special characters (other than the ones on a normal keyboard, or these characters that are on a keyboard: '~', '{', and '}' only these 3 characters in the quotation marks don't work. Sorry for the inconvenience!")
      exit()
    elif message[a] == '{':
      print("Sorry, the encryptor doesn't support any special characters (other than the ones on a normal keyboard, or these characters that are on a keyboard: '~', '{', and '}' only these 3 characters in the quotation marks don't work. Sorry for the inconvenience!")
      exit()
    elif message[a] == '}':
      print("Sorry, the encryptor doesn't support any special characters that aren't on a normal office keyboard. However, these characters that are on a keyboard don't work: '~', '{', and '}' only these 3 characters in the quotation marks don't work. Sorry for the inconvenience!")
      exit()
    a=a+1
    if a==b:
      break
  encrypt(message, aShift, sShift)

I tested this out by encrypting a short phrase ("HELLO THERE") with an ASCII shift of "4" and a string shift of "22".
@Una:~/Python_Programs/Encrypt$ python3 Encrypt.py
Encrypt or Decrypt? (E/D): E
What is your message?: HELLO THERE
ASCII shift?: 4
String shift?: 22
LIPPS$XLIVI

Then, I called the program again and asked it to decrypt the encrypted phrase ("LIPPS$XLIVI").  I will skip to the portion of the terminal output where one can see the original text.
@Una:~/Python_Programs/Encrypt$ python3 Encrypt.py
Encrypt or Decrypt? (E/D): D
What is the encoded message?: LIPPS$XLIVI
. . .
ASCII shift:  4 String shift:  18 O THEREHELL
ASCII shift:  4 String shift:  19 LO THEREHEL
ASCII shift:  4 String shift:  20 LLO THEREHE
ASCII shift:  4 String shift:  21 ELLO THEREH
ASCII shift:  4 String shift:  22 HELLO THERE
ASCII shift:  4 String shift:  23 EHELLO THER
ASCII shift:  4 String shift:  24 REHELLO THE
ASCII shift:  4 String shift:  25 EREHELLO TH

As would make sense the complimentary shift values match the original shift values where one sees the correct decrypted phrase.
Anyway, experiment with that.  Hope that helps.
Regards.


text:
Q: UITableViewCell Dynamic height with expandable UIView As I want to create tableview cell that has dynamic height I don't know what height it will take after rendering the content.
And there is a UIView which is hidden. It will render when someone taps on the cell, the UIView is visible.
Now the problem arises when content is larger its starts hiding, and to make that view visible I need the height in Float.
// I am using this as a logic for cell expander.
class var expanderHeight : CGFloat { get { return  160 } }
class var defaultHeight :CGFloat { get { return 140 } }

func checkHeight(){
    imageexpander.hidden = (frame.size.height < EaterysTableViewCell.expanderHeight)

}

func watchFrameChanges(){
    if !isObserving {
        addObserver(self, forKeyPath: "frame", options: [NSKeyValueObservingOptions.New, NSKeyValueObservingOptions.Initial], context: nil)
    }
}

func ingnoreFrameChanges(){
    if isObserving {
        removeObserver(self, forKeyPath: "frame")
        isObserving = false
    }
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if keyPath == "frame" {
        checkHeight()
    }
}

I have three labels like this:
   `|label one|
    |label two|
    |label three|`

How do I add constraints so that content of label one and label two do not get truncated when they have multiple lines (dynamically)?


text:
Q: An alternative for "ignorance" Can you help me make this sentence more clear? Especially the part about users' compliance.

Two issues of the computer system are lack of customization and ignorance of users' compliance.

I want to say that the design of the computer system does not take into account the way that users respond to the system. But I just want to say it in one word: ignorance, negligence,...
Any other suggestions?


text:
Q: Which function is a faster alternative to FOR? Google Apps Script - Google Sheets i have a code :
function check(){
  var sh = SpreadsheetApp.getActive();
  var sheet = sh.getSheetByName("1")
  var getNames = sheet.getRange("A:A").getValues().filter(String).toString().split(",");
    for (var j = 0; j < getNames.length; j++) {
      var sheetnow = sh.getSheetByName(getNames[j]);
      var last = sh.getSheetByName(getNames[j]).getLastRow();
      for (var i = 1 ; i <= last ; i++ ) {
        var rangeactive = sheetnow.getRange(i ,7).getValue();
        var setval = sheetnow.getRange(i ,8);
          if (rangeactive == 1 && setval.getValue() == "") {
              setval.setValue("OK");
          }
      }
    }
}

It still works fine, but For will be very slow because all the sheets have more than 200000 rows and will run more than 6 minutes. Is there any other more efficient way? Thanks
https://docs.google.com/spreadsheets/d/13p4xrIfACk_l_oRgBnDr8VaOtEL9o4SxeIql5eqryOc/edit#gid=1480346296

A: Try this:
function check(){
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("1")
  const names = sh.getRange(1,1,sh.getLastRow()).getValues().flat();
  names.forEach(n => {
    let s = ss.getSheetByName(n);
    let vs = s.getRange(1,7,s.getLastRow(),2).getValues();
    let sv = s.getRange(1,8,sh.getlastRow()).getValues();
    vs.forEach((r,i) => {
      if(r[0] == 1 && r[1] == '') {
        sv[i][0] = "OK";
      }
    });
    s.getRange(1,8,sv.length,sv[0].length).setValues(sv);
  });
}


text:
Q: How to create a Winform in Unity and display it? I am having a released unity game with its Assembly-CSharp.dll already decompeiled by DnSpy.I want to add something that can display information. Due to difficulty to edit UI without the visual editor of Unity, I decided to make a winform by Visual Studio then copy the UI layout code to DnSpy. I know how to add reference, and using those namespaces, then create an instance of Form. But I can't get it displayed by calling Form.show() of the newly created instance.
Can any one help me to solve this?
added on 2021/1/26:
this question was asked long time ago and I didn't know how to ask good answer, as a result I never give any furthur detail such as stack trace or error message. But such info cannot be retrieved any more. Here by informing readers.

A: I have solved this question.The problem is that the System.Windows.Forms.dll and System.Drawing.dll that I copied to GameDirectory\GameName_Data\Managed is wrong.
I should not copy it from system folder. Instead, it should be the one located at UnityDirectory\Editor\Data\Mono\lib\mono\2.0. Using other dll will cause a lot of errors.


text:
Q: How to export multiple functions using module.exports in node.js I'm creating a utilities class to handle some of our common functions to help reduce code copy/past in our modules: I created an exports module. All that's happening here is the export of an object which contains three functions.
module.exports = {
    //retrieve a secret object from the AWS Secrets Manager
    //Parameter should be string value of the Secret ID

     getSecretIdAsync : async (param) => {
        return await new Promise((resolve, reject) => {
            scrtmgr.getSecretValue({SecretId: param}, (err, data) => {
                if(err){
                    reject(console.log('Error getting SecretId: ' + err, err.stack));
                } else{
                    if('SecretString' in data)
                    return resolve(JSON.parse(data.SecretString));
                }
             });
        });
    },

    //retrieves the AWS Paramter value from the AWS Paramter store
    //param should be string value of parameter hierarchical id

    getParameterValueFromStoreAsync : async (param) => {
        return await new Promise((resolve, reject) => {
            servmgr.getParameter({ Name: param}, (err, data) => {
                if(err){
                    reject(console.log('Error getting parameter: ' + err, err.stack));
                }
                return resolve(data.Parameters.Value);
            });
        });
    },

    //retrieves the AWS Paramter "object" from the AWS Paramter store
    //param should be string value of parameter hierarchical id

    getParameterFromStoreAsync : async (param) => {
        return await new Promise((resolve, reject) => {
            servmgr.getParameter({ Name: param}, (err, data) => {
                if(err){
                    reject(console.log('Error getting parameter: ' + err, err.stack));
                }
                return resolve(data.Parameters);
            });
        });
    }
}

Whenever I attempt to reference this module (say in my unit test I reference to module as:
let chai = require('chai');
let ut = require('../utilities.js');
let expect = chai.expect;
let aws = require('aws-sdk-mock');

describe('get parameter value', ()=>{

    it('resolves', (done)=>{
        var result = aws.mock('SSM', 'putParameter' , {"Name": "someName", "Value": "someValue"} );
        console.log('###### ' + JSON.stringify(ut));

        //console.log(obj);
    });
});

directory structure is
utilities.js is located in the root, where the unit test is in a folder called test.
Whenever I try to import the utilities module the object it always empty.
console.log('###### ' + JSON.stringify(ut)); generates ###### {}
I've exported individual functions in the past and I thought a group of functions would just require exporting a constructor.
Should multiple functions be exported in a different manner?

A: MDN web docs offers an explanation for the behavior that you're seeing with JSON.strigify():

If undefined, a Function, or a Symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
edit: To clarify, I think you're exporting your utility functions correctly, but JSON.stringify() explicitly promises to not print functions.

A: JSON.stringify doesn't serialize functions, if you need to do so you have to use a custom stringify function like this https://github.com/braceslab/json-stringify-extended
so, running
console.log(ut)

will print
{ getSecretIdAsync: [AsyncFunction: getSecretIdAsync],
  getParameterValueFromStoreAsync: [AsyncFunction: getParameterValueFromStoreAsync],
  getParameterFromStoreAsync: [AsyncFunction: getParameterFromStoreAsync] }

also, you can remove async and await from your functions, are useless using  return new Promise


text:
Q: Is there no extra intermediate subfactor for the basic construction? Let $(N \subset M)$ be a unital inclusion of ${\rm II}_1$ factors, the basic construction is $N \subset M \subset M_1 = \langle M , e^M_N \rangle$.
Question: For any intermediate subfactor $N \subset P \subset M_1$, is it true that   $N \subset P \subseteq M$ or $M \subset P \subset M_1$ (i.e. no extra intermediate)?

A: This answer came by a discussion with Keshab Chandra Bakshi.
Consider the subfactor $(R \subset R \rtimes  \mathbb{Z}/2)$, then $R \subset R \rtimes  \mathbb{Z}/2 \subset M_2(R) = R \otimes M_2(\mathbb{C})$ is the basic construcition, but $(R \subset M_2(R))$ admits continuously many intermediate subfactors which are conjugate to $R \rtimes  \mathbb{Z}/2$ by unitaries in $\mathbb{C} \otimes M_2(\mathbb{C})$. So the answer is no.


text:
Q: Windows 8.1 search not finding Control Panel settings Since upgrading to Windows 8.1 from 8, I've noticed that doing a search (Windows + S) is not turning up any Control Panel settings. For example, if I try to find Windows Update by typing in "update", I'm not getting any results. It's almost if the Settings option of the search is not actually doing anything.

Doing the same search from within the Control Panel itself gives me the results I'm looking for:

Any insight as to why this is happening? I'm fairly certain this worked fine in Windows 8, but I have no way of verifying that. Is this just a setting somewhere that I've missed?

A: We had been experiencing exactly the issue you described.
Recently we had migrated to using SSDs and as part of that, we disabled the "Allow files on this drive to have contents indexed in addition to file properties" setting on the C drive.

After re-enabling this setting, we found that the Control Panel settings returned in the search results (in both Everywhere and in Settings).

A: I had this exact same problem. However the solution wasn't to enable indexing on my SSD.
Counterintuitively, I solved it by simply disabling the Windows Search Service.

As soon as I disabled Windows Search, search worked perfectly again.
My PC is new and I had recently enabled Windows Search when Microsoft OneNote prompted me to.

Given the choice, I went with slower OneNote searches and a working Search charm!

A: Hey to do a search in the settings menu the default keyboard shortcut is "Windows + W" not "Windows + S". So try searching for update in the settings menu. Also if your'e not getting anything from typing update then you can try to search for windows update. It should bring up the settings for the update options.

A: I also removed indexing from the drive, and lost all control panel and settings in searches.
You can get them back by enabling Allow files in this folder to have contents indexed in addition to file properties for the folder (and all folders and files under):
C:\Users\{user}\AppData\Local\Packages\windows.immersivecontrolpanel_cw5n1h2txyewy\LocalState

That way you can keep indexing off for most of your drive.
(I've tested this on Window 10, not 8.1)
Source: Windows 10 forum

A: In my case, I had to:

*

*Enable "Show Administrative Tools" in "Tiles" settings (see this answer)

*Add missing links such as "Windows Update" and "Programs and Features" manually in %AppData%\Microsoft\Windows\Start Menu\Programs\Administrative Tools` (not sure why they were not there in the first place).

I can now type Win  + S and type "Update", and "Windows Update" shows up.
If you have trouble creating these shortcuts, here are a few links that might help: How to create a Programs and Features shortcut and How to create a Windows Update shortcut


text:
Q: Inconsistent java and sql object types Need a little assistance with a jdbc issue.
I've really struggled finding a solution to this.  I don't have much experience with JDBC, and it doesn't look too newbie-friendly.  If anyone can help it would be appreciated.  By help I mean pointing me to other resources or even better if you can offer a direct solution.
The exception is created in oracle.sql.STRUCT.java:51
throw new SQLException("Cannot construct STRUCT instance, invalid connection");

and is thrown in the final line of the following code:
SimpleJdbcCall simpleJdbcCall = getSimpleJDBCCall();
con = simpleJdbcCall.getJdbcTemplate().getDataSource().getConnection().getMetaData().getConnection();

WLConnection wc = (WLConnection) con;
Connection vendorConn = wc.getVendorConnection();

con.setAutoCommit(false);

Object[] custIdentifier = { null, new Long(125435345L)};

StructDescriptor structDesc =         StructDescriptor.createDescriptor("O_CUSTOMER_TYPE_CID_PID", vendorConn);

STRUCT struct = new STRUCT(structDesc, vendorConn, custIdentifier);
STRUCT[] structArray = new STRUCT[] { struct };

ArrayDescriptor des = ArrayDescriptor.createDescriptor("T_CUSTOMER_TYPE_CID_PID", vendorConn);
ARRAY array = new ARRAY(des, vendorConn, structArray);

ArrayDescriptor desEvnt = ArrayDescriptor.createDescriptor("T_EVENT_TYPE_ID", vendorConn);
ARRAY arrayEvnt = new ARRAY(desEvnt, vendorConn, events);

StructDescriptor fltDetailsStructDesc =
                StructDescriptor.createDescriptor("O_FLIGHT_DETAILS", vendorConn);

DATE flightDateUTC = new DATE(flightDt);
NUMBER flightNum = new NUMBER(fltNo);
Object[] fltDetailFields = new Object[] { flightNum, flightDateUTC };

// Exception thrown in constructor below
STRUCT fltDetailsStruct = new STRUCT(fltDetailsStructDesc, vendorConn,     fltDetailFields);

I'm using ojdbc6 version 11.2.0.4
The SQl object expected is:
TYPE O_FLIGHT_DETAILS AS OBJECT
(
FLIGHT_NO NUMBER(5), -- Marketing Flight Number
UTC_DEP_DATE Date, -- Scheduled Flight departure Date in UTC
BKG_DT DATE -- Flight Booking date in UTC
);

Any help, much appreciated.

A: I think the problem was as follows:
the StructDescriptor for the 'O_FLIGHT_DETAILS' object was expecting an array containing 3 values, as per the SQL object.  Since the array supplied contained only 2 values, a mismatch occurred and exception was thrown.  The error message 'inconsistent java and sql object types' was accurate.
I changed the fltDetailFields instantiation line to:
Object[] fltDetailFields = new Object[] { flightNum, flightDateUTC, null };

and it worked as expected.


text:
Q: 404 error when I try to update my form with id 1, but its not happen to another id

i have db with id 1,2,4 (img-1)
but if I try to update id_bank = 1, i got 404 error (img-2)
but that update work with another id (img-3)
this application work fine yesterday, but I got this error this morning, I dont know why, I really need help :(
Update:
I use codeigniter framework,
this is my controller code

  function form($id_bank = false)
    {
    $this->id_bank  = $id_bank;
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('
', '
');
        $data['page_title']     = lang('bank_form');
        $data['breadcrumbs'] = array();
        $data['breadcrumbs'][] = array(
            'text' => lang('home'),
            'href' => base_url()
            );
        $data['breadcrumbs'][] = array(
            'text' => lang('bank_form'),
            'href' => base_url('bank')
            );
        //default values are empty if the provinsi is new
        $data['id_bank']       = '';
        $data['nama_bank']      = '';
        $this->form_validation->set_rules('nama_bank', 'lang:nama_bank', 'trim|required|max_length[64]');
        //$this->form_validation->set_rules('id_categories', 'lang:id_categories', 'trim|required|max_length[64]');
        // validate the form
        if ($this->form_validation->run() == FALSE)
        {
            $this->view('bank/form', $data);
        }
        else
        {
            if (!$this->auth->hasPermission('modify', 'bank'))
            {
                $this->session->set_flashdata('error', lang('error_acces'));
                redirect('bank');
            }

            $this->load->helper('text');

            $save['id_bank']        = $id_bank;
            $save['nama_bank']          = $this->input->post('nama_bank');

            $this->Model_bank->save_provinsi($save);

            $this->session->set_flashdata('message', lang('message_provinsi_saved'));
            //go back to the category list
            redirect('bank');
        }
}

this is on my view

                    <?php echo lang('no');?>
                    <?php echo sort_url('nama_bank', 'nama_bank', $order_by, $sort_order, $code);?>
                    <?php echo sort_url('gambar', 'image', $order_by, $sort_order, $code);?>
                    <?php echo lang('action');?>

                <?php echo (count($type) < 1)?'
'.lang('no_type').'
':''?>

                <?php
                $pages = ($page-1)*10;
                foreach ($type as $merks):
                    $pages+=1;

                ?>

                    <?php echo  $pages; ?>
                    <?php echo  $merks->nama_bank; ?>
                     <img  width="50px" height="50px" src='<?php echo $this->config->item('url_image').'photo/bank/'.$merks->image?>'>

                        <a href="<?php echo site_url('bank/form/'.$merks->id_bank); ?>" data-toggle="tooltip" title=" <?php echo lang('edit');?>" class="btn btn-sm btn-primary">
                        <?php if ($this->auth->hasPermission('delete', 'bank')) {  ?>
                        <a href="<?php echo site_url('bank/delete/'.$merks->id_bank); ?>" data-toggle="tooltip" onclick="return areyousure();" title="<?php echo lang('delete');?>" class="btn btn-sm btn-danger">
                        <?php } ?>

            <?php endforeach;?>

this on my routes:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

 $route['default_controller']   = "dashboard";


text:
Q: Unable to install Opera in Fedora 28 using rpm
*

*I can't install the program by double-click because it conflicts with previously installed opera.

*I can't install opera via the following command:
rpm -ivh opera-stable_56.0.3051.52_amd64.rpm
because
libXss.so.1()(64bit) is needed by opera-stable-56.0.3051.52-0.x86_64

ButtI don't Know how to get this object file (?) on my Fedora. dnf don't know about this package. Neither does apt-get nor yum.
OS: Fedora 28

A: A search on rpmfind reveals that the package you need on Fedora 28 is libXScrnSaver. Do yum install libXScrnSaver and then you should be able to install Opera.
You can also use yum to install one-off RPMs, so that it can try to automatically install dependencies, like this: yum install ./opera-stable_56.0.3051.52_amd64.rpm


text:
Q: How do I increase the amplitude of this elastic animation effect? I'm using Raphael.js to animate an SVG circle's radius on hover. I like the stock elastic effect that the library offers, but I'd like to increase the amplitude - i.e., make the circle grow and shrink with a lot more gusto when it's hovered - not with extra speed, but to grow larger and shrink smaller when the effect runs.
I copied the elastic function and renamed it super_elastic, and have been tinkering with it here:
http://jsfiddle.net/ryWH3/
I have no idea how the function works, so I've just been tinkering with its numerical values to see what happens. So far I haven't found anything that appears to do what I want. Can anyone recommend any modifications to the function (or a different function altogether) that might do what I'm looking for?
Thanks!

UPDATE:
Thanks for the replies! Sorry, I may not have explained this very well. I'm guessing that the statement "grow larger and shrink smaller" was especially misleading.
I'm aware that the r property affects the final radius of the circle after the animation runs; what I'm trying to do, though, is make the elastic animation "bounce" with greater amplitude. That is, while the animation will still start and end at the same r values that I've set for the circle, I'd like the elastic transition to be a lot more dramatic - expand and contract the circle much more aggressively during the transition before arriving at the final r values. To do this, I'm assuming that I need to modify the equation used in the elastic function to make the effect more dramatic.
Hopefully that makes sense - it's kind of hard to explain without showing an example, but if I had an example, I wouldn't have needed to post this question. ;-)

A: OK, based on your clarification, here's a new answer.  To expand the effect of the easing (amplification), you need to multiply the easing result with a multiplier like this.
return 6 * Math.pow(2, -10 * n) * Math.sin((n - .075) * (2 * Math.PI) / .3) + 1;

But, when you do that, you find that the large part of the amplification goes too fast.  The small part goes slow and the large part goes fast.  So, the pace when it's larger needs to be changed.  My guess (which seems to work) was to change Math.sin() to Math.cos() because that shifts the phase and it seems to work as you can see here: http://jsfiddle.net/jfriend00/fuaNp/39/.
return 6 * Math.pow(2, -10 * n) * Math.cos((n - .075) * (2 * Math.PI) / .3) + 1;

Other things to understand about this easing function.  This part:
(2 * Math.PI) / .3

determines how many bounce cycles there are.  The larger that multipler is, the more bounces it will have (but the faster the bounces will go).  The smaller that multipler is, the fewer bounces it will have (and the slower those bounces will go).
This part:
Math.pow(2, -10 * n)

determines how fast the bounce decays since this value gets smaller the larger n gets which negates the other multipliers as n gets large.  So:
Math.pow(2, -5 * n)

makes it decay slower (you see more of the larger swings at the beginning and less of the smaller swings at the end.

A: To make the circle go larger when you hover over it, you change the hovered radius which I've upped to r: 100 here.  To make the circle smaller, you change the initial size and the unhovered size from 25 to something smaller like this:
var paper = Raphael(0, 0, 300, 300),
    circle = paper.circle(150, 150, 10);   // <== change initial radius here to make it smaller

circle.attr({
  'stroke': '#f00',
  'stroke-width': 4,
  'fill': '#fff'
});
circle.hover(function() {
  this.animate({ r: 100 }, 1000, 'super_elastic');   // <== change enlarged size here
}, function() {
  this.animate({ r: 10 }, 1000, 'super_elastic');    // <== change small size here
});

// no changes made to the easing function
Raphael.easing_formulas.super_elastic = function(n) {
  if (n == !!n) {
    return n;
  }
  return Math.pow(2, -10 * n) * Math.sin((n - .075) * (2 * Math.PI) / .3) + 1;
};

You can see it here: http://jsfiddle.net/jfriend00/fuaNp/.
The super_elastic() function is the easing function which controls what pace the animation moves at different parts of the cycle.  Easing doesn't control the overall amplitude.  That's done with the parameters to the animate() method.
If you wanted to slow down the animation, you would increase the time of the animation (make the two 1000 arguments to animate() be larger numbers.  If you wanted to speed up the animation, you make those two numbers smaller.  These are milliseconds for the animation.  Smaller numbers means the animation runs in fewer milliseconds (which means faster).


text:
Q: "Diagnostic startup" + Bitlocker = Deadlock? I'm dealing with a frustrating problem for a friend. His Windows 10 PC was running slowly and he read online that he could solve it by switching to "Diagnostic startup" in msconfig. After that he rebooted and found out his password wasn't accepted anymore. We tried on-screen-keyboard and verified that his password was correct, but no success.
I read online that this is a common issue that could be fixed by booting into save mode or other options in the "Advanced startup options" menu.
However, this is where the trouble starts, it turns out his PC is encrypted with Bitlocker and of course he doesn't know the recovery key, and he doesn't have any memory of enabling Bitlocker. Also he doesn't use a MS account to login, so no luck of finding the recovery key there. So we are unable to boot using save mode.
In short the situation:

*

*Admin user password is known

*That password is not accepted since "Diagnostic startup" in msconfig was enabled

*C drive encrypted by Bitlocker

*Unable to boot in save mode because Bitlocker recovery key is unkown

I feel like it might be possible to set the PC to "Normal startup" in msconfig using the cmd in the "Advanced boot options" menu, however, that cmd is mounted at the 'X' drive since the 'C' drive is of course encrypted, so I'm unable to find all system programs there.
A system reinstall is not an option because of the files on the drive. Any help is greatly appreciated.

A: Turned out the guy did have some random MS account that contained the recovery key. Through that we were able to decrypt the drive and then reinstall windows while keeping the files.


text:
Q: Reasoning about the boolean vector in Coq, based on the value of its sum. (kind of universal instantiation for vectors) I've got stuck with theorem which is easy to formulate:
"If the maximal element of the vector is 0 then each element of the vector is 0".
The goal is to be able to use such an idiom as "fold_left orb false v".
So my first aim is to prove this particular lemma:
Lemma all_then_some (A:Type) :
 forall (n:nat) (p:Fin.t (S n))
  (v : Vector.t bool (S n))
  (H : (Vector.fold_left orb false v) = false),
 (Vector.nth v p) = false.
Proof.
...

Some thoughts:
1) To strengthen the hypothesis and prove something like this:
(forall (b:bool), (List.fold_left orb l b)  = b) <->
(forall (p:nat), (List.nth p l false) = false)
(** NB: variant for lists here! **)

2) Use principle "rectS" from the standard library /Vectors/Fin.v
3) Use small scale reflection library.
UPDATE: to find the partial solution please see my answer below.(ged)
UPDATE2: Solution is here: https://github.com/georgydunaev/TRASH/blob/master/UNIV_INST.v
(it is called "Theorem all_then_someV")

A: You can indeed use a more structured lemma from math-comp, a quick example [that can surely be improved]:
From mathcomp Require Import all_ssreflect.

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

Lemma nat_of_bool_inj : injective nat_of_bool.
Proof. by case=> [] []. Qed.

Lemma all_false n (r : n.-tuple bool) :
  \max_(i in 'I_n) tnth r i <= 0 ->
  forall i, tnth r i = false.
Proof.
by move/bigmax_leqP => H i; apply/nat_of_bool_inj/eqP; rewrite -leqn0 H.
Qed.

You have some more specialized lemmas relating \big[orb/false] with has.

A: The code consists of two parts:
I have proved my lemma for List in the 1st part and, similarly, I have almost proved for Vector in the 2nd part.
There is a problem in the last step of the second part.
("induction p." causes "Abstracting over the terms "n0" and "p"  leads to a term … which is ill-typed". I don't understand what shall I do instead of "induction p.".)
(*PART 1*)
Require Import Coq.Lists.List.
Import ListNotations.

Fixpoint A2 l :fold_left orb l true = true.
Proof.
destruct l; simpl.
reflexivity.
apply A2.
Defined.

Theorem A1 (x y:bool): (orb x y = false)->(x=false)/\(y=false).
Proof. intro H. destruct x, y; firstorder || inversion H. Defined.

Fixpoint A0 b l : fold_left orb (b :: l) false = orb b (fold_left orb l false) .
Proof.
destruct l.
simpl. firstorder.
simpl.
destruct b.
simpl.
apply A2.
simpl.
reflexivity.
Defined.

Fixpoint all_then_some (l:list bool) {struct l}:
(List.fold_left orb l false) = false ->
(forall (p:nat), (List.nth p l false) = false).
Proof.
intros.
destruct l. simpl. destruct p; trivial.
simpl.
rewrite A0 in H.
pose (Q:=A1 _ _ H).
destruct Q.
destruct p. trivial.
apply all_then_some.
trivial.
Defined.
(*PART 2*)
Require Import Coq.Vectors.Vector.
Import VectorNotations.

Fixpoint B2 (n:nat) (l:t bool n) :fold_left orb true l  = true.
Proof.
destruct l; simpl.
reflexivity.
apply B2.
Defined.

Fixpoint B0 b (n:nat) (l:t bool n) :
fold_left orb false (b :: l)  = orb b (fold_left orb false l) .
Proof.
destruct l.
simpl. firstorder.
simpl.
destruct b.
simpl.
apply B2.
simpl.
reflexivity.
Defined.

Fixpoint all_then_someV (n:nat) (l:Vector.t bool n) {struct l}:
(Vector.fold_left orb false l ) = false ->
(forall p, (Vector.nth l p  ) = false).
Proof.
intros.
induction l eqn:equa.
inversion p. (* simpl. destruct p; trivial.*)
(*simpl.*)
rewrite B0 in H.
pose (Q:=A1 _ _ H).
destruct Q.
induction p.

I think something like the following code can help (because "destruct" tactic is like "_rect" application), but I am not sure.
Definition G0 h (n:nat) (l:Vector.t bool n) := fold_left orb false (h :: l) = false.
fold G0 in H.
assert (vari : G0 h n l).
exact H.
clear H.
revert h l vari.
set (P := fun n p => forall (h : bool) (l : t bool n) (_ : G0 h n l),
@eq bool (@nth bool (S n) (cons bool h n l) p) false).
unshelve eapply (@Fin.rectS P).

UPDATE2: Solution is here: https://github.com/georgydunaev/TRASH/blob/master/UNIV_INST.v
(it is called "Theorem all_then_someV")


text:
Q: CSS Transform - Rotate & Skew doesn't work together I've got a question which hopefully someone will be able to help out with. So I am trying to create a diamond div shape which will itself, be a link:

Creating these a separate divs with for instance and image for the diamond with a link around it won't work in this situation due to the overflow on to the other blocks.
So my first though was to create a div and use transform in CSS to get this desired effect:

However, when trying to create this, get got the following:

.test {
 width: 192px;
 height: 144px;
 transform: skewX(-40deg) rotate(25deg);
 display: block;
 background-color: red;
 top:50px;
 left:50px;
 position:absolute;
}

By running this, you can see that within the transform attribute, both rotate and skew cannot work together as it seems the skew is affected by the rotate.
Has anyone else come across the same sort of thing when trying to create custom shapes like this? Is there another way (either CSS or Javascript) where I could get the desired effect?
Any help would be greatly appreciated. If anyone needs any further information, please let me know.
Thanks very much :)

A: As I explained in another answer (Simulating transform-origin using translate). The multiplication is done from left to right but the visual effect is from right to left:

.test {
 width: 192px;
 height: 144px;
 transform:rotate(25deg)  skewX(-40deg) ;
 display: block;
 background-color: red;
 top:50px;
 left:50px;
 position:absolute;
}

By the way, here is some alternatives to achieve a similar shape without transform.
With gradient:

.box {
  width:200px;
  height:100px;
  background:
    linear-gradient(to top right, red 49%,transparent 50%) top right,
    linear-gradient(to top left, red 49%,transparent 50%) top left,
    linear-gradient(to bottom right, red 49%,transparent 50%) bottom right,
    linear-gradient(to bottom left, red 49%,transparent 50%) bottom left;
  background-size:50% 50%;
  background-repeat:no-repeat;
}

With clip-path:

.box {
  width: 200px;
  height: 100px;
  background: red;
  -webkit-clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
  clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
}

With SVG:

<svg viewBox="0 0 200 100" width='200'>
<polygon points="0 50,100 0,200 50,100 100" fill=red />
</svg>

A: You need to declare the rotate before the skew.
Transform is very specific in what order its transformations are done.


text:
Q: fluentd tail read_from_head true doesn't work Wanted to read logs from "/var/log/yum.log" as an example, with fluentd's tail plugin, and input it to solr collection1. When I tried with default config, solr displayed only logs that where read during the plugin was running. But i wanted to read the whole file from the beginning with all past logs. So as fluentd documentation suggested, I used "read_from_head true" parameter in "source" section. However it had no effect, the tail plugin still worked the same way, just reading the last logs.
Could you please suggest what am i doing wrong?
This is my config file:
<source>
  @type tail
  <parse>
      @type none
  </parse>
  path /var/log/yum.log
  pos_file positions.pos
  tag varlog.*
  path_key filename
  read_from_head true
</source>

<match varlog.**>
  @type solr

  # The Solr base url (for example http://localhost:8983/solr).
  base_url http://localhost:8983/solr

  # The Solr collection/core name (default collection1).
  collection collection1
</match>

A: Have you run fluentd ever before , and does file "positions.pos" exsit?
if so , you have to delete file "positions.pos" first.


text:
Q: How to use sap.m.ViewSettingsDialog in a sap.suite.ui.commons.Timeline as a custom filter? Currently, I want to integrate a multi-faceted filter in a sap.suite.ui.commons.Timeline, as it is described in the Fiori Design Guidelines. The guidelines say, that one have to use a sap.m.ViewSettingsDialog for it.
Looking into the Timeline API says, that there exists an aggregation customFilter, but the control used inside needs to have an openBy function, which is called to open the custom filter popover / dialog.
My problem now is, that the sap.m.ViewSettingsDialog does not have a openBy function, but only (since it is a dialog, the API description reflects it) an open() function.
How do I correctly implement a multi-faceted filter by using the ViewSettingsDialog?
Thanks so much!

A: You have three options:

*

*Use a different Popover (e.g. ResponsivePopover).

*Hide the filter bar button by setting the showTimeFilter and showItemFilter to false and than add your own button with whatever logic you need:
oTimeline.getHeaderBar().addContent(new Button({
    press: function () {
      oViewSettingDialog.open();
    }
});

*You can extend the sap.m.ViewSettingsDialog to add an openBy method which will just call open. It can be done statically:
var CustomViewSettingDialog = ViewSettingDialog.extend("my.namespace.CustomViewSettingDialog", {
  openBy: function () {
    this.open();
  }
});

Or in runtime:
var oViewSettingDialog = new ViewSettingDialog(...);
oViewSettingDialog.openBy = function () {
  this.open();
}


text:
Q: Could not get audio input stream from input stream I want to get the sound file at the URL provided in the code and play it (It is in mp3 format). I looked through some Stack Overflow questions related to this problem, and they all said to get mp3plugin.jar so I did.
In Eclipse, I added it as an external jar (as it is located inside of my Downloads folder, not sure if that's the best place for it) under Configure Build Path. I ran it again and it's still giving me this error:

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream
      at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
      at Starter.main(Starter.java:21)

Here is the code:
public class Starter {

    public static void main(String[] args) {
        AudioInputStream din = null;
        try {
            URL url = new URL("http://c5.rbxcdn.com/2e6d33a5b3b1d8f250c395816ff9f145");
            HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
            InputStream bufferedIn = new BufferedInputStream(httpcon.getInputStream());
            AudioInputStream in = AudioSystem.getAudioInputStream(bufferedIn);
            AudioFormat baseFormat = in.getFormat();
            AudioFormat decodedFormat = new AudioFormat(
                    AudioFormat.Encoding.PCM_SIGNED,
                    baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
                    baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
                    false);
            din = AudioSystem.getAudioInputStream(decodedFormat, in);
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
            SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
            if(line != null) {
                line.open(decodedFormat);
                byte[] data = new byte[4096];
                // Start
                line.start();

                int nBytesRead;
                while ((nBytesRead = din.read(data, 0, data.length)) != -1) {
                    line.write(data, 0, nBytesRead);
                }
                // Stop
                line.drain();
                line.stop();
                line.close();
                din.close();
            }

        }
        catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            if(din != null) {
                try { din.close(); } catch(IOException e) { }
            }
        }
    }
}

A: You need to get http://www.javazoom.net/mp3spi/docs/doc1.9.4/javazoom/spi/mpeg/sampled/file/MpegAudioFileReader.html
download the jars. I have my classpath as
.;C:\Vision\Audio\libs\vorbisspi1.0.3.jar;C:\Vision\Audio\libs\tritonus_share.jar;C:\Vision\Audio\libs\tritonus_remaining-0.3.6.jar;C:\Vision\Audio\libs\jorbis-0.0.15.jar;C:\Vision\Audio\libs\jogg-0.0.7.jar;C:\Vision\Audio\libs\jl1.0.jar;C:\Vision\Audio\libs\mp3spi1.9.4.jar;

you probably only need mp3spi1.9.4.jar - some of these are for other formats but I'm not sure so I include them all.
Then have the following program
public AudioInputStream readMP3URL(String f) {
    AudioInputStream audioInputStream = null;
    AudioFormat targetFormat = null;
    try {
        AudioInputStream in = null;
        MpegAudioFileReader mp = new MpegAudioFileReader();
        in = mp.getAudioInputStream(new URL(f));
        AudioFormat baseFormat = in.getFormat();
        targetFormat = new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED,
                baseFormat.getSampleRate(),
                16,
                baseFormat.getChannels(),
                baseFormat.getChannels() * 2,
                baseFormat.getSampleRate(),
                false);
        audioInputStream = AudioSystem.getAudioInputStream(targetFormat, in);
    }
    catch (Exception ue) {
        System.out.println("\nUnsupported Audio");
    }
    return audioInputStream;
}

public void readURL() {
    int i, j, k = 0, l, basicU = 1024;
    AudioFormat targetFormat = null;
    audioInputStream = readMP3URL("http://c5.rbxcdn.com/2e6d33a5b3b1d8f250c395816ff9f145");
    if (audioInputStream == null) System.out.println("null audiostream");
    targetFormat = audioInputStream.getFormat();
    byte[] data = new byte[basicU];
    DataLine.Info dinfo = new DataLine.Info(SourceDataLine.class, targetFormat);
    SourceDataLine line = null;
    try {
        line = (SourceDataLine) AudioSystem.getLine(dinfo);
        if (line != null) {
            line.open(targetFormat);
            line.start();
            while ((k = audioInputStream.read(data, 0, data.length)) != -1) {
                line.write(data, 0, k);
            }
            line.stop();
            line.close();
        }
    }
    catch (Exception ex) {
        ex.printStackTrace();
        System.out.println("audio problem " + ex);
    }
}


text:
Q: Fast methods to copy(move) files in batch file I have a massive number of files in one directory that I need to validate.
The problem was, the file explorer takes too much time to load the file list and my whole computer becomes slow.
So I wrote the following code to group files by moving certain number of files(shown as %limit% and will be 700) to numbered folders(shown as %DirN%)
for /f "tokens=1-2 delims=:" %%a in ('dir /b /a-d ^|findstr /n /v ".bat .cmd .txt"') do if %%a lss %limit% robocopy "%cd%" "%cd%\%DirN%" "%%b" /mov >nul

This code itself worked fine just as it was designed, but an additional problem was found: speed.
Since I am dealing with the files that are occupying 20 GB of my disk, the code seems to take forever to move files this way.
Is there any faster way to copy(move) files?
ps. I've tried /move and /xcopy commands but did not see much differences.

Since there was a request for context, I attach full code:
@echo off
pushd %~dp0

set DirN=-1
:Check_DirN
set LeftOver=
for /f "tokens=*" %%a in ('dir /b /a-d ^|findstr /v ".bat .cmd .txt"') do (set LeftOver=%%a)
if "%LeftOver%"=="" goto Done

set /a DirN+=1
if exist "%cd%\%DirN%" goto Check_DirN

:Create
md %DirN%

:Move
cls
echo Moving files to Directory %DirN%...
set /a limit=700+2
for /f "tokens=1-2 delims=:" %%a in ('dir /b /a-d ^|findstr /n /v ".bat .cmd .txt"') do if %%a lss %limit% robocopy "%cd%" "%cd%\%DirN%" "%%b" /mov >nul
goto Check_DirN

exit
:Done
del list.txt>nul 2>&1
echo Task Done!
pause>nul

Comments

*

*I used set /a to adjust %limit% that are off due to findstr /n /v

*This script will be compiled to .bat file and will be put into a folder containing files to sort.

Example Environment(minimized):
There are 1,500 documents with subfolders named 0,2 and 4 in a parent folder.
The script will be placed inside of the parent folder and be executed.

Script requirements:

*

*Create numbered directory starting from 0, only if the directory doesn't exist

*Move 700 files to newly created directory. The files will be moved
even if the number of files is less than 700.

*Repeat task 1 and 2 until there are no remaining files left in
the parent directory.

Example Result of Script Execution:
There are subfolders named 0, 1, 2, 3, 4 and 5 with a script in a parent folder.
There will be 700 documents each in subfolder 1 and 3.
There will be 100 documents in subfolder 5.
The will be no change in subfolders 0, 2 and 4.

A: I am providing this as an alternative to Magoo's answer. I have used your initial RoboCopy command and because that is an external command, removed the dependency on the external FindStr to hopefully take account of any speed difference.
@Echo Off
If /I Not "%__CD__%"=="%~dp0" PushD "%~dp0" 2>Nul||Exit/B
SetLocal EnableDelayedExpansion
Set "DirN=-1"

:Check_DirN
Set/A "DirN+=1"
If Exist "%DirN%" GoTo Check_DirN
Set "limit=700"
For %%A In (*.bat *.cmd *.txt) Do (
    If Not Exist "%DirN%" MD "%DirN%"
    If /I Not "%%~nxA"=="%~nx0" RoboCopy . "%DirN%" "%%A" /MOV 1>NUL
    Set/A "limit-=1"
    If !limit! Lss 0 GoTo Check_DirN
)
Echo(Task Done!
Timeout -1 1>Nul

A: @echo off
pushd %~dp0

set DirN=-1
:Check_DirN
set /a DirN+=1
if exist "%cd%\%DirN%" goto Check_DirN
md %DirN%
set /a limit=700
for /f "tokens=1* delims=:" %%a in ('dir /b /a-d ^|findstr /v ".bat .cmd .txt" ^|findstr /n "." ') do (
 if %%a gtr %limit% goto Check_DirN
 set /a limit=0
 echo(move "%%b" "%cd%\%DirN%\"
)
if %limit% neq 0 rd %DirN%
echo Task Done!
pause>nul

The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE to MOVE to actually move the files.  Append >nul to suppress report messages (eg. 1 file moved)
First, create the new directory. No need to involve the for in this.
Next, establish your limit, then select-and-number your directorylist and move each file in turn to the destination.
When the file limit is reached, go back and create a new destination directory.
Note that delayedexpansion is exploited. %limit% will be replaced by its value in the parsing phase, and will be set to 0  if any file is moved. Since the replacement of its real value has already been done by the parser, this will not affect the loop, but can be detected after the loop is finish to mean "a file was moved".
If no file was moved, then limit will remain non-zero on exiting the for loop, hence the newly-created directory is empty and can be deleted.
I'd suggest you try this with a smaller limit on a dummy test directory to ensure it works. Should be substantially faster.
[edit - create directory after having checked it doesn't already exist]
[edit2- cascade 2 findstrs - the first to exclude the extensions, the second to number the lines. Attempting to use one findstr will number according to the position in the dir command, so excluded files will be allotted a number, but not be transferred; hence the count-moved would be short of limit
Note that since the files are not actually moved with the echo(move in place, the same list of files will be repeated over and over. When the move is invoked, the files that have been moved obviously won't be found in a leter iteration]


text:
Q: train() in caret package returns an error about names & gsub I am using caret package to predict the improvementNoticed variable
library(caret)
head(trainData)

     improvementNoticed                            V1               V2
681                   0                    0.06451613       0.006060769
1484                  0                    0.77924586       0.331009145
1356                  0                    0.22222222       0.017538684
541                   0                    0.21505376       0.011102470
2214                  1                    0.59195217       0.064764408
1111                  0                    0.97979798       0.036445064
               V3                                          V4       V5
681   0.008182531                                  0.05263158        0
1484  0.316603794                                  0.88825188        0
1356  0.016182822                                  0.20000000        0
541   0.012665610                                  0.10000000        0
2214  0.051008693                                  0.55000000        0
1111  0.034643632                                  0.93333333        0

and I run
myControl = trainControl(method='cv',number=5,repeats=2,returnResamp='none')
model1 = train(improvementNoticed~., data=trainData, method = 'glm', trControl=myControl)

and I get the following error:
Error in names(out) <- paste("Fold", gsub(" ", "0", format(seq(along = out))),  :
  'names' attribute [1] must be the same length as the vector [0]

This is a result of the trainData[,1] being a factor (rest numeric); previously (when trainData[,1] was numeric) I got a different error:
Error in cut.default(y, unique(quantile(y, probs = seq(0, 1, length = cuts))),  :
  invalid number of intervals

Please note that improvementNoticed is a binary variable.
If i convert trainData[,1] into integer, I get the same error, as with a numeric.
Two last things:
traceback()
5: createFolds(y, trControl$number, returnTrain = TRUE)
4: train.default(x, y, weights = w, ...)
3: train(x, y, weights = w, ...)
2: train.formula(improvementNoticed ~ ., data = trainData, method = "glm",
       trControl = myControl)
1: train(improvementNoticed ~ ., data = trainData, method = "glm",
       trControl = myControl)

And results of sessionInfo()
R version 3.0.1 (2013-05-16)
Platform: x86_64-redhat-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8
 [5] LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_GB.UTF-8
 [7] LC_PAPER=C                 LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] parallel  stats     graphics  grDevices utils     datasets  methods
[8] base

other attached packages:
 [1] elasticnet_1.1     lars_1.2           klaR_0.6-9         MASS_7.3-26
 [5] kernlab_0.9-18     nnet_7.3-6         randomForest_4.6-7 doMC_1.3.0
 [9] iterators_1.0.6    caret_5.17-7       reshape2_1.2.2     plyr_1.8
[13] lattice_0.20-15    foreach_1.4.1      cluster_1.14.4

loaded via a namespace (and not attached):
[1] codetools_0.2-8 grid_3.0.1      stringr_0.6.2   tools_3.0.1

A: As it happens, the error was a really basic one.
I was performing normalization on the data (that I did not suspect would cause the issue) but it turned out one of the variables only had 0's in it; hence I got all NaN's, which caused the model to fail.


text:
Q: How to use 2-factor auth with Bitbucket API I have this code which use to work with the Bitbucket API (api.bitbucket.org), but it no longer works because I turned on 2-factor auth (which requires you to provide a code using your mobile phone).
const bitbucketBase64 = Buffer
  .from(`afills@teros.net:Gmm4br_*`)
  .toString('base64');

const request = https.get({

    protocol: 'https:',
    port: 443,
    hostname: 'api.bitbucket.org',
    path: pth,
    headers: {
      'Authorization': `Basic ${bitbucketBase64}`,
    }

  });

so is there a way to create a bitbucket account that has 2-factor auth but can still access the api programmatically? or should I turn-off 2 factor-auth for our bots that need to access the bitbucket api?

A: I am quite sure that the App Passwords are the ones you are looking for. Look at this for more information: https://confluence.atlassian.com/bitbucket/app-passwords-828781300.html
In short: App Passwords can be created on the Access management page of your user and then be used as normal Basic Authentication.


text:
Q: Symfony2 controller navbar i would put a controller for my navbar and i would use a query to get a variable from my database..
I don't have a controller and i create it in this way:
<?php

  namespace Dt\EcBundle\Controller;

  use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  use Symfony\Component\HttpFoundation\Request;

  class NavbarController extends Controller {

public function navbarAction(Request $request) {
    $prova = "ciao";
    return $this->render('DtEcBundle:Header:navbar.html.twig',array(
            "prova" => $prova,

    ));
    }
 }

Now i put my render controller in the body of : "{# app/Resources/views/base.html.twig #}"
{{ render(controller('DtEcBundle:Navbar:navbar', { 'prova': prova })) }}

I follow this but i don t understand the error: "http://symfony.com/doc/current/book/templating.html#embedding-controllers"
I Get this error Variable "prova" does not exist in DtEcBundle:Header:navbar.html.twig at line 5 but if i write the code in navbar.html.twig give me equals error..
If i remove the variable and i write only
{{ render(controller('DtEcBundle:Navbar:navbar')) }}

Give me a server error number 500 o.o..
How can i do for use my controller only in navbar.html.twig??

A: The error is the code:
{{ render(controller('DtEcBundle:Navbar:navbar', { 'prova': prova })) }}

the prova variable doesn't exists in twig, the controller is fine.
I if you want put the var from twig to controller:
 /**
 * @Route("/prova/{prova}", name="prova")
 */
public function navbarAction(Request $request,$prova) {
    return $this->render('DtEcBundle:Header:navbar.html.twig',array(
            "prova" => $prova,

    ));
}

and twig:
{% set prova = 'foo' %}
{{ render(controller('DtEcBundle:Navbar:navbar', { 'prova': prova })) }}

A: navbarAction doesn't take prova variable as a parameter, so why are you passing it there in a base template?
I think that action should fetch these data from db.
In that case, using:
{{ render(controller('DtEcBundle:Navbar:navbar')) }}

seems to be ok, and error is somewhere else.
If you get a 500, check logs to tell us what's exactly wrong.
And format your code, it's barely readable.


text:
Q: How do I connect a python server to an android project? I am working on a project in Android Studio and I want to connect it to a server I wrote in python using multiThreaded sockets. The Python server works fine with clients written in python, but my Android client is not able to connect.
This is the server:
# thread function
def threaded(soc):
    while True:

        # data received from client
        data = soc.recv(1024)
        if not data:
            print('Bye')

            break
       # todo
    # connection closed
    soc.close()

def main():
    host = 'localhost'

    port = 12345
    listen_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_soc.bind((host, port))
    print("socket binded to port", port)

    # put the socket into listening mode
    listen_soc.listen(5)
    print("socket is listening")

    # a forever loop until client wants to exit
    while True:

        # establish connection with client
        soc, addr = listen_soc.accept()
        print('Connected to :', addr[0], ':', addr[1])

        # Start a new thread and return its identifier
        start_new_thread(threaded, (soc,))
    listen_soc.close()

if __name__ == '__main__':
    main()

and this is the android client:
private ServerHandler sh;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sh = new ServerHandler();
        if(sh.connect("___.___.__.__", 12345))
            Log.d("MYTAG", "connected");
        else
            Log.d("MYTAG", "couldn't connect");
    }

ServerHandler class:
    public class ServerHandler extends Thread {
    private Socket socket;
    private BufferedReader in;
    private PrintStream out;
    public ServerHandler() {
        socket = new Socket();
    }

    /**
     * Tries to connect to a server
     * @return True if successfully connected, otherwise False
     */
    public boolean connect(String ip, int port) {
        try {
            socket.connect(new InetSocketAddress(ip, port));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintStream(socket.getOutputStream(), true /* If this is false, you need to call out.flush() for the PrintWriter to send*/);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Closes the socket
     */
    public void disconnect() {
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
        Sends a string *without* a \n
     */
    public void send(String s) {
        out.print(s);
    }
    /*
        Sends a string with a \n
     */
    public void sendLine(String s) {
        out.println(s);
    }
    /*
        Receives a line. NOTE: This method will lock the program until a **line** (\n) is received.
     */
    public String recvLine() {
        try {
            return in.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}


text:
Q: What impact would Riemann's conjecture if it had to be demonstrated as a whole? I ask myself for many years without ever having answers that suit me.

What impact would Riemann's conjecture if it had to be demonstrated as
  a whole?  What would be the impact on our lives?

I already know that the Riemann hypothesis holds its importance in number theory, particularly on prime numbers.
The Riemann hypothesis is one of seven Millenium problems, a reputed insurmountable mathematical challenge posed by the Clay Mathematics Institute in $2000$. One of the criteria why the institute has chosen seven problems was that the resolution would be a great interest to advance mathematics and society.
Can you share me your opinion on this question?
P.S. I already know there exists a similar question : Proving the Riemann Hypothesis and Impact on Cryptography and What is so interesting about the zeroes of the Riemann $\zeta$ function?. However, the question is not exactly the same.
The question has been modified

A: Notwithstanding Godel's proof, it would be another instance that if a conjecture
seems true, it will eventually be proven to be so. I put this in the same class
as the Collatz conjecture. Ed Gray


text: Q: como puedo ver una pagina desde mi telefono por wifi a un computador que tiene un servido lamp que esta conectado a la misma red wifi no se si me explique bien en el titulo de la pregunta, pero acá doy mas detalle, para empezar aclaro que tengo un computador con linux instalado, y tengo un servidor local con xampp. como dije tanto mi PC como mi teléfono están conectados a la misma red wifi, a lo que quiero llegar es si es posible que pueda yo visualizar o interactuar con la pagina web o aplicación que realice con PHP en mi PC, accediendo desde mi teléfono ?.. saludos


text:
Q: Mutually referential Prolog rules in family tree I've seen various implementations of family trees in Prolog, but I haven't found one that does what I would like to do, which is to define child and parent by referring to each other.
I want to do this because sometimes I have a fact that someone is a child of someone, at other times I have the fact that someone is the parent of someone. From either of these kinds of facts, I'd like to be able to ask who are parents and who are children.
My attempt at coding this is :-
parent(mary, fred).
child(john, peter).
child(paul, peter).

parent(P, C).
parent(P, C) :- child(C, P).
child (C, P).
child(C, P) :- parent(P, C).

This seems to work ok except that it will continue to give me the same results duplicated over and over. Eg :-
[3]  ?- parent(peter, X).
true ;
X = john ;
X = paul ;
true ;
X = john ;
X = paul ;
true

Is there a way I can get it to stop after it has given me the full set of results once ?
More generally, is this kind of definition a weird thing to want to do (because of the mutual recursion) ? I want to be able to have facts of either parent or child, as reported, but also to infer the "opposite" relationship from these.
Thanks !

A: The issue with your program is that you are merging predicates.
parent/2 and child/2 are facts, you should not name a rule like a fact that is already defined in your program.
Rename the rules and all will work. Also, the base clause in your rules should add a condition, that match the fact, something like this:
parent(mary, fred).
child(john, peter).
child(paul, peter).

isparent(P, C):- parent(P, C).
isparent(P, C):- child(C, P).

ischild(C, P):- child(C, P).
ischild(C, P) :- parent(P, C).

Now the query:
?- isparent(peter, X).
X = john
X = paul

Also, don't use the complement rule in your condition, that's not necessary and will avoid you the recursion


text:
Q: Missing data when using unique count and creating an aggregation in Kibana I have a behavior in Kibana, I can't explain. The following is a simple bar chart, counting unique users, filtered by application and a role, and ensuring certain fields exist on the logs:

This graph shows that I have approx. 170 users which have the role 'Landmand'. If I split the bar by the term 'fields.Role', I would expect a identical chart, since I already applied a filter specifying 'fields.Role:Landmand' in the search. However I see this.

This suddenly limits the unique count to approx. 150 users. I've tried with different fields and it seems to have the same behavior - as soon as I split the bar, I seem to limit the data somehow.
Any information is greatly appreciated.

A: It happens because it uses the cardinality aggregation to do the unique count. As it is explained in the link, the count is approximate and it has a % of error. Just do a quick test, try to copy the request and try with a different precision threshold to see the difference.
To set a custom precision_threshold you can use the advanced section and put a custom JSON Input to the aggregation:

If you go to the Request section, you can actually see that the threshold has been added to the cardinality aggregation.


text:
Q: API divided into REST and SOAP parts and design patterns I need to work with some payment gateway API. The API is divided into two parts. There are some methods based on REST and a few methods accessible through SOAP webservice. I would like to create some bridge to combine it into single API class in my application. However I am not sure it is a good choice.
The question is.. is there any design pattern for this kind of situations?

A: I would suggest Gateway
The difference is that Gateway hides external API complexity to your internal API.
Facade, seems to me the opposite. Hides your complexity to external clients.
In both cases the implementation is similar.

A: As @user1172763 mentioned this is called a Facade. A facade is usually used to provide a simplified interface for a more complex system. But as the wiki link mentions, a Facade is also used to:

wrap a poorly designed collection of APIs with a single well-designed API.

In this case you hide two heterogenous APIs (one REST, one SOAP)  behind a homogenous (facade) API.

A: Not much of a pattern nerd, but I think that you would use the "Facade Pattern."

A: And in addition to using the Facade pattern, and if you want to get more elegant and pure with your code, I would recommend using the Adapter pattern to cleanly convert the interface of the outer API classes to what is expected for the inner API classes.


text:
Q: jQuery modal dialog using loading a form page that already contain jQuery code (Autocomplete) content? I have a form in a web page dynamically generated and I would like to display it using a the jQuery UI modal dialog.
The solution I was proposed in a previous post works when my form does not embedded jQuery UI itself : jQuery UI modal dialog form using remote content.
The way the remote form already contains jQuery functions : Autocomplete.
How to solve that problem?

                    software
                    script
                    exec_type
                    run_status
                    test_result
                    review_status
                    priority
                    author
                    creation date
                    update date
                    edit

                    software
                    script
                    exec_type
                    run_status
                    test_result
                    review_status
                    priority
                    author
                    creation date
                    update date
                    edit

form.html looks like that:

        <form action="/followup/forms/runs/8/" method="post">

Software: <select name="software" id="id_software">

                    <option value="">---------</option>
                    <option value="1" selected="selected">AS_1500_211</option>
                    <option value="2">AS_1500_212</option>
                    <option value="3">AS_1500_213</option>
                    <option value="4">AS_1500_214</option>
                </select>

Script: <select name="script" id="id_script">
                    <option value="">---------</option>
                    <option value="1">OBJECT__1_TC1</option>

                    <option value="2">OBJECT__2_TC1</option>
                    <option value="3">OBJECT__2_TC2</option>
                    <option value="4">OBJECT__3_TC1</option>
                    <option value="5">OBJECT__3_TC2</option>
                    <option value="6">OBJECT__4_TC1</option>
                    <option value="7">OBJECT__4_TC2</option>
                </select>

            <input type="submit" value="Submit" />
        </form>

A: so I know that this is an old post, but i don't see an answer here.  I believe what you need is something like a jquery plugin called livequery.  It will allow you to add the jquery-ui features to your table that gets loaded dynamically by waiting until they exist in the dom.
current:
$(function() {
        $("#id_software").combobox();
        $("#id_script").combobox();
});

with livequery:
$(function() {
        $("#id_software").livequery(function() { $(this).combobox(); });
        $("#id_script").livequery(function() { $(this).combobox(); });
});


text:
Q: How do I Make My created_at Timestamps set to the User timezone? I have a React/Rails app that allows users to submit a report. However, the reports are always being marked with a utc created_at timestamp. Since the users are in different timezones this can cause a problem.
For example, if I create a report at ~9pm PST for February 7, the utc timestamp will show February 8 - which messed with daily reporting.
I thought this could mitigated on the front end, but using the javascript Date() object, which I thought would be local to the machine running the js, but the rails db timestamps still show the UTC time.
So far I've tried that, adding this in the createReport component
  async function handleSubmit(e) {
    e.preventDefault();
    if (!rep_type) {
      alert("Please provide a rep_type")
      return
    }
    const date = new Date();
    let data = await axios.post(`${API_ROOT}/api/reports`, {
      report: {
        user_id: props.currentUser.id,
        rep_type: rep_type,
        rep_count: rep_count,
        created_at: date
      }
    })

And then in my reports_controller.rb I am expecting created_at to be a parameter
  def create
    @report = Report.create!(
      user_id: params["report"]["user_id"],
      rep_type: params["report"]["rep_type"],
      rep_count: params["report"]["rep_count"],
      created_at: params["report"]["date"]
    )
  end

What's interesting, is when I console.log(date) I see what I'd expect:
Mon Feb 07 2022 18:15:52 GMT-0800 (Pacific Standard Time)

But when I look at the network request I see the date is back to UTC

Edit:
By changing my POST request in createReport to send date as a string I can see in the network request I am sending the date/timezone I want, but rails is automatically changing it to UTC so I think it's a rails thing to fix.
What would be the most straightforward approach to make sure the date is at least accurate to the date in which the user created the report?

A: What I usually do is to ask the user to select the timezone that he/she wants to use in the system and then in a around_action I set the timezone for the request. In that way all dates are saved in UTC but are visible in the user's timezone
around_action :set_time_zone
...
def set_time_zone
  old_time_zone = Time.zone
  Time.zone = current_user.timezone
  yield
ensure
  Time.zone = old_time_zone
end

Another option is to send the offset (not the date) from the browser and set the Time.zone based on that
const date = new Date();
const offset = date.getTimezoneOffset()/60;

and then in rails
Time.zone = ActiveSupport::TimeZone[-offset]

But, it could be tricky for DST
My advice is to keep the timestamps as UTC in the database and only transform it to show to the user, for reporting just be careful doing the searches using times that include timezones


text:
Q: Vue Dynamic URL From state. In axios call I want to parse the axios url call from a variable state in vuex. As simple as this:-
state: {
getOrganizationURL: "opensource",
}

actions: {
  getOrganizationDashboard({commit, state}) {
      axios
      .get(`"https://xxx/api/report/"${state.getOrganizationURL}`, {
        headers: {
          Authorization: `Bearer ${state.currentAuthToken}`,
        },
      })
      .then(response => {
        commit("setOrganizationsDashboardData",response.data)

      });
  },
}

when checking the network on the browser. The API call is going to a weird url instead.
e.g
Request URL: http://localhost:8080/%22https://xxxx/api/report/%22opensource
which leads to page not found...
I think it a minor mistake. Any tips please?


text:
Q: Me aparece un pequeño espacio a la derecha cuando hago un slider Pues resulta que hice un slider con HTML y CSS y me aparece un pequeño espacio a la derecha del todo y no logro solucionarlo con overflow: hidden, este es mi codigo:

.main__partners {
  .slider {
            position: absolute;
            top: 2146px;
            left: 20px;
            width: 100%;
            height: 204px;
            margin: auto;
            overflow: hidden;
            .slider__track {
                display: flex;
                animation: scroll 70s linear infinite;
                -webkit-animation: scroll 70s linear infinite;
                width: calc(200px * 24);
            }
            .slide {
                width: 200px;
                height: 204px;
                margin: 0 10px;
                background: #FFFFFF;
                box-shadow: 0px 4px 15px 10px rgba(0, 0, 0, 0.04);
                border-radius: 8px;
                text-align: center;
                img {
                    width: 80%;
                    height: 70px;
                    margin: 25px 0;
                }
                h5 {
                    display: inline-block;
                    width: 132px;
                    height: 18px;
                    color: $cSliderHeader;
                    font-weight: 600;
                    font-size: 1.8rem;
                    line-height: 20px;
                }

                .sub__title {
                    margin-bottom: 20px;
                    p {
                        font-weight: 600;
                        font-size: 1.2rem;
                        line-height: 26px;
                    }
                }

                .date {
                    width: 132px;
                    height: 12px;
                    font-size: 1.2rem;
                    font-weight: 400;
                    line-height: 10px;
                    display: inline-block;
                    color: $cSliderDate;
                }

                .normal__date {
                    margin-top: 15px;
                }
            }
            @keyframes scroll{
                0% {
                    -webkit-transform: translateX(0);
                    transform: translateX(0);
                }
                100% {
                    -webkit-transform: translateX(calc(-200px * 12));
                    transform: translateX(calc(-200px * 12));
                }

}

Contamos con el apoyo y respaldo de excelentes aliados

Incubación

Mayo 2020

Ronda
Pre-Semilla

Julio 2020

Aceleración

Octubre 2020

Premio

"Transformando al mundo"

Julio 2021

Ronda
Seed

Septiembre 2021

Alianza

"Mitigar la migracion en Latam"

Enero 2022

Ronda
Pre-Serie A

Abril 2022

Ronda
Pre-Serie A

Abril 2022

Lanzamiento
México

Junio 2022

Lanzamiento
México

Junio 2022

Lanzamiento
México

Junio 2022

Ronda
Pre-semilla

Octubre 2020

Incubación

Mayo 2020

Ronda
Pre-Semilla

Julio 2020

Aceleración

Octubre 2020

Premio

"Transformando al mundo"

Julio 2021

Ronda
Seed

Septiembre 2021

Alianza

"Mitigar la migracion en Latam"

Enero 2022

Ronda
Pre-Serie A

Abril 2022

Ronda
Pre-Serie A

Abril 2022

Lanzamiento
México

Junio 2022

Lanzamiento
México

Junio 2022

Lanzamiento
México

Junio 2022

Ronda
Pre-semilla

Octubre 2020

En la imagen se puede ver el pequeño scroll que aparece para deslizar hacia la derecha.


text:
Q: Is the function $f(x) = \sum_{n\geq 1 } \cos(n^2 x ) / n^{2.6}$ absolutely continuous? It is of course continuous.
Here the exponent $2.6 $ is delibrately chosen to be bigger than $2.5$.
If we differentiate the series formally term-by-term, we will get
$$   - \sum_n \frac{\sin n^2 x }{n^{0.6}} . $$
This series is at least in the $L^2 $ space. That is why a number bigger than $2.5$ is chosen.  But I am not sure whether it is convergent. If in the numerator, it were $n$ in stead of $n^2$, it is convergent by the Dirichlet test.


text:
Q: How to map java reference type to database column type Suppose i have a classes like this
@Entity
public class Customer implements Serializable {
    private int id;
    private String firstName;
    private String lastName;
    private Referee referee;
    private Collection<Address> addresses;
    private Collection<Account> accounts;
    .....
} //end of class Customer

@Entity
public class Referee implements Serializable {
    private int id;
    private String name;
    private String comments;
    ....
} //end of class Referee

@Entity
public class Account implements Serializable {
    private int id;
    private double balance;
    private String accountType;
    ...
}

@Entity
public class Address implements Serializable {
    private int id;
    private String addressLine;
    private String country;
    private String postCode;
    ...
}

Now if i make Table in database of name Customer. Then what type will i use for the type Referee, Collection<Address> and Collection<Account>. Like if i make column id, then it's type will be INTEGER, String changes to VARCHAR but what type do i use for Collection and Referee?
Thanks

A: The referee field would be integer in the database because it has to store the id field of the Referee class which is of type int.
Collections will also be based on the id's of classes. For 1 to N relationships a column on the N side can be used. So if a Customer has multiple addresses but an address never belongs to more then one Customer then you can store the id of the customer in the address table to store the relationship. If it is N to M you will need an additional so called join table which stores paires of customer id + address id. Same story for accounts.
BTW many JPA providers can generate the tables for you see their manual for how.
If you are new to JPA you should get a good book about it. A couple of tutorials will not give you enough in depth knowledge to use it well. Personally I have read Pro EJB 3: Java Persistence API.
When learning JPA the netbeans IDE can be a great help as well as it will give you lots of useful hints for annotating your entities. It will for instance notice that your collections need additional annotations and will give you choices for one to many or many to many and uni- or bidirectional.


text:
Q: Current milliseconds since the start of execution How I get the current milliseconds since the start of execution in log4j patternlayout?
Eg:
000000.000| blah|
000000.000| blah|
000000.000| exception|
000000.001| foo|


text:
Q: Best way to deploy changes in an HAProxy cluster I have a two-node HAProxy cluster with Keepalived to provide high availability and redundancy. Now I'm trying to figure what is the best way to do changes in the configuration of my HAProxy's. Is there a rsync between the two clusters enough? (also with a command to reload the config on the slave one). Is there any better way?
Thanks!

A: Yes - use a configuration management tool like Puppet or Chef - store your config in version control, then the tool can handle distributing it to both servers and doing the graceful restart of the service.
It's probably overkill when you're looking at just this task, but it will be useful throughout your environment.