text:
Q: VSCode, WSL & Docker - Debugging with gdbserver I want to debug a C++ application with VSCode, running in docker container, inside WSL.
My current setup:

*

*VSCode is running on the host Windows machine. 'Native Debug' extension installed on the remote (should be installed locally?)

*Source code is within WSL Ubuntu distribution, VScode connected with WSL-Remote.

*The application can be executed from a docker container, with gdbserver installed. Container is with fixed IP (172.17.0.2).

I already ran gdbserver on the container with:
gdbserver 172.17.0.2:9999 /path/to/app
How can I attach VScode to the gdbserver, running in a container on the WSL?
Here is what I've already tried, and the outcome:

*

*
     {
         "name": "Simple Native Plugin",
         "type": "gdb",
         "request": "attach",
         "executable": "./app",
         "target": "172.17.0.2:9999",
         "cwd": "${workspaceRoot}",
         "remote": true
     },

Result:
Could not start debugger process, does the program exist in filesystem?
Error: spawn gdb ENOENT

*
  {
      "name": "(gdb) Attach - WSL - Native Plugin",
      "type": "gdb",
      "request": "attach",
      "target" : "172.17.0.2:9999",
      "remote" : true,
      "executable": "${workspaceFolder}/app",
      "gdbpath": "/usr/bin/gdbserver",
      "cwd": "${workspaceRoot}",

  },

Result:
undefined/bin/bash: line 0: exec: -q: invalid option
exec: usage: exec [-cl] [-a name] [command [arguments ...]] [redirection ...]
During startup program exited with code 2.
Exiting

*
 {
      "name": "(gdb) Launch - WSL - CPPdbg Plugin",
      "type": "cppdbg",
      "request": "launch",
      "remote" : true,
      "miDebuggerServerAddress": "172.17.0.2:9999",
      "miDebuggerPath": "/usr/bin/gdbserver",
      "program": "${workspaceFolder}/app",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceRoot}",
      "externalConsole": true,
      "linux": {
          "MIMode": "gdb",
      },
      "windows": {
          "MIMode": "gdb"
      }
  }

Result:
Starting: "/usr/bin/gdbserver" --interpreter=mi
Unknown argument: --interpreter=mi
"/usr/bin/gdbserver" exited with code 1 (0x1).

A: Your second try was almost correct. Try to enter the path to gdb instead of gdbserver in gdbpath.

A: For what it's worth, the TCP parameter for gdbserver is host:port where host is the IP of the host machine. The IP in the question is 172.17.0.2, which Docker uses for the Container's IP, try 172.17.0.1. That's the default for the host.
You can verify what addresses your container is using by running this in the host:
docker container inspect -f '{{ .NetworkSettings.IPAddress }}' <image-name>


text:
Q: How can I get the current SparkSession in any place of the codes? I have created a session in the main() function, like this:
val sparkSession = SparkSession.builder.master("local[*]").appName("Simple Application").getOrCreate()

Now if I want to configure the application or access the properties, I can use the local variable sparkSession in the same function.
What if I want to access this sparkSession elsewhere in the same project, like project/module/.../.../xxx.scala. What should I do?

A: Since 2.2.0 you can access the active SparkSession through:
/**
 * Returns the active SparkSession for the current thread, returned by the builder.
 *
 * @since 2.2.0
 */
def getActiveSession: Option[SparkSession] = Option(activeThreadSession.get)

or default SparkSession:
/**
 * Returns the default SparkSession that is returned by the builder.
 *
 * @since 2.2.0
 */
def getDefaultSparkSession: Option[SparkSession] = Option(defaultSession.get)

A: When SparkSession variable has been defined as
val sparkSession = SparkSession.builder.master("local[*]").appName("Simple Application").getOrCreate()

This variable is going to point/refer to only one SparkSession as its a val. And you can always pass to different classes for them to access as well as
val newClassCall = new NewClass(sparkSession)

Now you can use the same sparkSession in that new class as well.

A: Once a session was created (anywhere), you can safely use:
SparkSession.builder.getOrCreate()

To get the (same) session anywhere in the code, as long as the session is still alive. Spark maintains a single active session so unless it was stopped or crashed, you'll get the same one.
Edit: builder is not callable, as mentioned in the comments.

A: This is a old question and there are couple of answer that are good enough but I would like to give one more approach that can be used to make it work.
You can create a trait that extends from serializable and create spark session as a lazy variable and then through out your project in all the objects that you create, you can extend that trait and it will give you sparksession instance.
Code as below:
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.DataFrame
trait SparkSessionWrapper extends Serializable {
  lazy val spark: SparkSession = {
    SparkSession.builder().appName("TestApp").getOrCreate()
  }
//object with the main method and it extends SparkSessionWrapper
object App extends SparkSessionWrapper {
 def main(args: Array[String]): Unit = {
   val readdf = ReadFileProcessor.ReadFile("testpath")
   readdf.createOrReplaceTempView("TestTable")
   val viewdf = spark.sql("Select * from TestTable")
 }
}

object ReadFileProcessor extends SparkSessionWrapper{
 def ReadFile(path: String) : DataFrame = {
  val df = spark.read.format("csv").load(path)
  df
 }
}

As you are extending the SparkSessionWrapper on both the Objects that you created, spark session would get initialized when first time spark variable is encountered in the code and then you refer it on any object that extends that trait without passing that as a parameter to the method. It works or give you a experience that is similar to notebook.
Update : If you even want it to be more generic and have an need to even set the custom appname based on the type of workflow you are running you can do it as below :
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.DataFrame
trait SparkSessionWrapper extends Serializable {
  lazy val spark: SparkSession = {
    createSparkSession(appname)
  }
def appname : String
def createSparkSession(appname : String) : SparkSession ={
    SparkSession.builder().appName(appname).master("local[*]").getOrCreate()
  }
//object with the main method and it extends SparkSessionWrapper
object App extends SparkSessionWrapper {
 def main(args: Array[String]): Unit = {
   val readdf = ReadFileProcessor.ReadFile("testpath")
   readdf.createOrReplaceTempView("TestTable")
   val viewdf = spark.sql("Select * from TestTable")
 }
override def appname: String = "ReadFile"
}

object ReadFileProcessor extends SparkSessionWrapper{
 def ReadFile(path: String) : DataFrame = {
  val df = spark.read.format("csv").load(path)
  df
 }
override def appname: String = "ReadcsvFile"
}

the only main difference is that you need to create an abstract function inside the trait and then you would have to override that into any of the startup class that you are using to provide the value.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UBUNTU12.4(quantal) powerpc logon I work with a thrift store and we have an APPLE g3 ibook(dual USB) donated with some version of ubuntu. I downloaded the 12.4 version and the system asks for a password and username in the first screen.
I am not a linux/ubuntu expert. Need some help in
either
a. Change the Username/login
or better
b. Remove the pw requirement.
This will allow us to sell the machine, which has an airline card etc in it.
cheers
vichu
PS: to save bandwidth, please feel free to send me an email dierctly.

A: If you are just going to sell the computer it is best to do a fresh install so that all the old files are at least overwritten.
I would recommend that you install 12.04 not 12.10 as 12.10 is still in testing.  I would not be happy if I bought a computer that had an unstable OS
To install just boot into the Live USB or Live CD and select Install Ubuntu
When next screen comes up select Replace Ubuntu version X with Ubuntu 12.04
Mark the check box that says format the drive to reformat the drive and wipe all the documents and preferences
Then just let the installer run and when finished you should have a brand new Ubuntu installed.
BTW in doing this you will not need the old password.  To effectiely run Linux you need to have some password to do admin tasks.  Just choose some easy to remember password to install the system and tell the buyer to be sure to change it.  If you select using no password you can do nothing but boot the computer and run most programs, you cannot install remove or update without a password.  I.E. you have a limited account that is only slightly more useful than a guest acct.


text:
Q: Is it considered a bad practice to oversize an array so that negative indices behave well? I have been practicing implementing some classic dynamic programming algorithms and was wondering if my implementation of the longest common subsequence search has a significant code smell.
In python, my version of the code is as follows:
def calculate_LCS_matrix(S, T):
    '''
    Computes the longest common subsequence of the two input strings

    Args:
        S (str): first input string
        T (str): second input string
    '''

    # Here is the potentially offending line, I add 1 to both dimensions of the
    # array so that the array is padded with zeroes on the bottom and right.
    # With this, negative i and j indices simply return 0 from the other side of
    # the array, as desired.
    valuestore = np.zeros((len(S)+1, len(T)+1))

    def LCS(s_char, t_char, i, j):
        '''
        Computes LCS of substrings up to index i and j
        '''

        # Without the array padding, I would have to check special cases for
        # i==0 and j==0
        if s_char == t_char:
            return valuestore[i-1, j-1] + 1
        else:
            return np.max([valuestore[i-1, j], valuestore[i, j-1]])
    for i, s in enumerate(S):
        for j, t in enumerate(T):
            value = LCS(s,t,i,j)
            valuestore[i, j] = value

    return valuestore

I am not looking for input on the algorithm itself, just on whether or not it is a bad practice to use this 0-padding space to save lines of code and potential confusion.
If you can give any specific examples of where this  could lead to trouble, I would very much appreciate it!
To help illustrate, the result of running the calculate_LCS_matrix function on the strings
"AAABBBBAABB"
and
"AAABBCCAAB"
is this matrix:
array([[ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  0.],
       [ 1.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  0.],
       [ 1.,  2.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  0.],
       [ 1.,  2.,  3.,  4.,  4.,  4.,  4.,  4.,  4.,  4.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  5.,  5.,  5.,  5.,  5.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  5.,  5.,  5.,  5.,  6.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  5.,  5.,  5.,  5.,  6.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  5.,  5.,  6.,  6.,  6.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  5.,  5.,  6.,  7.,  7.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  5.,  5.,  6.,  7.,  8.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  5.,  5.,  6.,  7.,  8.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

The zero padding around the edges is being used during certain calls to LCS.

A: I don't see anything wrong with it in principle, if you can afford storage space and it makes your life easier.
But I don't personally do it this way, primarily because the guy coming after me (or me, six months later) might think they can actually write legitimate data into those padded rows and columns, and... Kaboom.  Notice how many comments you had to write into your code so that we could understand it well enough to answer your question?  You'd have to write those same comments IRL.
So I work out the correct logic for avoiding the array edge instead.


text:
Q: Laravel can't connect to AWS S3 I have set up an S3 bucket and created an IAM user with full S3 access permission, and ran composer require league/flysystem-aws-s3-v3.
I have also have configured the following in .env:
AWS_ACCESS_KEY_ID=XXXX
AWS_SECRET_ACCESS_KEY=YYYY
AWS_DEFAULT_REGION=us-west-3
AWS_BUCKET=my-bucket
AWS_USE_PATH_STYLE_ENDPOINT=false
FILESYSTEM_DRIVER=s3

The problem is that I can't interact with S3 at all from my controller.
I've tried sending files to S3:
$path = $request->Image->store('images', 's3');

I have also manually uploaded an image to S3, then tried to check if it can find it:
if (Storage::disk('s3')->exists('photo.jpg')) {
dd("file found");
} else{
dd("file not found");
}

This results in this error: Unable to check existence for: photo.jpg
This makes me think that the issue is with flysystem-aws-s3-v3.
Is there a way to narrow down where the issue resides? by the way, I'm using Laravel 9 and flysystem-aws-s3-v3 3.0 if that helps.

A: I finally found the reason why the connection didn't work.
This is how the .env file looked like:
//some env vars here...

AWS_ACCESS_KEY_ID=XXXX
AWS_SECRET_ACCESS_KEY=YYYY
AWS_DEFAULT_REGION=us-west-3
AWS_BUCKET=my-bucket
AWS_USE_PATH_STYLE_ENDPOINT=false
FILESYSTEM_DRIVER=s3

//many other env vars here...

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=

It turns out that Laravel (or maybe it was Flysystem?) already configured the same S3 variables and left the values empty. So my environment variables were getting overridden by these empty ones, leaving the connection to fail.
I guess the lesson to learn here is to always check your entire .env file if it contains multiple vars with the same key.
Bonus
After setting up S3 with Laravel, you could use these snippets to:

*

*Generate a random string as new name for your image file:

$imageName = preg_replace('/[\W]/', '', base64_encode(random_bytes(18)));

*

*Save an image to your S3 bucket:

Storage::disk('s3')->put($newImagePath, file_get_contents($imageName));
 //$imageName is just a string containing the name of the image file and it's extension, something like 'exampleImage.png'
 //make sure to include the extension of the image in the $imageName, to do that, concatenate your the name of your image with "." + $Image->extension()

*

*Get an image from your S3 bucket:

$image =  Storage::disk('s3')->temporaryUrl($imagePath, Carbon::now()->addSeconds(40));   //tip: if you get a squiggly line on tempraryUrl(), it's just Intelephense shenanigans, you can just ignore it or remove it using https://github.com/barryvdh/laravel-ide-helper
//This will generate a temporary link that your Blade file can use to access an image, this link will last for 40 seconds, this 40 seconds is the period when the image link will be accessible.
//Of course after your image loads onto the browser, even if the image link is gone, the image will remain on the page, reloading the page generates a new image link that works for another 40 seconds.
//This will work even with S3 images stored with Private visibility.

//In your blade file:
<img src="{{$image}}">

*

*Check if an image exists in your S3 bucket:

if (Storage::disk('s3')->exists($imagePath)) {  //make sure to include the full path to the image file in $imagePath
//do stuff
}

*

*Delete an image from your S3 bucket:

Storage::disk('s3')->delete($imagePath);

A: It looks like you did everything right! .. is it working for the local drive?
also you might try to flush the cache:
php artisan cache:clear
php artisan config:clear


text:
Q:  name does not exist I am trying to set up a combo box with in my DataGrid and I am not allowed to set the ItemSource of the combo box (in my in my .xaml.cs  code) because I keep receiving this error "The name 'cboChangeRequestStatus' does not exist in the current context. Don't understand why I can set this in other variations of DataGrid but cannot when I use this set
<DataGridTemplateColumn Header="Status">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding StatusCode}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox   SelectedValue="{Binding Status, Mode= TwoWay}"
                        SelectedValuePath="StatusId"
                        DisplayMemberPath="StatusCode"
                        Name="cboChangeRequestStatus"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

A: You cannot do that easily, and you shouldn't do that.
Directly from MSDN:
Styles and templates in WPF provide the ability to reuse and reapply content in a straightforward way. However, styles and templates might also include elements with XAML names defined at the template level. That same template might be used multiple times in a page. For this reason, styles and templates both define their own XAML namescopes, independent of whatever location in an object tree where the style or template is applied.
See: WPF XAML Namescopes
If you have a Class like:
public class Test
{
  public ObservableCollection<Status> StatusCollection { get; set; }
  public Status Status { get; set; }
}

Than you could use it like this:
ItemsSource="{Binding Path=StatusCollection}"
SelectedItem="{Binding Path=Status, Mode=TwoWay}"

Or consider creating a StaticResource for the collection if the collection is not dynamic.

A: Lets say.... you are setting the ViewModel as the DataContext of the Window in which you have you DataGrid... then..
XAML
<DataGridTemplateColumn.CellEditingTemplate>
     <DataTemplate>
         <ComboBox   ItemsSource="{Binding Path=StatusCodes,
                                             RelativeSource={RelativeSource
                                                              Mode=FineAncestor
                                             AncetorType={x:type Window}}}"
                     SelectedValuePath="StatusId"
                     DisplayMemberPath="StatusCode"
                     Name="cboChangeRequestStatus"/>
     </DataTemplate>
 </DataGridTemplateColumn.CellEditingTemplate>


text:
Q: How to load Python script into Jupyter Notebook without revealing code and making it available to all cells I'm trying to import a Python script as a module into one of my Notebooks, but the import or import importlib commands do not work in Jupyter Notebook like they do in a standard Python file and terminal.
I've come across the %load command but as far as I understand and have seen in my own Notebook, is that it only loads the contents of the script I'm trying to import into the current cell and is invisible to the other cells, and it also outputs the code in the script being imported for everyone to see.
I want to be able to load the script and make it available to all cells, as well as hiding the code for the purpose of encapsulation and also keeping the Notebook neat and tidy - only focusing on the code relevant to the topic of the Notebook. Is this possible?


text:
Q: Does running "exec echo some; echo test" in bash never print "some test"? Does running exec echo "some "; echo "test" in bash never print "some test"?
I would seek confirmation to this question, as I am writing a small shell script and I would like it to not contiue anything after the exec command has been called.
I think that I would not need to worry, as my understanding, after consulting:

*

*man 3 exec

*man 1p exec
The shell scripts, when executed by the shell will make

*

*the shell execute the program exec, which

*uses the exec*** family system calls that replace the shell/bash that which has been executing the script, by this impeding further actions of the shell (which was "replaced")

As laid out before, main goal of this question is to seek confirmation for my reasoning as to prevent that anything in the script occuring after the exec (such as echo test) would be executed.
I would appreciate a general answer (POSIX), as far as possible, but just in case of particularities I am most interested in GNU/Linux and GNU/Bash

A: Right, if exec succeeds, it replaces the current shell, so the following commands are not, err.. executed.
However, at least in Bash, the shell also exits if the exec fails:

exec [-cl] [-a name] [command [arguments]]
If command is supplied, it replaces the shell without creating a new process. [...]  If command cannot be executed for some reason, a non-interactive shell exits, unless the execfail shell option is enabled. In that case, it returns failure.

So even something like bash -c 'exec /bin/nosuchfile; echo foo' will just print an error message about the missing program file. To handle the error in the script, you'd need something like
#!/bin/bash
shopt -s execfail
exec /someprogram
echo whoops, it failed

But, you still get the error message from exec. If you put a redirection on the exec, it stays in effect if the script continues after the exec failed.

A: The exec builtin (with a command argument¹) replaces the shell process². No subsequent code in the shell process is executed.
Thus the only way exec echo "some "; echo "test" would print some text is if there was an executable command called echo in the PATH, and this executable printed some text rather than some. It cannot happen under normal circumstances where the echo executable behaves as one would expect from a command called echo.
If there is no executable file called echo in the PATH or executing it fails, then exec will display an error message and exit the shell. Even in that case, echo "test" is not executed.
¹  exec without a command argument is a different beast. It doesn't replace the shell process, it just applies redirections.
²  In a subshell, only the subshell is affected, the parent shell keeps running normally.

A: exec does always finish the script if it executes a command and does so successfully (not related to the command's exit code but to starting it).
exec can be run without a command in a very useful way: To permanently redirect file descriptors:
exec 3>/path/to/file

If the command cannot be started then the shell behaviour depends on the configuration. bash exits by default.
It may be best for you to use a function instead:
safe_exec () {
    cmd="$1"
    if test -z "$cmd" || ! test -f "$cmd" || ! test -x "$cmd"; then
        exit 1
    else
        exec "$@"
    fi
}

safe_exec echo "some "; echo "test"


text:
Q: How to select the matching template in Excel My data is as follows:

I need to find the index of the matching template. Now I am using the complicate finction:
=IF(COUNTIF(A2,D$2)>0,1,IF(COUNTIF(A2,D$3)>0,2,IF(COUNTIF(A2,D$4)>0,3,0)))
Is there any better way?
I know that I probably could just determine UDF with VBA which would iterate through the templates range but I would avoid it.
I can find the best cell based on the template with MATCH().

But I need the opposite direction.
And I know that I could probably use Fuzzy Lookup. But I would again avoid it.

A: Since we are numbering according to the values we are looking for in the cell, I could not see a solution other than the if command. Because we are looking for more than one template and moving forward.
It's not the solution you want, but it might be a different alternative.
=IF(IFERROR(FIND($D$2,A2),0)>0,1,IF(IFERROR(FIND($D$3,A2),0)>0,2," "))


text:
Q: Pentaho - Skip 2 lines in CSV file before header I have a CSV file in the following structure :
*name of the file*
*date & location*
header1   header2    header3
data1,    data2,     data3

I have a csv input step which reads the contents of the file. How can I skip the first two files in the file to read the header from line 3? The CSV input step doesn't seem to have an option for this.
Any help is appreciated!

A: May be this solution could help someone else. To skip the rows from csv file you have to read the file using "Text file input" step and consider all your columns as one,
use a separator which is not avaiable in your data and then fileds will not split. Then assign row numbers using "Add Sequence" step. after that you can use "Filter" step to skip the starting rows. Once you have removed top rows then split the fields using "Split fileds" step and give column names.this image contains transformation snap


text:
Q: I4GL to .NET — trying to understand decimal and int Coming from .NET, I'm trying to understand the following.
DEFINE total_real DECIMAL(12,5)
DEFINE total_dec  DECIMAL(6,5)
DEFINE total_int  SMALLINT

LET total_real = (total_real / 50)
LET total_int = total_real
LET total_dec = total_real - total_int

What is the purpose of total_real - total_int?
I tried to do some similar with C# but can't do it without first converting total_int to double/decimal. Is this just converting a decimal to int?

A: You should read the manual on the 4GL!
It appears that the code is taking a "real number", dividing it by 50, and then getting the 'whole number' and 'decimal fraction' parts.

A: The code is written dangerously, but as Richard Scheider surmised in his answer, the intent is to get the integer and fractional parts of the number.
The problem is that SMALLINT is a 16-bit quantity with a range of ±32,767 (-32,768 is reserved to represent NULL).  And a DECIMAL(12,5) can accept values up to 9,999,999.99999 in magnitude.  And that number divided by 50 is a lot bigger than the range of values that fits in a SMALLINT.
Doing the job in 'all decimal', you might use:
DEFINE total_real DECIMAL(12,5)
DEFINE total_dec  DECIMAL(6,5)
DEFINE total_frac DECIMAL(6,0)

LET total_real = (total_real / 50)
LET total_int  = TRUNC(total_real)
LET total_frac = total_real - total_int

Alternatively, simply change SMALLINT to INTEGER.  INTEGER is a 32-bit signed quantity.


text:
Q: Micronaut's HttpClient: connection pool, connection-pool-idle-timeout and connect-ttl: how do they work in conjunction? I'm in doubt about the settings below:

*

*micronaut.http.client.connect-ttl

*micronaut.http.client.connection-pool-idle-timeout

I would like to understand:

*

*What is the purpose of the settings below?

*How do they differ?

*How do they work together?

*Are these settings useful if the pool is DISABLED (micronaut.http.client.pool.enabled = false)?

The micronaut documentation is not clear to me.


text:
Q: iOS Facebook Auth URL-Scheme I'm having a strange problem...
based on the example "Hackbook" provided by Facebook to demonstrate the proper use of the Facebook iOS SDK, I'm trying to implement the same thing in my app.
The wired thing is: Jumping back to my app works only when using Safari to authenticate.
When I use the Facebook app, it doesn't jump back to my App, but curiously to the still existent "Hackbook" app on my iPhone.
Authenticating via Safari works just fine on both device and simulator.
Any ideas?

A: Are you using your own App ID in your app's plist for the FacebookID property and the URL scheme?
If both apps register the same URL (both have the same app ID and are installed on the same device at once), it may just be a coincidence that one returns back to the other app in one instance and your app in another instance.


text:
Q: presenting same image in all orientations in fullscreen I was just wondering how can I set up a gallery in landscape and portrait mode, and show the images as normal in both modes (not stretched or squashed). The only way I can think of is having the same image in both sizes so it can be shown the one that suits the orientation. This idea appears "dumb" to me so if someone knows a better way to set an image view in all orientations please give me some advices

A: Landscape and portrait are different aspect ratios.  If you don't want to stretch or squash the images, you can either crop the image or letterbox it.
Cropping is where you don't show the entire image, for instance an image that covers the entire screen in portrait would have the top and bottom removed.
Letterboxing is where the entire image is shown, but with a solid colour surrounding the image.  For instance, a landscape image shown in portrait would have black areas above and below the image.
It's relatively easy to do the above on the iPhone by selecting the correct content mode options in Interface Builder.
You can also supply different images as you describe, but that would just mean that you'd be cropping or letter boxing manually.

A: You should look at the contentMode property of your image view (or any UIView subclass, for that matter). Set it to UIViewContentModeScaleAspectFit, which will size the content of the image view to fill as much of it as possible without distorting the aspect ratio or clipping anything. In this case, just set the image view to be as large as possible, and the content mode will handle the rest.


text:
Q: Splitting child node from XML file into their own XML files I have an XML file (on the left) and I want to create multiple files (on the right):
<ParentNode>                                  file1:
    <ChildNode>                               <ParentNode>
        <node></node>                             <ChildNode>
    </childNode>                                      <node></node>
    <ChildNode>                                   </childNode>
        <node></node>                         </ParentNode>
    </childNode>                              file2:
    <ChildNode>                               <ParentNode>
        <node></node>                             <ChildNode>
    </childNode>                                      <node></node>
</ParentNode>                                      </childNode>
                                              </ParentNode>

I am trying to take the first child node from the original XML file and add it to a new one but I keep getting errors around replacing nodes.
I want to do something like the following
 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
 Document newDocument;

 Node firstChild = document.getFirstChild();
 NodeList childNodes = firstChild.getChildNodes();

 Element parentNode;
 for (int i = 1; i < childNodes.getLength(); i++ ) {
     newDocument = docBuilder.newDocument();
     parentNode = newDocument.createElement("ParentNode");
     newDocument.appendChild(parentNode);
     newDocument.getFirstChild().appendChild(childNodes.item(i));
 }

but I get an error
org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.

any help pointing in the right direction appreciated!

A: Nodes in the DOM have a concept of their owning document (hence your WRONG_DOCUMENT_ERR).
So you need to import the node from the original DOM to your new one. See Document.importNode()

A: From Java documentation,
Use cloneNode method.

SUMMARY:
public Node cloneNode(boolean deep)

Returns a duplicate of this node,
  i.e., serves as a generic copy
  constructor for nodes. The duplicate
  node has no parent; ( parentNode is
  null.).
Cloning an Element copies all
  attributes and their values, including
  those generated by the XML processor
  to represent defaulted attributes, but
  this method does not copy any text it
  contains unless it is a deep clone,
  since the text is contained in a child
  Text node. Cloning an Attribute
  directly, as opposed to be cloned as
  part of an Element cloning operation,
  returns a specified attribute (
  specified is true). Cloning any other
  type of node simply returns a copy of
  this node.
Note that cloning an immutable subtree
  results in a mutable copy, but the
  children of an EntityReference clone
  are readonly . In addition, clones of
  unspecified Attr nodes are specified.
  And, cloning Document, DocumentType,
  Entity, and Notation nodes is
  implementation dependent.

EDIT :
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class Test{
 static public void main(String[] arg) throws Exception{

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 Document doc = builder.parse("foo.xml");

 TransformerFactory tranFactory = TransformerFactory.newInstance();
 Transformer aTransformer = tranFactory.newTransformer();

 NodeList list = doc.getFirstChild().getChildNodes();

 for (int i=0; i<list.getLength(); i++){
    Node element = list.item(i).cloneNode(true);

 if(element.hasChildNodes()){
   Source src = new DOMSource(element);
   FileOutputStream fs=new FileOutputStream("k" + i + ".xml");
   Result dest = new StreamResult(fs);
   aTransformer.transform(src, dest);
   fs.close();
   }
   }

  }
}


text:
Q: Where have I made a mistake when using JS array as a function "repository"? I need to format numbers with custom number of decimal places. I use simple functions and I was trying to reuse already configured "formatting function".
Where do I have a mistake?
Edit: I've added full formatter setup, that uses http://numbrojs.com/ to format number in given language.
code:
const decimalPlacesDefaults = 2
const formatters: any = []

const createFormatter = (decimalPlaces = decimalPlacesDefaults) => {
    const formatter = numbro

    const language = formatter.languageData()
    language.delimiters = {
        decimal: ',',
        thousands: ' ',
    }

    formatter.registerLanguage(language, true)

    formatter.setDefaults({
        thousandSeparated: true,
        mantissa: decimalPlaces,
    })

    return formatter
}

const getFormatter = (decimalPlaces = decimalPlacesDefaults) => {
    // return createFormatter(decimalPlaces)   <-- when I uncomment this, everything works as expected
    const key = `f_${decimalPlaces}`

    if (formatters[key] === undefined) {
        formatters[key] = createFormatter(decimalPlaces)
    }

    return formatters[key]
}

const format = (value: string, decimalPlaces = decimalPlacesDefaultCount): string => {
    const formatter = getFormatter(decimalPlaces)

    return formatter(value).format()
}

test:
describe('format function to custom decimal places', () => {

    it('should reflect custom decimal places for all calculations', () => {
        expect(format('123', 3)).toMatch('123,000')
        expect(format('123', 1)).toMatch('123,0')
        expect(format('23.456', 2)).toMatch('23,46')  <-- fails here with '23,5' instead of '23,46'
        expect(format('11.24', 3)).toMatch('11,240')
        expect(format('456.78', 2)).toMatch('456,78')
    })

})


text:
Q: Understanding the affect of sample composition changes on mean over time I am working on a problem that is similar to the following.
Suppose I am interested in understanding what is causing the mean price of apples to change from month to month.
My dataset has a similar structure to the following:

Region
Apple Vendor
Apple Size
Date
Price

Region 1
Vendor A
Small
01-01-2022
1.00

Region 2
Vendor A
Small
01-01-2022
1.10

Region 2
Vendor B
Small
01-01-2022
1.50

Region 1
Vendor A
Small
02-02-2022
1.00

Region 3
Vendor C
Large
02-02-2022
2.00

...
...
...
...
...

Region 20
Vendor 40
Medium
12-12-2022
1.87

where the average monthly rate for an apple is:

Jan
Feb
Mar
...

1.11
1.21
1.15
...

While not strictly true for my real problem, if it is simpler we can assume that the price of an apple will always be the same if the Region, Vendor, and Size are the same. Also, assume that the number of samples and group proportions vary from month to month.
I want to understand how changes in my sample's mix of Region, Vendor, and Size affect the monthly mean rate of apples. For example, I would like to be able to say something like the average rate of apples increased in February mostly due to an increase in the proportion of Vendor D in our sample.
Looking for advice on the best way to approach this problem as I am really not sure what area I should even group this problem into.


text:
Q: Rest api, tokens? Is there anyone that can give me a really detailed guide how to get the access token and Access token secret?
i've found my Consumer key in my magento but after that i'm lost :(
Where can i find a step by step guide ? :)

A: You cannot find the token and token secret from Magento backend. You need to query these from the database directly.
First login to Magento backend and go to System->Web Services->REST - Oauth Consumers. Take a note of the oauth consumer you need the keys for. You can also find consumer_key and consumer_secret from there if you click on that consumer's row. However it's easy to find the keys from DB also:
The consumers and secrets are stored in DB table oauth_consumer. Find the necessary user by column "name" from there and copy the columns "key" and "secret". These are "consumer_key" and "consumer_secret".
Take a note of entity_id in oauth_consumer table.
Then look at DB table oauth_token. Find a record by  consumer_id and copy columns "token" and "secret".
Now you have all the 4 keys that are necessary to make a fully authenticated Oauth request towards this Magento instance.


text:
Q: Array shuffle java i have to problems trying to shuffle the values of an array and returning them. I have to ask the user if it wants to shuffle using a loop, if the users answers "y" then display the shuffle values if the answers is "n" then get out of the loop. I would appreciate any help.
Here is what i have so far.
Main class
package lab4b;

import java.util.Scanner;

public class Lab4B
{

    public static void main(String[] args)
    {
        final int size = 15;
        char q = 'y';
        boolean flag = false;

        Shuffler myShuffler = new Shuffler(size);

        myShuffler.display();
        System.out.println();

        Scanner input = new Scanner(System.in);
        System.out.printf("Do you wish to shuffle this numbers? ");
        String input2 = input.next();

        myShuffler.shuffle();
        myShuffler.display();
        System.out.printf("Do you wish to shuffle this numbers? ");

        input.close();

    }
}

Shuffler class
package lab4b;

import java.util.Random;

public class Shuffler
{

    private int[] data;

    public Shuffler(int size)
    {
        data = new int[size];

        for (int i = 0; i < size; i++)
        {
            data[i] = i + 1;
        }

    }

    public void shuffle()
    {

        for (int i = 0; i < data.length; i++)
        {
            Random r = new Random(15);

            int second = r.nextInt(15) + 1;
            int temp = data[i];
            data[i] = data[second];
            data[second] = temp;
        }

    }

    public void display()
    {

        String values = "";

        for (int i = 0; i < data.length; i++)
        {
            if (i < 15)
            {
                values += (i + 1);
                if (i < 14)
                {
                    values += ", ";
                }
            }
        }
        System.out.printf("Array Contents: %s \n", values);

    }
}

A: I don't know why you would code the Shuffle logic yourself.  Java Collections has a built-in Shuffle:  http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#shuffle(java.util.List).  There is one that takes a Random too:  http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#shuffle(java.util.List, java.util.Random)
Turn your Array into a List, let Collections shuffle it, turn the list back to an array.

A: Here's a part that might fail:
for (int i = 0; i < data.length; i++)
{
  Random r = new Random(15);

  int second = r.nextInt(15) + 1;
  int temp = data[i];
  data[i] = data[second];
  data[second] = temp;
}

You're creating a second index in the range [1,15] but what if the data array is smaller or bigger? If smaller you'd get an IndexOutOfBoundsException if bigger, you'd always swap the current element with those at indices 1 to 15.
In that part you're listing the indices instead of the values and only up to 15 of them:
if (i < 15) //what if data was bigger than 15 elements?
{
  values += (i + 1); //you might want to use data[i] instead of (1 + 1) here.
  if (i < 14)
  {
    values += ", ";
  }
}


text:
Q: GPGME Passphrase prompt issue (Ruby) In the example below, I have tried password and passphrase. Neither seem to allow me to run my code without a openpgp box prompting for the passphrase, the following message:
Pinentry Mac
"Please enter the passphrase to unlock the secret key for the OpenPGP certificate"
What do I need to change to allow my code to run without the prompt? I know my password is correct in the code.
I have tried :
ctx = GPGME::Ctx.new :password=> 'password'

and this:
ctx = GPGME::Ctx.new :passphrase_callback => method(:passfunc)

But both do not seem to work. Any advice is appreciated.
  def self.passfunc(obj, uid_hint, passphrase_info, prev_was_bad, fd)
    io = IO.for_fd(fd, 'w')
    io.puts 'password'
    io.flush
  end

  def self.decrypt_file(local_file, decrypted_file = nil)
    # Set decrypted file path if one is not provided
    decrypted_file = local_file.chomp(File.extname(local_file)) + ".csv" if decrypted_file == nil
    encrypted_data = GPGME::Data.new(File.open(local_file))

    # Set the password and GPG Key to decryption
    ctx = GPGME::Ctx.new :password=> 'password'

    # I have tried the passphrase call back
    #ctx = GPGME::Ctx.new :passphrase_callback => method(:passfunc)

    #KEY= GPGME::Data.new(File.open("key.gpg"))
    ctx.import_keys Rebal::Config::KEY

    # Decrypt the data
    decrypted = ctx.decrypt encrypted_data
    decrypted.seek(0)

    #Write the data to a file
    File.write(decrypted_file, decrypted.read)

    #return path
    decrypted_file
  end

The following link did not seem to help...
Using passphrase callback in ruby gpgme
and I'm not sure what this link is referring to or how it addresses my specific issue, but it might be the soltuion...
how to bypass pinentry (passphrase screen) while decrypting a file using gpgme  If someone can explain to me what changes to my code would help, I'm listening.
SOLUTION: I found out that the pinentry prompt is because of GPG2 vs GPG1.4. I downgraded to GPG1.4 and now it seems to work.
If someone knows how to get GPG2 to work, please comment
thank you

A: Providing pinentry_mode: GPGME::PINENTRY_MODE_LOOPBACK option worked for me on GPG2:
GPGME::Ctx.new(
  pinentry_mode: GPGME::PINENTRY_MODE_LOOPBACK,
  passphrase_callback: method(:passfunc)
)


text:
Q: Как в CSS сделать выделение текста цветом? Как в CSS сделать выделение текста цветом? Цвет выделения может быть в RGBA-формате, т.е. с прозрачностью.

Имеется ввиду не выделение курсором. А изначально текста выделен.

A:

div {
  color: #fff;
  max-width: 400px;
  text-align: center;
}
div > span {
  padding: 3px 0;
  line-height: 1.45;
  background: rgba(20,172,211,.5);
  box-shadow: 10px 0 rgba(20,172,211,.5), -10px 0 rgba(20,172,211,.5);
}

Как в CSS сделать выделение текста цветом? Цвет выделения может быть в RGBA-формате, т.е. с прозрачностью.


text:
Q: How can I now the rules of a built machine learning model? How can I now the rules of a built machine learning model?
I mean when I create a machine learning (ex. KNN, SVM) using python, how can I know how the data is divided into the classes and based on what any data point is decided to belong into a class?


text:
Q: Linker error: fatal error LNK1120: 1 unresolved externals It shows " Linker error: fatal error LNK1120: 1 unresolved externals "
Whole project = header file, 1st .cpp file and 2nd .cpp file with main() function.
Any1 has idea what ive done wrong?
//golf.h for golf.cpp
const int Len = 40;
struct golf{
    char fullname[Len];
    int handicap;
};
//dla gotowych wartosci
void setgolf (golf & g, const char * name, int hc);
//do wpisywania wartosci
int setgolf (golf & g);
//tylko handicap
inline void handicap (golf & g, int hc);
//wyswietla info o graczu
void showgolf (const golf & g) ;

NEXT FILE
//golf.cpp for 9-1.cpp
#include <iostream>
#include <cstring>
#include "golf.h"
extern const int Len;
void setgolf (golf & g, const char* name, int hc){
    strcpy(g.fullname,name);
    g.handicap=hc;
}
int setgolf (golf & g){
    using namespace std;
    cout << "Podaj fullname golfiarza" << endl;
    if (cin.getline(g.fullname,Len)) return 0;
    cout << "Teraz podaj jego handicap" << endl;
    cin >> g.handicap;
    return 1;
}
inline void handicap (golf & g, int hc){
    g.handicap=hc;
}
void showgolf (const golf & g){
    using std::cout;
    using std::endl;
    cout << "Fullname gracza to: " << g.fullname << endl;
    cout << "Jego handicap to: " << g.handicap << endl;
}

LAST FILE
#include <iostream>
#include <cstdlib>
#include "golf.h"
using namespace std;
int main(){
    cout << "Witaj!\nTutaj program golficzny!" << endl;
    golf filip;
    golf klaudia;
    cout << "Automatyczne uzupelnienie Filipa" << endl;
    setgolf(filip, "Filip Bartuzi",100);
    showgolf(filip);
    cout << "Manualne uzupelnienie Klaudii" << endl;
    ((setgolf(klaudia))==1) ? showgolf(klaudia) : cout << "nie wprowadziles gracza!" << endl; ;
    cout << "Zly handicap? Okey, zmienie handicap Filipowi" << endl;
    handicap(filip,50);
    showgolf(filip);
    cout << "Od razu lepiej, nieprawda?" << endl;
    system("PAUSE");
    return 0;
}

Any idea?

A: inline void handicap (golf & g, int hc){
    g.handicap=hc;
}

Try removing the inline keyword if the function is in golf.cpp file.
Alternatively, relocate the entire function in the golf.h file. (Here, this choice seems more appropriate.)
Reason: If a function is to be inline, then its body must be visible to the callers. That is possible only if the function body is placed in the header file, not the implementation file.
Possibly relevant: C++ inline member function in .cpp file

A: Remove the inline word. It's meant to provide both a declaration and a definition of the function at the same place (which make the compiler possibly replace every call to the function by its code).
In your code, you use the inline keyword, but provide the code somewhere else.
It should look like this :
inline void handicap (golf & g, int hc){   g.handicap=hc; }
directly in your .h file. (And the definition can be removed from the golf.cpp file)


text:
Q: Image cannot upload on server in android i am getting image from gallery and put into server by php, all is done but image cannot save on server Please help me
   public int uploadFile (String sourceFileUri) {

        String fileName = sourceFileUri;
       String upLoadServerUri="http://thinksl.com/taughtable/update.php";
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);
        int serverResponseCode = 0;
        StrictMode.ThreadPolicy th= new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(th);

        if (!sourceFile.isFile()) {

             Log.e("uploadFile", "Source File not exist :"
                                 );

             runOnUiThread(new Runnable() {
                 public void run() {

        }
             });

             return 0;

        }
        else
        {
             try {

                   // open a URL connection to the Servlet
                 FileInputStream fileInputStream = new FileInputStream(sourceFile);
                 URL url = new URL(upLoadServerUri);
                //String uploaded_file="image";
                 // Open a HTTP  connection to  the URL
                 conn = (HttpURLConnection) url.openConnection();
                 conn.setDoInput(true); // Allow Inputs
                 conn.setDoOutput(true); // Allow Outputs
                 conn.setUseCaches(false); // Don't use a Cached Copy
                 conn.setRequestMethod("POST");
                 conn.setRequestProperty("Connection", "Keep-Alive");
                 conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                 conn.setRequestProperty("uploaded_file", fileName);

                 dos = new DataOutputStream(conn.getOutputStream());

                 dos.writeBytes(twoHyphens + boundary + lineEnd);
                 dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                         + fileName + "\"" + lineEnd);
                 dos.writeBytes(lineEnd);

                 // create a buffer of  maximum size
                 bytesAvailable = fileInputStream.available();

                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 buffer = new byte[bufferSize];

                 // read file and write it into form...
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                 while (bytesRead > 0) {

                   dos.write(buffer, 0, bufferSize);
                   bytesAvailable = fileInputStream.available();
                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                  }

                 // send multipart form data necesssary after file data...
                 dos.writeBytes(lineEnd);
                 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                 // Responses from the server (code and message)
                 serverResponseCode = conn.getResponseCode();
                 String serverResponseMessage = conn.getResponseMessage();

                 Log.e("uploadFile", "HTTP Response is : "
                         + serverResponseMessage + ": " + serverResponseCode);

                 if(serverResponseCode == 200){

                     runOnUiThread(new Runnable() {
                          public void run() {

                              String msg = "File Upload Completed.\n\n See uploaded file here"
                                           ;

                              Toast.makeText(Edit_Profile.this, "File Upload Complete.",
                                           Toast.LENGTH_SHORT).show();
                          }
                      });
                 }

                 //close the streams //
                 fileInputStream.close();
                 dos.flush();
                 dos.close();

            } catch (MalformedURLException ex) {

                ex.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {

                        Toast.makeText(Edit_Profile.this, "MalformedURLException",
                                                            Toast.LENGTH_SHORT).show();
                    }
                });

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(Edit_Profile.this, "Got Exception : see logcat ",
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception", "Exception : "
                                                 + e.getMessage(), e);
            }
            return serverResponseCode;

         }

       }

Php file
   $target = "uploads/";
   $target1 =$target . date(U).( $_FILES['image']['name']);
   $path="http://thinksl.com/taughtable/uploads/";
   $image=$path . date(U).( $_FILES['image']['name']);
   move_uploaded_file($_FILES['image']['tmp_name'], $target1);

A: Here is method I have used for uploading image to server.
/**
 * Upload Image to server
 *
 * @param file              image to be saved
 * @param compressorQuality quality of image
 * @return path of uploaded image in server
 */
private String uploadImage(Bitmap file, int compressorQuality) {
    String final_upload_filename = "demo_image.png";
    String response = null;
    HttpURLConnection conn = null;
    try {
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------14737809831466499882746641449";
        URL url = new URL("image_upload_url");
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", final_upload_filename);
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"" + final_upload_filename + "\"" + lineEnd);
        dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
        dos.writeBytes(lineEnd);
        file.compress(CompressFormat.PNG, compressorQuality, dos);
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush();
        dos.close();
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bytesRead;
        byte[] bytes = new byte[1024];
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();
        is.close();
        response = new String(bytesReceived);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response;
}

You can use this method like:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
String server_response = uploadImage(bitmap, 100);

I hope it helps!


text:
Q: How to assign result of NSURLSession to a variable in same method? To say I'm new to Objective-C would be a huge understatement. I'm primarily a Ruby/Rails developer and it completely spoiled me when it comes to OOP & programming in general.
After getting tired of reading tutorials, I decided to try to use NSRULSession to hit one of my Rails apps (an Elder Scrolls Online skill planner) & display some of the JSON response on my iOS app. Delegates make no sense, I'm not sure how to break this functionality up into methods, etc, so I thought I'd keep it simple & do it all in the viewDidLoad() method (yes, I know it's bad practice).
- (void)viewDidLoad {
    [super viewDidLoad];

    __block NSDictionary *skillData; // No clue what __block is

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://www.esomix.com/skill_builds/17.json"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@", json[@"name"]);
        skillData = json;
    }];

    [dataTask resume];

    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
    myLabel.textColor = [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1];
    [self.view addSubview:myLabel];

    NSLog(@"%@", skillData[@"name"]);
    NSLog(@"bottom of method");
}

After lots of toying around, I figured out that despite the NSURLSession code before my NSLogs at the bottom, it returns its data after they're rendered. No wonder my label.text (not shown) wasn't getting set! Here's the order of my three NSLogs:
(null)
bottom of method
Single-Target Lockdown Sniper

I guess my question is what's the simplest, proper way to make an JSON API request and use the data to generate a UI element/other tasks after the data has returned. Thanks so much!

A: A couple of clarifying points:

*

*You ask

what's the simplest, proper way to make an JSON API request and use the data to generate a UI element/other tasks after the data has returned

In short, use the JSON response inside the completion block, not after it, for example:
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://www.esomix.com/skill_builds/17.json"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSDictionary *skillData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        // use `skillData` here

        // finally, any UI/model updates should happen on main queue

        dispatch_async(dispatch_get_main_queue(), ^{
            UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
            myLabel.textColor = [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1];
            myLabel.text = skillData[@"name"]; // or whatever you wanted from `skillData`
            [self.view addSubview:myLabel];
        });
    }];

    [dataTask resume];

    // don't try to use `skillData` here, as the above block runs asynchronously,
    // and thus `skillData` will not have been set yet
}

*The purpose of the __block qualifier is to let the block update a variable whose scope is outside the block. But, because the NSURLSessionDataTask runs asynchronously, there's no point in trying to reference skillData outside that block (because the viewDidLoad method will have completed well before the completionHandler for the NSURLSessionDataTask is invoked, as illustrated by your NSLog results).
So, since there's no point in referencing skillData outside the block, then there's no point in defining it with the __block qualifier outside of the block. Just make it a local variable inside the block. If you want to update your model (or perhaps some properties of the view controller), you can do that (but when dealing with class properties and ivars, no __block qualifier is needed).


text:
Q: How to move focus (scroll) to a specific row in ag grid react version I have a question regarding agrid react version.
ag grid version : 26.1.0
I'm developing a search for a specific keyword in a specific field like the link below. Actually, the project is a little more complicated, but I made the sample as simple as possible.
https://plnkr.co/edit/P3NoepCXxPJ9BpzK?preview
ex)
gridRef.current.api.forEachNode(function (node) {
  if (node.level === 0) {
    groupNode = node;
  }
  if (node.data) {
    if(node.data.year === 2012) {
      node.setSelected(true);
      groupNode.setExpanded(true);
    }

  }
});

When the Select All Athlete button is clicked, a specific keyword is searched and the corresponding row is selected.
It is a grouped grid, and if the row of the searched result is child, the corresponding group row is expanded.
If the data of the corresponding row is at the bottom of the grid, so you have to scroll down to see the focused row, is there a way to automatically scroll the defrost row so that the topmost row is displayed?
result i want


text:
Q: Interview questions This is an interview question:
Given: f(n) = O(n)
       g(n) = O(n²)
find f(n) + g(n) and f(n)⋅g(n)?

What would be the answer for this question?

A: When this answer was prepared, f(n) was shown as o(n) and g(n) as Θ(n²).
From f(n) = o(n) and g(n) = Θ(n²) you get a lower bound of  o(n²) for f(n) + g(n), but you don't get an upper bound on  f(n) + g(n) because no upper bound was given on f(n). [Note, in above, Θ is a big-θ, or big theta]
For f(n)·g(n), you get a lower bound of o(n³) because Θ(n²) implies lower and upper bounds of  o(n²) and O(n²) for g(n).  Again, no upper bound on  f(n)·g(n) is available, because f(n) can be arbitrarily large;  for f(n), we only have an o(n) lower bound.
With the question modified to give only upper bounds on f and g, as f(n) = O(n) and g(n) = O(n²), we have that f(n)+g(n) is O(n²) and f(n)·g(n) is O(n³).
To show this rigorously is a bit tedious, but is quite
straightforward.  Eg, for the f(n)·g(n) case, suppose that by the definitions of O(n) and O(n²) we are given C, X, K, Y such that n>X ⇒ C·n > f(n) and n>Y ⇒ K·n² > g(n).  Let J=C·K and Z=max(X,Y).  Then n>Z ⇒ J·n³ > f(n)·g(n) which proves that f(n)·g(n) is O(n³).

A: O(f(n) + g(n)) = O(max{f(n), g(n)})

so for first
f(n) + g(n) = O(max{n, n^2}) = O(n^2)

for
f(n) ⋅ g(n)

we  will have
O(f(n) ⋅ g(n)) = O(n ⋅ n^2) = O(n^3)

A: Think about it this way.
f(n) = c.n + d
g(n) = a.n^2 + b.n + p
Then,
f(n) + g(n) = a.n^2 + (lower powers of n)
And,
f(n).g(n) = x.n^3 + (lower powers of n)
It follows that O(f(n) + g(n)) = O(n^2)
and O(f(n).g(n)) = O(n^3)

A: This question can be understood like this :-

f(n)=O(n) means it takes O(n) time to compute f(n).

Similarly,

for g(n) which requires O(n^2) time

So,

P(n)=f(n)+g(n) would definitely take O(n)+O(n^2)+O(1)(for addition,
  once you know the value of both f and g)

. Hence, this new function
P(n) would require O(n^2) time.
Same is the case for

Q(n) =f(n)*g(n) which requires O(n^2) time

.


text:
Q: Reading XML file in FME? I want the below xml file to be read by fme.
I tried reading documents and seeing videos. This xml looks more complicated.
http://pastebin.com/pXmjwEqW
<InspectObjects>
<Object id="197589" action="update" objectType="pole" DataSetName="electric"     UniverseId="0" WorldId="0">
<Attributes>
<Attribute id="asset_id"></Attribute>
<Attribute id="id">197589</Attribute>
<Attribute id="location_description">A.T.L.</Attribute>
<Attribute id="npcl_ct">False</Attribute>

I have different objects in a single xml file. I want to filter based on "objectType".
How this can be done by using xml parsing in FME?

A: To extract the attributes you need the xmlflattener

"Flattens content of XML element(s) into feature attributes.
This transformer provides a quick and easy way to output any content
  or attributes of an XML element as feature attributes by specifying
  the element name or path. Optionally, the XML attributes from the
  ancestors of the specified elements can be fetched as FME attributes
  as well."

A good reference
https://knowledge.safe.com/articles/Samples_and_Demos/Reading-Complex-XML-or-GML-using-the-XMLFlattener

A: As mentioned in a previous answer, use the XMLFlattener.  In the the Expose Attributes parameter of the transformer, be sure to expose the "Object.objectType" attribute (you can rename the attribute with the AttributeRenamener if you like) You can then use filtering and testing transformers on this new attribute.
This looks like FieldSmart XML.  It is not clear what are you doing with the data.

A: Now FME has made it very easy to extract the XML (and Json) elements at the reader level. This is just an update since the question was asked in 2015 and the latest version of FME is 2018.

You could flatten your file here as well


text:
Q: ng-disabled is not working This might be a silly question. But I just started experimenting with AngularJS. Can someone point out what I'm doing wrong in validation. The button is not disabled even when the fields are invalid.
What's the difference between
 ng-disabled="myForm.$invalid" and
ng-disabled="myForm.cuisine.$invalid || myForm.title.$invalid || myForm.description.$invalid || myForm.cost.$invalid"

I think using myForm.$invalid is a cleaner way of disabling the button. Any tips?
<form name="myForm">

        <select ng-required="true" name="cuisine" ng-model="model.food.cuisine" class="form-control" type="text">
            <option ng-repeat="c in model.cuisines" value="{{c}}">{{c}}</option>
        </select>

            Please select cuisine type.

        <input ng-required="true" name="title" ng-minlength="4" ng-maxlength="25" ng-model="model.food.title"
               type="text" class="form-control">

Please pick a valid title with atleast 4
            characters.

            <textarea ng-required="true" name="description" ng-minlength="10" ng-maxlength="255"
                      ng-model="model.food.description" type="text" class="form-control"></textarea>

Please describe your food with 10 - 255
            characters.

        <input name="cost" ng-pattern="/0-9/" ng-required="true" min="1" ng-model="model.food.cost" type="number"
               class="form-control" placeholder="Cost">

Please enter a valid number

Please enter cost of food item.

        <button ng-disabled="myForm.$invalid" class="btn btn-success btn-block">Add Food</button>

</form>

A: Apparently, validations don't work if the form element is inside the body of a table.
It works fine if I moved the form tag outside the table.
Thanks everyone.


text:
Q: PHP MySQL how to transition database input from stripslashes to parameters I'm trying to update an old program that uses regular MySql queries, runs all the inputs through addslashes() prior to inserting them, and runs the retrieved data through stripslashes() before returning it.  I'm trying to update the program to run with Mysqli and use prepared statements, but I'm not sure how to make the transition with the existing data in the database.
My first thought was to write a function to test if slashes have been added, but the general consensus in the answers to similar questions I found was that this isn't doable.
I'm trying to avoid doing a mass update to the database, because it's an open source program and this seems likely to potentially cause problems for existing users when they try to upgrade.
If I continue to use addslashes() prior to inserting using MySqli and prepared statements would this work?  What would be the reasons for not doing it this way and instead going the full database upgrade route?
Edit:
Based on a comment that appears to be deleted now, I went and looked at the database directly. All I could find was an ' that had been converted to ' and no slashes.  When I pulled out the data it came out fine without running stripslashes().  So do the added slashes just tell mysql to escape the data when it's inserted?  Will all the data come out find if I remove the stripslashes()?  If so what's the point of stripslashes()?

A: You have several questions:

If I continue to use addslashes() prior to inserting using mysqli_ and prepared statements would this work?

No, it would not: the added backslashes would then be stored in your database, which is not what you want. In prepared statements the provided arguments are taken literally as you pass them, as in that mechanism there is no more need to escape quotes.

What would be the reasons for not doing it this way and instead going the full database upgrade route?

See above.

So do the added slashes just tell MySql to escape the data when it's inserted?

The added slashes are interpreted when you embed a string literal in your SQL, as that necessarily is wrapped in quotes. For example:
$text = "My friend's wedding";

$sql = "INSERT INTO mytable VALUES ('$text')";
$result = mysqli_query($con, $sql);

The mysqli_query will fail, as the SQL statement that is passed to it looks like this:
INSERT INTO mytable VALUES ('My friend's wedding')

This is not valid SQL, as the middle quote ends the string literal, and so the s that follows is not considered part of the string any more. As the SQL engine does not understand the s (nor wedding and the dangling quote after it), it produces a syntax error. You can even see something is wrong in the way the syntax is highlighted in the above line.
So that is where addslashes() is (somewhat) useful:
$text = "My friend's wedding";
$text = addslashes($text);
$sql = "INSERT INTO mytable VALUES ('$text')";
$result = mysqli_query($con, $sql);

This will work because now the SQL statement sent to MySql looks like this:
INSERT INTO mytable VALUES ('My friend\'s wedding')

The backslash tells MySql that the quote that follows it has to be taken as a literal one, and not as the end of the string. MySql will not store the backslash itself, because it is only there to escape the quote (see list of escape sequences in the documentation).
So in your table you will get this content inserted:

My friend's wedding

Then:

Will all the data come out fine if I remove the stripslashes()?

Yes. In fact, it should never have been in your code in the first place, as it will negatively effect what you get when there truly are (intended!) backslashes in your data. You are maybe lucky that a backslash is a rare character in normal text. Apparently you have not found any backslash in your database data, so it probably did not badly affect you until now. It is an error to think that the addslashes() call during the saving of data had to be countered with a stripslashes() call while reading the data, because, again, MySql had already removed them while writing the data into the database.

If so what's the point of stripslashes()?

There is no point in the context of what you are doing. It only is useful if you have received somehow a string in which there are characters that have a backslash before them, and have the meaning to escape the next character when the string is used in some context. But since you only briefly have such strings (after calling addslashes()) and MySql interprets these escapes by removing the backslashes in the written data, you never again see that string with the additional backslashes.
Situations where you would need stripslashes() are very rare and very specific. For your scenario you don't need it.


text:
Q: how to get address information when I click on a location icon I have a set location code in my app. I want to get address information when I click on a location icon. How to use a click event
public class MyActivity extends MapActivity implements LocationListener
{

MapView mapView;
MapController mc;
private MyLocationOverlay myLocOverlay;
private String provider;
private LocationManager lm;
Drawable location = null;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.location);

    mapView = (MapView) findViewById(R.id.mview);
    mc = mapView.getController();
    mapView.setBuiltInZoomControls(true);
    mc.setZoom(15);

    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = lm.getBestProvider(criteria, false);

    Location location = lm.getLastKnownLocation(provider);

    if(location != null){
        onLocationChanged(location);
    }
}

@Override
protected void onResume(){
    super.onResume();
    lm.requestLocationUpdates(provider, 400, 1, this);
    myLocOverlay = new MyLocationOverlay(location.this, mapView);
    myLocOverlay.enableMyLocation();
    mapView.getOverlays().add(myLocOverlay);
    myLocOverlay.runOnFirstFix(new Runnable() {

        @Override
        public void run() {
            mc.animateTo(myLocOverlay.getMyLocation());

        }
    });

     mapView.postInvalidate();
}

@Override
protected void onPause() {
    super.onPause();
    lm.removeUpdates(this);
    myLocOverlay.disableMyLocation();
}

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}
@Override
public void onLocationChanged(Location location) {

    double lat = location.getLatitude();
    double lng = location.getLongitude();

}
@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}
@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

 }


text:
Q: JSHint and angular-mocks error When i run JSHint over my Jasmine tests using angular-mocks, i get errors for the "module" or "inject" function. How can I fix this? I know i can define those methods as globals in the .jshintrc, but is this the elegant way to solve this?
'module' is not defined
'inject' is not defined

A: As you can see here:
https://github.com/angular/angular-seed/blob/master/.jshintrc
The angular seed project follows that practice. So it seems to be quite accepted.
I suggest you to copy the linked jshintrc.
The file's content if the link would change:
{
  "globalstrict": true,
  "globals": {
    "angular": false,
    "describe": false,
    "it": false,
    "expect": false,
    "beforeEach": false,
    "afterEach": false,
    "module": false,
    "inject": false
  }
}


text:
Q: CSS vertical align inside a FIXED position div I have a header: FIXED position.
Here is css:
#header{
    position:fixed;
    height: 6em;
    display:block;
    width: 100%;
    background: rgba(255, 255, 255, 1);
    z-index:9;
    text-align:center;
    color: #000000;
}

And inside, I want to center text middle and vertical middle.
Here is what I have so far, but it's not working. All example online shows with an absolute position as the container, but it's not working with the fixed one.
HTML:

Bewolf Photography

Bewolf Photography

CSS for text and image:
#bandname
{
   display: inline-block;
   font-size: 2.8em;
   padding: 0px 0px 0 0;
   vertical-align: middle;
   background: rgba(0, 255, 0, 1);
}

#insta {
 display: inline-block;
 padding: 0px 0px 0px 50px;
 vertical-align: middle;
}

I just can't figure that one out...
I tried using
   line-height:  6em;

Help would be appreciated.. .thanks
but that doesn't work either.

A: The easiest solution is to have the following css for it's content.
#header .wrapper
{
   position: relative;
   top: 50%;
   transform: translateY(-50%);
}

Since there are multiple children, it's better to wrap them around a wrapper div. Here's the working example:
http://jsfiddle.net/zf987w0b/1/

A: You can use the properties left, right, top and bottom, set em to 50% for example, and them use the transform property to translate the element -50% of itself to perfectly center it. Sounds confuse but i made a fiddle: http://jsfiddle.net/zzztfkwu/ Will this work?
EDIT: http://jsfiddle.net/kbh97n82/1 updated fiddle with .wrapper solution.

A: Use the pseudo element vertical centre trick.
#header:before brings the inline elements down to the centre. The direct children of header are given display: inline-block and vertical-align: middle to keep a straight line.
Read more about pseudo elements here.
This technique basically adds a "div" before the rest of your content. (It can be replaced with a real
 if you really need this to work in IE7 and below. [Don't bother!] ). It basically looks like this:

I am :before and you will all do as I say! To the middle, plebs!

Yes master!

Anything you say sir!

Working Example
Note: I removed the div from around the image. It seems unnecessary, but can be placed back in if needs must. Also, I have targeted only the direct children of #header using the direct children selector: >. Here is a huge list of CSS selectors.

#header {
  position: fixed;
  height: 6em;
  display: block;
  width: 100%;
  background: rgb(0, 255, 255);
  /* Fall-back for browsers that don't support rgba  */
  background: rgba(0, 255, 255, 1);
  z-index: 9;
  text-align: center;
  color: #000000;
  top: 0px;
}
#header:before {
  content: '';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}
#header > div,
#header > img {
  display: inline-block;
  font-size: 2.8em;
  padding: 0px 0px 0 0;
  vertical-align: middle;
}

Test

test


text:
Q: Different request status in Curl and Golang (200 and 403) i have a problem getting data from website (https://avito.ru) using standard golang http library on local MacBook Air - im getting status 403 Forbidden. There is no problem on opening that site from browser (with disabled JavaScript), and there is no problem on getting data using standard Curl function (curl -v https://www.avito.ru/moscow) - getting status 200 all the time.
There is a Golang code:
package main

import (
    "crypto/tls"
    "crypto/x509"
    "flag"
    "fmt"
    "io/ioutil"
    "net/http/httputil"
    "time"
    "database/sql"
    "log"
    "net/http"

    "golang.org/x/net/http2"
    "github.com/PuerkitoBio/goquery"
)

func main() {

    request, err := http.NewRequest("GET", "https://www.avito.ru/moscow", nil)
    if err != nil {
        log.Fatal(err)
    }
    request.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36")
    request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    request.Header.Add("Accept-Language", "en-us")
    request.Header.Add("Connection", "keep-alive")
    request.Header.Add("Host", "www.avito.ru")
    fmt.Println(request.Header)

    // Do something with the request
    client := &http.Client{}
    caCert, err := ioutil.ReadFile("/etc/ssl/cert.pem")
    if err != nil {
        log.Fatalf("Reading server certificate: %s", err)
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    var httpVersion = flag.Int("version", 2, "HTTP version")

    fmt.Println(string(*httpVersion))
    client.Transport = &http2.Transport{
        TLSClientConfig: &tls.Config{
            RootCAs:            caCertPool,
            // InsecureSkipVerify: true,
        },
    }

    requestDump, err := httputil.DumpRequest(request, true)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(string(requestDump))

    response, err := client.Do(request)
    fmt.Println(string(response.Proto))

    if err != nil {
        log.Fatal(err)
    }

    defer response.Body.Close()

    fmt.Println(response.Status)

    doc, err := goquery.NewDocumentFromReader(response.Body)
    if err != nil {
        fmt.Println("here2")
        log.Fatal(err)
    }
    pageTitle := doc.Find("title").Contents().Text()

    fmt.Println(pageTitle)
}

There is prints:

GET / HTTP/1.1
Host: www.avito.ru
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Connection: keep-alive
Accept-Encoding: gzip

HTTP/2.0
map[Content-Type:[text/html; charset=utf-8] Date:[Sat, 14 Nov 2020 13:14:10 GMT] Server:[nginx] X-Content-Type-Options:[nosniff] X-Envoy-Upstream-Service-Time:[14] X-Xss-Protection:[1; mode=block]]
403 Forbidden
here3
Доступ с вашего IP-адреса временно ограничен — Авито
here4
Доступ с вашего IP-адреса временно ограничен — Авито

There is prints of Curl -v:

Alexanders-MacBook-Air:~ alexchistyakov$ curl -v https://www.avito.ru/moscow
*   Trying 185.89.12.132...
* TCP_NODELAY set
* Connected to www.avito.ru (185.89.12.132) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: C=RU; ST=Moscow; L=Moscow; O=Limited Liability Company KEH eCommerce; CN=*.avito.ru
*  start date: Feb  4 09:48:54 2019 GMT
*  expire date: Feb  4 09:48:54 2021 GMT
*  subjectAltName: host "www.avito.ru" matched cert's "*.avito.ru"
*  issuer: C=BE; O=GlobalSign nv-sa; CN=GlobalSign Organization Validation CA - SHA256 - G2
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x7f7feb00ba00)
> GET /moscow HTTP/2
> Host: www.avito.ru
> User-Agent: curl/7.64.1
> Accept: */*
>
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
< HTTP/2 200
< server: nginx
< date: Sat, 14 Nov 2020 13:28:28 GMT
< content-type: text/html; charset=UTF-8
< set-cookie: u=2ke25u1o.n9oms3.9cgwbvpc4sw0; path=/; expires=Tue, 10-Nov-37 13:28:28 GMT; HttpOnly; Max-Age=536112000; secure; domain=.avito.ru
< set-cookie: v=1605360508; path=/; expires=Sat, 14-Nov-20 13:58:28 GMT; HttpOnly; Max-Age=1800; secure; domain=.avito.ru; SameSite=Lax
< cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< set-cookie: buyer_location_id=621540; expires=Sun, 14-Nov-2021 13:28:28 GMT; Max-Age=31536000; path=/; domain=.avito.ru; secure; HttpOnly; SameSite=Lax
< set-cookie: luri=rossiya; expires=Sun, 15-Nov-2020 13:28:28 GMT; Max-Age=86400; path=/; domain=.avito.ru; secure; HttpOnly; SameSite=Lax
< set-cookie: buyer_selected_search_radius4=0_general; expires=Thu, 18-Mar-3019 13:28:28 GMT; Max-Age=31504464000; path=/; domain=.avito.ru; secure; SameSite=Lax
< set-cookie: tmpBannerHash=; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; secure; HttpOnly; SameSite=Lax
< set-cookie: tmpSideBlockHash=; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; secure; HttpOnly; SameSite=Lax
< set-cookie: tmpSearchBottomHash=; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; secure; HttpOnly; SameSite=Lax
< set-cookie: sx=H4sIAAAAAAACAw3EwQqAIAwA0H%2FZucOiJcu%2FyYiRA4UWDhL%2Fvd7hdVjSu0tpT0lVSQ5CY%2FJ%2Fh9ihQYQr31osaMskfpCIV0UUFkOuajDBCXEOuBKFDXmMD9eve2RUAAAA; expires=Sat, 21-Nov-2020 13:28:28 GMT; Max-Age=604800; path=/; domain=.avito.ru; secure; HttpOnly; SameSite=Lax
< set-cookie: so=1605360508; expires=Sat, 14-Nov-2020 13:43:28 GMT; Max-Age=900; path=/; domain=.avito.ru; secure; HttpOnly; SameSite=Lax
< set-cookie: dfp_group=52; expires=Sat, 14-Nov-2020 13:38:28 GMT; Max-Age=600; path=/; domain=.avito.ru; secure; HttpOnly; SameSite=Lax
< set-cookie: buyer_laas_tooltip=; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=.avito.ru; secure; HttpOnly; SameSite=Lax
< set-cookie: tmpSrcFromBp=ijrkns6kvj4gwc4ggwok00g8gs08oks; expires=Sat, 14-Nov-2020 14:28:28 GMT; Max-Age=3600; path=/; domain=.avito.ru; secure; HttpOnly; SameSite=Lax
< set-cookie: sessid=e33049edd828b91d73300175d802c306.1605360508; expires=Sun, 15-Nov-2020 13:28:28 GMT; Max-Age=86400; path=/; domain=.avito.ru; secure; HttpOnly; SameSite=Lax
< set-cookie: buyer_from_page=; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; secure; HttpOnly; SameSite=Lax
< x-request-url: /moscow
< x-envoy-upstream-service-time: 532
< x-xss-protection: 1; mode=block
< x-content-type-options: nosniff
<

<!DOCTYPE html>

<html> <head> <script>

What can i have to try for getting status 200 in Golang like Curl?
Thanks

A: Here is working example:
package main
import "net/http"

func main() {
   r, e := http.Head("https://www.avito.ru/moscow")
   if e != nil {
      panic(e)
   }
   println(r.StatusCode == 200)
}


text:
Q: ember.js "onReady" after layout change Is there a way to trap an onReady-style event in Ember.JS after the layout has finished changing and all new elements are in the DOM?   I have a datepicker that I'd like to use in my ember.js application that requires that you call

$('.datepicker').datepicker();

once all elements that want to use the datepicker are on screen.
In my app, I dynamically create input text elements after the initial render and so I can't just call this at the initial onReady have this executed against the new elements.
Is there a way to hook into this sort of event with Ember.js and call this at that time?

A: You need to override the didInsertElement event in your Ember.View ala

didInsertElement: function() {
    $('.datepicker').datepicker();
},


text:
Q: Jest Babel Error: Test suite failed to run Here's my package.json
{
    "name": "js-stack",
    "version": "1.0.0",
    "license": "MIT",
    "scripts": {
        "start": "babel-node src",
        "test": "eslint src && flow && jest --coverage"
    },
    "dependencies": {},
    "devDependencies": {
        "babel-cli": "^6.26.0",
        "babel-eslint": "^10.1.0",
        "babel-jest": "^26.0.1",
        "babel-preset-env": "^1.7.0",
        "babel-preset-flow": "^6.23.0",
        "babel-preset-react": "^6.24.1",
        "eslint": "^7.1.0",
        "eslint-config-airbnb": "^18.1.0",
        "eslint-plugin-compat": "^3.7.0",
        "eslint-plugin-flowtype": "^5.1.3",
        "eslint-plugin-import": "^2.20.1",
        "eslint-plugin-jsx-a11y": "^6.2.3",
        "eslint-plugin-react": "^7.19.0",
        "eslint-plugin-react-hooks": "^2.5.0 || ^1.7.0",
        "flow-bin": "^0.126.1",
        "jest": "^26.0.1",
        "react": "^16.13.1"
    },
    "browserslist": [
        "> 1%"
    ]
}

Here's my .babelrc file
{
    "presets": [
        "env",
        "react",
        "flow"
    ]
}

While it got me the error
Test suite failed to run

    Plugin/Preset files are not allowed to export objects, only functions.
In /Users/Codes/Javascript/js-stack/node_modules/babel-preset-react/lib/index.js

Could Someone tell me how to deal with it? I tried some solutions as they said but still get it! SO confused!!!! THX

A: Remember having a problem similar to this before. have you tried getting rid of the .babelrc with babel.config.js ? This is how the file will look like
/* eslint-disable func-names */
module.exports = function (api) {
  const presets = [
    '@babel/preset-env',
    '@babel/preset-react',
    '@babel/preset-flow'
  ];
  const plugins = [];

  api.cache(false);

  return {
    presets,
    plugins
  };
};


text:
Q: Best way to pass values from popup page to parent page I have a main page for customer in which i need to select location for the customer . to pick a location we have desined a popup page which has a grid which displays all locations . once user pics the loction that particular location should be returned back to the main page .
Location object contains feilds - LocId,LocName,LocState,LocCountry,PinCode  .
The entire location object should be returned to the main page not a single value .
My code for opening location is
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="../Content/Images/search.png" Height="21px" ToolTip="Search Location" Width="21px"
                        OnClientClick="ShowLocation();" />

function ShowLocation() {
    window.showModalDialog('../StandardLookups/Location.aspx', '_blank', 'dialogWidth:820px; dialogHeight:400px; dialogLeft:250px; dialogTop:250px;status:no; scroll:no; help:no; resizable:no,edge: Raised,doPostBackAfterCloseCallback: false,postBackElementId: null');

}

Code in popup window once the row is selected by the user
 protected void btnSelect_Click(object sender, EventArgs e)
    {
        List<object> locationValues = gvLocationLookup.GetSelectedFieldValues(new string[] { "LocId", "LocName", "LocState","LocCountry","PinCode" });

        var locationValue = (object[])locationValues[0];

        var location= new Location
        {
            LocId = (int?)locationValue[0],
            LocName = (string)locationValue[1],
            LocState = (string)locationValue[2]
            LocCountry = (string)locationValue[3]
            PinCode =   (string)locationValue[4]
        };
        Session["SELECTED_LOCATION"] = location;
        Response.Write("<script> window.opener.location.reload(false); window.close();</" + "script>");
        Response.End();
    }

Currently i use sessions values to move values . Is there any better approaches ?

A: You can check here what method suits to your needs.
http://msdn.microsoft.com/en-us/library/6c3yckfw%28v=vs.100%29.aspx

A: I've created a system like this before, using only client side code (javascript, no C#).
The requirement was that, when filling in a form, a specific value (e.g. a location) could be selected in a popup.
Once the value was clicked in the popup, the parent page receives this information through javascript, and the popup closes itself.
Note that the parent page must have the needed fields to be filled. In my case it is an autocomplete textbox (=FieldName) and a linked HiddenField (=FieldName_key), which holds the unique key to the text in the textbox.
function confirmSelection(code, key)
{
    try {
        window.opener.document.getElementById('<%= FieldName %>').value = code;
        window.opener.document.getElementById('<%= FieldName %>_key').value = key;
        window.close();
    }
    catch (e) {window.close();}
}

An additional benefit of this client-side script (opposed to the C# script) is that you don't have to reload the parent page, which can disturb your user in his/her work.


text:
Q: How do i check the RAM on my Ubuntu sever? I'm using an old laptop that originally had 512MB of RAM and installed Ubuntu Server 12.04 I upgraded the old 512MB memory card to 1GB memory card, and now I just want to check how much RAM my laptop Ubuntu Server actually recognized.
If someone knows the Ubuntu Server command to checking RAM that is being recognized, please let me know.

A: Use the following in terminal
cat /proc/meminfo

A: GUI: Applications -> System Tools -> Sysinfo
Console command: free -m


text:
Q: Use prolog to show cause of boolean logic failure Suppose i have the following boolean logic:
Z = (A or B) and (A or C)

Is it possible to use prolog possibly (maybe together with some library) to figure out why Z is false and to return the answer in the following formats:

*

*Z is false because A or (b and c) are false

*If i substitute some known values (or all) like (c = true) that it will say: Z is false because A is false

*It can tell me which rule or which part of the rule causes this problem: Z is false because A is false in (A or B) of "Z = (A or B) and (A or C)?

Same questions again for when Z = true with everything in reverse.
Or are these kind of questions not suitable for prolog and i should look at some SAT solver or something else?
My goal is to analyze dataflow of a program and figure answer questions like. I expect this to be true/false but it's not, what could it be?

A: I have to say this is kind of a cool problem.
I see two fundamental approaches, one in which you use Prolog's read_term/2 to obtain a term along with the variable names used in the term, which would look something like this:
?- read_term(T, [variable_names(Names)]).
|: X and Y or Z and Q.

T = _5700 and _5702 or _5706 and _5708,
Names = ['X'=_5700, 'Y'=_5702, 'Z'=_5706, 'Q'=_5708].

Giving it some thought, it seemed like this would be more trouble than it would be worth for me, so I thought I'll illustrate a "simpler" version where we don't really have variables, just atoms and a separate list of variable values. You probably could adapt the one below to the one above without a huge amount of work though, it just didn't seem really necessary to solving the problem.
First we need to support these operators:
:- op(500, yfx, or).
:- op(400, yfx, and).

I went ahead and gave these the same precedence as + and * respectively, that just seemed intuitive to me.
I'm going to have a list of variables and assignments, like [x=true, y=false]. I created a predicate to manage that, but I thought the better of it eventually and removed it, but let's note that we made this decision here.
Now my plan is to create an evaluation predicate that is going to take an expression and the variable-value assignments. It's going to produce a boolean for the supplied expression and a "reason". I'm going to cheat here and use the "is" operator, but I'm only doing this because it reads nicely to me. The most basic kind of term is
evaluate(X, Assignments, Value, X is Value) :-
    atom(X), memberchk(X=Value, Assignments).

So we can now support expressions like x:
?- evaluate(x, [x=true], V, R).
V = true,
R =  (x is true).

?- evaluate(x, [x=false], V, R).
V = false,
R =  (x is false).

These are sort of like tautologies; if x=true, then the expression "x" is true because x=true. Likewise for false. But we have the reason there, which is what you're after. So let's handle "or" next:
evaluate(X or _, Assignments, true, Reason) :-
    evaluate(X,  Assignments, true, Reason).
evaluate(_ or Y, Assignments, true, Reason) :-
    evaluate(Y,  Assignments, true, Reason).

So now we should handle the case where one of the two is true:
?- evaluate(x or y, [x=true,y=false], V, R).
V = true,
R =  (x is true) ;
false.

?- evaluate(x or y, [x=false,y=true], V, R).
V = true,
R =  (y is true) ;
false.

If we give it x=true and y=true, we will get two solutions, one for x and one for y. But we need one more rule for the false case:
evaluate(X or Y, Assignments, false, R1 and R2) :-
    evaluate(X,  Assignments, false, R1),
    evaluate(Y,  Assignments, false, R2).

So the idea here is to notice that both sides of the "or" are false and then combine the reasons with "and". This way we get this:
?- evaluate(x or y, [x=false,y=false], V, R).
V = false,
R =  (x is false)and(y is false).

Because we delegate the sides, we can now see that large and complex "or" sequences should work:
?- evaluate(a or b or c or d or e, [a=false,b=false,c=false,d=true,e=false], V, R).
V = true,
R =  (d is true) ;
false.

You can extrapolate what we did for "or" for "and", where we basically have two false cases and one true case instead of two true cases and one false case:
evaluate(X and Y, Assignments, true, R1 and R2) :-
    evaluate(X,   Assignments, true, R1),
    evaluate(Y,   Assignments, true, R2).
evaluate(X and _, Assignments, false, Reason) :-
    evaluate(X,   Assignments, false, Reason).
evaluate(_ and Y, Assignments, false, Reason) :-
    evaluate(Y,   Assignments, false, Reason).

This works for some interesting cases you might expect:
?- evaluate(x and y or z, [x=true, y=true, z=false], V, R).
V = true,
R =  (x is true)and(y is true) ;
false.

?- evaluate(x and y or z, [x=false, y=false, z=true], V, R).
V = true,
R =  (z is true) ;
false.

There are some situations where this isn't super useful, such as this one:
?- evaluate((a or b) and (a or c), [a=true,b=false,c=false], V, R).
V = true,
R =  (a is true)and(a is true) ;
false.

As you can see the first solution is not super informative because we have already said something about a; maybe we could find a way to simplify the answer by combining the answers from the children more intelligently. On the other hand, it is somewhat more helpful in this case:
?- evaluate((a or b) and (a or c), [a=false,b=false,c=false], V, R).
V = false,
R =  (a is false)and(b is false) ;
V = false,
R =  (a is false)and(c is false).

?- evaluate((a or b) and (a or c), [a=false,b=true,c=true], V, R).
V = true,
R =  (b is true)and(c is true) ;
false.

Edit: Handling undefined values
The only piece that really needs to be changed to handle undefined values is the atom(X) branch, which should be replaced with this:
evaluate(X, Assignments, Value, X is Value) :-
    atom(X),
    (    memberchk(X=V, Assignments) ->
         Value = V
    ;    member(Value, [true,false])
    ).

When a=false appears in the binding list, it will be used; if it doesn't appear, then both a=false and a=true will be generated. This appears to cover your other use cases, starting with the completely general:
?- evaluate((a or b) and (a or c), [a=false], V, Reason).
V = true,
Reason =  (b is true)and(c is true) ;

V = false,
Reason =  (a is false)and(b is false) ;

V = false,
Reason =  (a is false)and(c is false).

And you can restrict the search to cases that produce the value you're interested in:
?- evaluate((a or b) and (a or c), [a=false], false, Reason).
Reason =  (a is false)and(b is false) ;
Reason =  (a is false)and(c is false).

Of course, Prolog isn't doing anything especially smart here; it isn't trying to work backwards to figure out what values of b and c are going to lead to false, it's just generating all the possibilities and trying to unify their evaluation with false. So each undefined variable you add to the expression is going to double the search space. If this is the inefficiency you're worried about, this may not be an ideal solution for you (or, it might be fine, you might try it and see if it's tolerable).
I think you might want to look into SAT solvers if your primary concern is performance, although I don't know offhand if they are capable of giving you "reasons" back for their inferences.


text:
Q: No errors are shown when trying to suggest an edit that doesn't meet the threshold There used to be an error message displayed when attempting to submit an edit suggestion (<2k users) if the edit does not meet a certain threshold (6 characters when only the body is edited, IIRC). Now, it does not display any messages. It does prevent submitting the edit as usual though:

Tested on Chrome and Firefox on Windows.

A: status-completed ... probably
This post hasn't received any update or even a status-review so, I'm not sure what had caused this bug but it appears to have been fixed at some point: