text:
Q: Need feedback form comments to save to sepoerate lines I have a feedback form that saves to a txt file, it saves perfectly but it saves on one line. So multiple comments would be saved on one line so that saves to just one line on notepad rather than separating different comments onto different lines.
Here is my HTML
<form action="feedback.php" method="post">

      Email Address:

        <input type="text" name="email_address" value="" maxlength="100" />

        Comments:

        <textarea rows="10" cols="50" name="comments">
        </textarea>

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

</form>

Here is my php:
<?php
$email_address = $_POST['email_address'];
$comments = $_POST['comments'];
$myfile = fopen("feedback.txt", "a") or die("Unable to open file!");
$txt = 'Email: '.$email.'\nComments: '.$comments.'\n\n';
fwrite($myfile, $txt);
fclose($myfile);
?>

So I need different comments to save to different line rather than just one.

A: Your \n (new line) is not working because you use apostrophe ' instead of double quotes ".
eg you have:
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';

And you need:
$txt="Email: ".$email."\nComments: ".$comments."\n\n";

EDIT
Your email address isn't being written as you change the variable name used.
e.g. You have this code:
$email_address=$_POST['email_address'];
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';

Your $txt variable is using $email however you're setting the $_POST data to variable $email_address.
Try this complete code:
$email_address = $_POST['email_address'];
$comments = $_POST['comments'];
$myfile = fopen("feedback.txt", "a") or die("Unable to open file!");
$txt="Email: ".$email_address."\nComments: ".$comments."\n\n";
fwrite($myfile, $txt);
fclose($myfile);

It's a simple mistake to make, but you should try to get into the habit of copying and pasting your variable names, rather than re-typing them. This (helps) avoid typos etc, which in large code blocks & multiple files, becomes an even bigger problem.
And use your error logs - they are invaluable when coding!
In this case PHP (thus the logs) would have moaned about that $email variable not being defined, which in turn would have led you to inspect the variable and you'd have likely worked it out.

A: I Would use PHP_EOL since it's cross-platform-compatible! That means it handles Unix/DOS/Mac issues!
(Also i think you want to change the $email variable)
So insteat your line:
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';

Use:
$txt = "Email: ". $email_address . PHP_EOL . "Comments: " . $comments . PHP_EOL . PHP_EOL;

A: $txt='Email: '.$email.'\nComments: '.$comments.'\n\n';

Use \r\n to make new line text file like:
$txt='Email: '.$email.'\r\n Comments: '.$comments.'\r\n';

A: You actually may use single quotes and concatenate a newline character but you'd need to write code like this:
<?php
echo 'This is a test of using a newline char.' . chr(10) .
'Did it work? It should have.';
?>

To reduce the possibility of things going wrong one should do certain checks. Did the user actually submit a form? Also, we should not assume that all data from $_POST is safe and hence I use htmlentities() for the email address and the comments, just in case a malicious user tries to slip in something they shouldn't.
The other point is that some people think that variable interpolation is slow but the ironic thing is that the more variable interpolation there is the more efficient that interpolation processing becomes.  Incidentally, I changed some of the newlines by adding some and removing others so that the final result is formatted in a way that is easier to read.
<?php
    if (isset($_POST) && $_POST != NULL) {
        $email_address = htmlentities($_POST['email_address']);
        $comments = htmlentities($_POST['comments']);
        $myfile = fopen("feedback.txt", "a") or exit("Unable to open file!");
        $txt="Email: $email_address\nComments:\n\n$comments\n\n";
        fwrite($myfile, $txt);
        fclose($myfile);
    }
?>

I replaced the morbid die() with exit() since they are both equivalent language constructs; they both generate the same EXIT opcode.


text:
Q: Time Need to validate for timepicker in xamarin forms I need to validate a selected time from the time picker. So if the selected time is not valid then I need to display a toast message.
Which event will trigger if time will select from the time picker?
And I don't want to bind the time if the selected time is not valid based on my condition.
XAML Code:
<controls:DatePickerCustom FontSize="14" HeightRequest="35" Date="{Binding CustomDate,Mode=TwoWay}" MaximumDate="{Binding MaximumDate}" FontFamily="Segoe UI" Format="D" IsEnabled="{Binding IsDatePickerEnable}">
                                    <DatePicker.Triggers>
                                        <DataTrigger TargetType="DatePicker" Binding="{Binding IsCustomSelected}" Value="true">
                                            <Setter Property="TextColor" Value="{DynamicResource HeadingTextColor}" />
                                            <Setter Property="TextColor" Value="{DynamicResource HeadingTextColor}" />
                                        </DataTrigger>
                                    </DatePicker.Triggers>
                                </controls:DatePickerCustom>

A: Handle this in your "setter" for property CustomDate.
In a setter, the new value is value. If value isn't valid, Show the toast message. Return from setter, without changing the internal field that holds the value, and without calling OnPropertyChanged.
If you need more information, please show the code that declares property CustomDate.
It that property is currently an "auto-property", convert it to a "full-property" - this will have a "backing field", and gives you a place to do the test, and reject the change.

A: You could listen the PropertyChanged event of TimePicker,then match the Time property.
For example:
<TimePicker PropertyChanged="TimePicker_PropertyChanged"></TimePicker>

private void TimePicker_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        TimePicker timePicker = sender as TimePicker;
        if (e.PropertyName.Equals("Time") )
        {
            var time = timePicker.Time;
            if (time.Minutes == 10) // your condition
            {

            }
            else
            {
                DisplayAlert("Warning", "This is a validate time", "Cancel");
            }
        }
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update object data-members in React state doesn't trigger re-rendering I'm using TypeScript and React to try to implement my custom types in React component. However the component is not re-rendering if data members of object in state has updated.
Here's my code:
class Person {
  name: string;
  surname: string;

  constructor(name: string, surname: string) {
    this.name = name;
    this.surname = surname;
  }
}

class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);
    this.state = {
      persons: [new Person("Alpha", "A"), new Person("Bravo", "B")]
    };
  }

  render() {
    return (

        <button
          onClick={() => {
            this.state.persons[0].name = "Zulu";
            this.state.persons[0].surname = "Z";
          }}
        >
          Change A to Z
        </button>

        <button
          onClick={() => {
            this.setState({
              persons: [...this.state.persons, new Person("Charlie", "C")]
            });
          }}
        >
          Add C
        </button>

        <button onClick={() => { this.forceUpdate(); }}> Force Update </button>

        {this.state.persons.map(person => (

            {person.name} {person.surname}

        ))}

    );
  }
}

Full Code Snippet
If I click on Change A to Z nothing will change - unless Add C or Force Update is clicked. I am assuming React cannot detect changes made in Person therefore no re-render.
I have some questions about this problem.

*

*Is this approach (custom datatype as state) recommended to use in React

*

*If yes - how do I make this work? (React able to detect changes made in Person)

*If no - what is the recommended approach to use custom datatype in React?

A: React will not re-render by default if every element in the new state is === to every element in the old state. You also have to call setState in order to trigger a re-render. Your Change A to Z is failing on both counts - you need to both create a new persons array without mutating what's currently in state, and then call setState with the new array.
Also, having a Person instance doesn't look to be accomplishing anything, since there are no methods on the class - and it'll make changing the state harder, so I'd remove Person entirely. Try
  constructor(props) {
    super(props);
    this.state = {
      persons: [{ name: 'Alpha', surname: 'A' }, { name: 'Bravo', surname: 'B' }]
    };
  }

Then change
      onClick={() => {
        this.state.persons[0].name = "Zulu";
        this.state.persons[0].surname = "Z";
      }}

to
onClick={() => {
  this.setState({
    persons: [{ name: 'Zulu', surname: 'Z' }, ...this.state.persons.slice(1)]
  });
}}

The
persons: [{ name: 'Zulu', surname: 'Z' }, ...this.state.persons.slice(1)]

effectively immutably replaces the first element of the array with the new Zulu object.


text:
Q: Calling JavaScript from component template I'm working on integrating payment forms from a third party, by using the Link to Javascript they provide.
when I place the code in the index.html page its works just fine, but when I move the code to the component template is not working, below is part of the code:
this is the script code to initialize the payment form:

 <form id="paymentForm" action="xxx" method="post" style="margin: 10%;">

        <button type="submit" class="btn btn-default">Submit</button>

    </form>

when I'm using these three-part together on the index page is working fine when I'm trying to work from a component template that is not

A: Put the script tag  inside the head tag within index.html
Then put the var tokenpay = TokenPay('tokenpay123'); etc block inside ngAfterViewInit within the relevant component (i.e. the component hosting the form). Then it should work fine.
Note that because tokenPay is a global variable, the TypeScript compiler will not recognise it so you will need to add:
declare const tokenPay: any
inside the .ts file of the relevant component.

A: It's not clear on what problem you're facing, but I think you have to call the   after your form. By doing so early, the form may not exist yet


text:
Q: Angular Link Card I have an app, a marketplace. When someone shares a link to a product I want to load a picture of the product and a name. Like when you share a link to a social media post there is a picture and a title. Can I do it with angular, and how do I do that?

A: What you search for is called a link preview,
What makes this work is metadata called the Open Graph Protocol. Facebook launched the Open Graph protocol in 2010,
The Open Graph Protocol allows websites to control what is displayed when a website is shared
example
<meta property="og:title" content="The Rock" />
<meta property="og:type" content="video.movie" />
<meta property="og:url" content="https://www.imdb.com/title/tt0117500/" />
<meta property="og:image" content="https://ia.media-imdb.com/images/rock.jpg" />

so if you have a link and want to display the preview of it, you just need to load the link and read this metadata values
How do you get this metadata from a website?
One way you can use linkpreview.net API to get what you are looking for
export interface LinkPreview {
    title:       string;
    description: string;
    image:       string;
    url:         string;
}
// ... here how to get the linkPreview
getLinkPreview(link:string): Observable<LinkPreview>{
  const url = "https://api.linkpreview.net?key=<enter your key>&q="+link;
  return this.http.get<LinkPreview>(url);
}

or if you don't want to use API you can use packages like

*

*@angular-material-extensions/link-preview

*ngx-link-preview


text:
Q: Finding the minimum "internal" nodes of AVL tree? I know how to find the minimum numbers of nodes in an AVL tree of height h (which includes external nodes) with the formula n(h) = n(h-1) + n(h-2) + 1 but I was wondering if there was a formula to just find the minimum internal nodes only of an AVL tree with height h.
So for n(3) = 4, if we're only counting internal nodes. n(4) = 7, if we're only counting internal nodes. I can draw it out and count the internal nodes but when you get to bigger AVL trees it's a mess.
I can't seem to find anything on this and trying to find a pattern with consistent answers has only led to hours of frustration. Thanks in advance.

A: Yep, there's a nice way to calculate this. Let's begin with the two simplest AVL trees, which have order 0 and order 1:
*    *
     |
     *

This first tree has no internal nodes, and the second has one internal node. This gives us our base cases for a recurrence relation:

*

*I(0) = 0

*I(1) = 1

From here, we notice that the way to get the fewest internal nodes in an AVL tree of order n+2 is to pick two trees of order n and n+1 as children (minimizing the number of nodes) that have the fewest internal nodes possible. The resulting tree will have a number of internal nodes equal to the number of internal nodes in the two subtrees, plus one for the new root. This means that

*

*I(n+2) = I(n) + I(n+1) + 1.

Applying this recurrence gives us the sequence

0, 1, 2, 4, 7, 12, 20, etc.

And hey - have we seen this before somewhere? We have! Adding one to each term gives us

1, 2, 3, 5, 8, 13, 21, etc.

which is the Fibonacci sequence, shifted down two positions! So our hypothesis is that

I(n) = F(n+2) - 1

You can prove that this is the case by induction on n.
Here's a different way to arrive at this result. Imagine you take an AVL tree of height n and remove all the leaves. You're now left with an AVL tree of height n-1 (prove this!), and all of the remaining nodes in this tree are the internal nodes of the original tree. The smallest possible number of nodes in an AVL tree of height n is F(n+2)-1, matching our result.


text:
Q: mod_rewrite: serve images form another server how can i write a mod_rewrite rule to handle all the requests like http://mysite.example/images/IMAGE.gif|jpg|png and serve instead http://mystaticfiles.example/IMAGE.gif|jpg|png ?
Thanks

A: As Pekka correct mentioned, you can send a Redirect ([R=301]) or you could use a the Proxy-flag ([P]) to send the request to a specific server. With the proxy method, you will lose the logging information about the requesting client, because you server mysite.example connect to mystaticfiles.example and grabs the content from their. You also double the bandwith, with in your system with a proxy.
client connection -> mysite.example -> proxy request to mystaticfiles.example
-> mystaticfiles.example sends file -> mysite.example -> sends file to client


text:
Q: MCRYPT in .Net I have a PHP decryption algorithm at one end, and a .Net encryption algorithm at another. I am using mcrypt_decrypt for decrypt purpose in PHP code, and looking for an equivalent of mcrypt_encrypt in .Net. More specifically, the PHP code that I want to convert to .Net is the following:
$cipher_alg = MCRYPT_RIJNDAEL_128;
$iv = mcrypt_create_iv ( mcrypt_get_iv_size ( $cipher_alg, MCRYPT_MODE_ECB ), MCRYPT_RAND );

$encrypted_string = mcrypt_encrypt ( $cipher_alg, $sessionkey, $string, MCRYPT_MODE_CBC, $iv );
$hex_encrypted_string = bin2hex ( $encrypted_string );

Is there an equivalent of mcrypt_encrypt in .Net?

A: I have come out with a solution in my blog.
Here is an excerpt :
    private static string CreateEncryptedString(string myString, string hexiv, string key)
    {
        RijndaelManaged alg = new RijndaelManaged();
        alg.Padding = PaddingMode.Zeros;
        alg.Mode = CipherMode.CBC;
        alg.BlockSize = 16 * 8;
        alg.Key = ASCIIEncoding.UTF8.GetBytes(key);
        alg.IV = StringToByteArray(hexiv);
        ICryptoTransform encryptor = alg.CreateEncryptor(alg.Key, alg.IV);

        MemoryStream msStream = new MemoryStream();
        CryptoStream mCSWriter = new CryptoStream(msStream, encryptor, CryptoStreamMode.Write);
        StreamWriter mSWriter = new StreamWriter(mCSWriter);
        mSWriter.Write(myString);
        mSWriter.Flush();
        mCSWriter.FlushFinalBlock();

        var EncryptedByte = new byte[msStream.Length];
        msStream.Position = 0;
        msStream.Read(EncryptedByte, 0, (int)msStream.Length);

        return ByteArrayToHexString(EncryptedByte);

    }

    public static byte[] StringToByteArray(String hex)
    {
        int NumberChars = hex.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        return bytes;
    }

    public static string ByteArrayToHexString(byte[] ba)
    {
        StringBuilder hex = new StringBuilder(ba.Length * 2);
        foreach (byte b in ba)
            hex.AppendFormat("{0:x2}", b);
        return hex.ToString();
    }

There is one thing to note. The key size must be 16. Which means that key parameter must be a string with 16 characters. Or else the encryption won't work and will throw a CryptographicException.
On the PHP end, here's how you do the decoding:
$cipher_alg = MCRYPT_RIJNDAEL_128;
$decrypted_string = mcrypt_decrypt($cipher_alg, $key,
$encrypted_string , MCRYPT_MODE_CBC, trim(hex2bin(trim($hexiv))));

A: There isn't a direct equivalent, but 128-bit Rijndael is supported (and probably most other ciphers that you would want). See the Rijndael class for details and an example.
Basically the encryption part of the framework is based on you specifying an appropriate instance of a base class (CryptoStream, SymmetricAlgorithm etc) rather than specifying a cipher by name - but you should be able to do what you need to.


text:
Q: how to print a value in array with json $qr=mysql_query("SELECT `setting-name`,`setting-explain` FROM `fndn_Setting`");
    $row=mysql_fetch_assoc($qr);
    for($i=1;$row=mysql_fetch_assoc($qr);$i++){
        $arr[$i]=$row;
    }

    echo json_encode($arr);

Hi
the json print this value:
{"1":{"setting-name":"sms_num","setting-explain":"201300"},"2":{"setting-name":"sms_txt","setting-explain":"40"}}

But I want to print this value:
{"1":{"sms_num","201300"},"2":{"sms_txt","40"}}

How can I correct this?

A: Change one line to take only values
    $arr[$i]=array_values($row);


text:
Q: Got error: FT_Open_Face failed: error 2 I am getting following error when i use CGContextDrawPDFPage(context, _PDFPage) for some files. Any work around to fix this issue?
FT_Open_Face failed: error 2.

A: Error 2 looks like errno 2 which is "File not found".  Please post more code to confirm this.


text:
Q: NPM error when I am trying to install @nuxtjs/firebase I am getting this error that I am not understanding and that I don't really know how to fix... I am using Nuxt.js and I want to use firebase along with it, but when I'm trying to firebase.nuxtjs.org and install @nuxtjs/firebase I am getting this error -
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: **************@1.0.0
npm ERR! Found: firebase@9.0.1
npm ERR! node_modules/firebase
npm ERR!   firebase@"^9.0.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer firebase@"^8.3.1" from @nuxtjs/firebase@7.6.1
npm ERR! node_modules/@nuxtjs/firebase
npm ERR!   @nuxtjs/firebase@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

I was hoping you all could help me with it. Thank you in advance!

A: As mentioned in the readme of the @nuxtjs/firebase library (https://github.com/nuxt-community/firebase-module), firebase version 9 is currently not supported. Using firebase@8.10.0 and @nuxtjs/firebase@7.6.1 should work.
You can track the progress of when firebase 9 is supported under nuxt here: https://github.com/nuxt-community/firebase-module/issues/573


text:
Q: Edubuntu packages on Ubuntu I found this thread
with some over-explained but interesting things.
the "linux-rt" pack doesn't exist in 10.10 this pack actually installs the realtime kernel but 10.10 doesn't have any. just try it without this part
PS:i will make you a quick explanation of every part in this command line, because knowledge is power
sudo - gives you a root privileges
aptitude - this is a text-based package manager similar to synaptic (you can successfully change this part with 'apt-get')
update - updates your software channels to current state
&& - and (from C program language)
install - install
ubuntustudio-desktop - GUI of ubuntustudio system
ubuntustudio-audio - a collection of applications aimed at audio creation and editing
ubuntustudio-audio-plugins - A collection of LADSPA and DSSI plugins.
ubuntustudio-video - a collection of applications aimed at video creation and editing
ubuntustudio-graphics - collection of applications aimed at 2D/3D creation and editing.
linux-rt - a metapackge that installs you the latest complete Realtime Linux kernel available.

I installed all the packages but didn't installed the Ubuntustudio-desktop because I wanted apps not new booting screen.
I want to install all apps of Edubuntu and don't want my Ubuntu to boot like Edubuntu i.e., I don't want edubuntu-desktop but all the packages of it. So instead of installing edubuntu-desktop what are the other name of packages?

A: You can add the following package bundle for your system according to your work-level!
ubuntu-edu-preschool - Preschool (
ubuntu-edu-primary - Primary ( ages 6-12) educational application bundle
ubuntu-edu-secondary - Secondary ( ages 13-18) educational application bundle
ubuntu-edu-tertiary - Tertiary ( university level ) educational application bundle


text:
Q: How to make applozic chat private for each user? How to make messages private that should be visible to only sender and receiver. Currently all message showing to all users.

A: There is different Group types, the default is Public Group type 2.
You can specify the group type when you create a group, it might be type 1 you will have to use.

A: you can use ALMessage property Metadata. In this metadata you can pass your own Key/Value. using this pair you can identity chat is private or not.
While get message from message list you can check your key is there in metadata or not. if key is there in metadata it means message is private or you can add that chat in other list array.


text:
Q: Reading multiple values from INI file using python I have a INI file from which I need to read multiple files:
[boy]
Gender=Male
Name=Jian
Age=23

When I do
def readINI(inp):
    configpath=path.relpath("roles.ini")
    config.read("roles.ini")
    if inp in config.sections():
            print(config.get(inp, 'Age'))

It gives me
boy 23.

But when I try to print multiple values like print(config.get(inp, "Name" "Age")). It gives me error saying :

TypeError: get() takes 3 positional arguments but 4 were given

Please help me out.


text:
Q: What is the C# equivalent of Java's getComponentType()? I am translating from Java to C# and have code similar to:
T[] @unchecked = (T[])Array.newInstance(array.getClass().getComponentType(), sampleSize);
I know getClass() equals to GetType() in C# and newInstance() equals to CreateInstance(); but idk what's the C# equivalent of getComponentType()?

A: Try this, it will work Array.CreateInstance(array.GetType().GetElementType(), sampleSize);


text:
Q: Layout of shared memory and cache coherency I have a number of processes, about 16 (but design limit is a few hundred) that communicate via shared memory. Each process has a reserved area in the shared memory where it places requests.  When a request is ready for others, it sets a per process bit "RequestReady".  Other processes are reading the RequestReady bits inside short run spin loops and take action if bits are set. This is specific to our needs and kernel semaphores are used frequently too, but the spin loops are faster for our highly specific need (tested)
I am especially interested in effects for cross socket cache coherency on x86 platforms rather than shared L2/L3 cache designs. This is not a question about affinity, I am aware of using that.
Currently, I have the "RequestReady" bit spaced out so that each process has its bit on a seperate cache line.   Logically something like
 struct {
    unsigned long RequestReady;
    char DataArea[5000];
 } ProcessSlots[MAX_SLOTS];

This means that I essentially have up to MAX_SLOTS of cachelines, being invalidated.  The advantage is that only one core will be writing to the cacheline, and other sockets will simply need to revalidate.  This means that writer will not (should not?) write stall, but readers will at some stage when they are scanning for work.  A disadvantage is that I have used a number of cachelines that might be better for something else.
An alternative layout would be
unsigned long RequestReady[MAX_SLOTS];
char DataArea[5000*MAX_SLOTS];

This means that all the RequestReady flags are together in a cacheline, so I only have one cache invalidate message, but I am worried about creating a hotspot like this, one that will be essentially shared across every socket/core. Will this degrade so that every read/write to this cacheline will be going to main memory?
The RequestReady bits are toggled often (ca. 10,000/sec)  and scanned frequently, (ca 100K to 10M/sec).  I know I will be going to main memory access speeds often, but want a layout that minimises this for such a hot area.
What is a good approach for laying out these RequestReady bits?  Is there an alternative layout I haven't considered? Does my first approach have any advantage for the writer over the second approach?


text:
Q: One of the Display Port connected to Intel Graphics not working I have 2 Display Port and an HDMI Port on my laptop and an HDMI Port.

*

*Mini Display Port 1.3 (using NVIDIA graphics). It's working

*Mini Display Port 1.2 (using Intel HD Graphics). It's not working

*HDMI Port (using NVIDIA Graphics). It's working.
Both Graphics drivers are up-to-date and working.
Note: I am using HDMI to mini Display port convertor. One monitor is using an HDMI port, second is using the Nvidia display port using the adapter. I want to buy a 3rd monitor and connect it to the remaining Display Port, but want to resolve this issue before ordering it.
Does buying a monitor which natively supports mini display port will solve the issue? How do I check to be sure since the monitor store here doesn't have return policy.
Note: I see some CPU usage in system process when I use the Intel Graphics Port. WPA says it's related to igdkmd64.dll which is part of Intel Graphics.

A: So I figure out the issue.
The Display Port connected to Intel HD Graphics doesn't support HDMI to mini DP adapters. You need to have a monitor which natively supports Display Port for it to work.


text:
Q: OpenLayers and Ionic 3 | tileLoadFunction not working I am building a simple map app with the Ionic 3 framework.  I am using OpenLayers 4.0.2 as the map api.
It has been going great until I tried implementing a custom tileLoadFunction for the basemap tile layer used in the app.  In my case, I am attempting to get tiles from an IndexedDB.
 tileLoadFunction: function(tile, src) {
     let imageTile = tile as ol.ImageTile;
     let img = imageTile.getImage() as HTMLImageElement;
     let tileCoord = imageTile.getTileCoord();
     tileCoord[2] = -tileCoord[2] - 1;
     self.mapDataService.getBasemapTile(tileCoord).then(b64 => {
         if (b64) {
             img.setAttribute('src', b64);
         } else {
             img.setAttribute('src', src);
             self.mapDataService.cacheBasemapTile(tileCoord,src);
         }
     });
 }

This is fairly common requirement, and I have seen dozen of implementations online - but not in TypeScript...  I can't just do tile.getImage().src = b64; or else I get complile errors.  So I cast to ol.ImageTile and HTMLImageElement.
I am 100% positive that the images returned by b64 or src variables are valid images. But the basemap tile is always blank???  Is there a better way to do this in TypeScript?


text:
Q: printf doubles with fixed overall length I would like to printf doubles such that the overall length is always the same and the number is rounded if too long.
For example, with overall length 7:
double a = 1.23456789;
double b = 12.3456789;
double c = 123.456789;
printf("a: %f\n", a);
printf("b: %f\n", b);
printf("c: %f\n", c);

would print:
a: 1.23457
b: 12.3457
c: 123.457

Is there a simple way to achieve this?

A: Yes, there is. See the specifications for printf conversion specifiers. Use a # to select the alternative form to keep the trailing zeros. Use the g to obtain a representation with a fixed total number of digits. The .6 specifies the exact number of digits.
printf("a: %#.6g\n", a);
printf("b: %#.6g\n", b);
printf("c: %#.6g\n", c);

A precision of 6 digits happens to be the default, so this works as well
printf("a: %#g\n", a);

A: printf("a: %.6g\nb: %.6g\nc: %.6g\n", a, b, c);

See ideone


text:
Q: Nginx with docker, location different from slash not found Summary
I created this simple example to correct and check the errors that I have in another more complex project.
So I've a docker-compose file with 1 web server and 2 app and a nginx conf file.
Please note, that I'm testing it with Docker Quick Start Terminal for Windows 10 Home Edition, but I've tested even on Ubuntu 18.04 and the outcome is the same.
Outcome
Going to: http://192.168.99.100:8080/
 Default output:

It works!

The only issue here is with app2, since I'm not able to access app2.
Going to http://192.168.99.100:8080/app2.
Error:

Not Found
The requested URL was not found on this server.

I'm not understanding why I'm not able to do that, and where is the error.
What I've Tried

*

*Switch the location order, so location /app2 after location /, but nothing changed

*Change the location of location /app2 to location /foo, even here same outcome.

*Change the path related to the previous example, anything different from location / does not works. (e.g. location /bar location /foobar location /test)

*Change location / in order to refer the app2 instead of app1, and it works but in this way I can't reach app1.

location / {
    proxy_pass http://app2:80;
}

location /app1 {
    proxy_pass http://app1:80;
}

Code
docker-compose.yml
version: "3.7"

services:
  web:
    image: nginx:alpine
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
    ports:
        - 8080:80
    networks:
        - app1_net
        - app2_net

  app1:
      image: httpd:latest
      networks:
        - app1_net

  app2:
      image: httpd:latest
      networks:
        - app2_net

networks:
  app1_net:
  app2_net:

nginx.conf
events {}
http {
    server{
        listen 80;
        listen [::]:80;

        server_name localhost;

        location /app2 {
            proxy_pass http://app2:80;
        }

        location / {
            proxy_pass http://app1:80;
        }
    }
}

A: This is the correct way, use a regex to allow sub folders navigation and a perfect match on /app2 to redirect traffic on http://app2:
location ~ ^/app2/(.*)$ {
  proxy_pass http://app2/$1;
}
location = /app2 {
  proxy_pass http://app2/;
}
location / {
  proxy_pass http://app1;
}

A: I have added another stackoverflow answer here.
It is summarized here:

*

*My setup has a couple of apps sitting behind nginx. I want to redirect /appx-uri/bla/blo/bli to /appx-uri/bla/blo/bli/ instead of /bla/blo/bli/ which is the default nginx behavior.

*Also, all my static files (for an app) are gathered for nginx to serve /repairapp/static/.

Adding the directive rewrite ^/repairapp/([^static].*[^/])$ /repairapp/$1/ permanent; in the server block fixes it.
I then have

*

*To fix the issue: rewrite ^/repairapp/([^static].*[^/])$ /repairapp/$1/ permanent;

*To have nginx serve resources location /repairapp/static/ {

*To access an app location /repairapp/ {


text:
Q: Obtaining Std Dev & t value in lmer() estimates I'm trying to use lmer() to construct a linear mixed effects model, but the output I get simply looks like this
> model <- lmer(elogit_ToTarget ~ (Age..vA..months. + EVT_GSV + DDNotAgeSensitive)*(OrthTime + OrthTime2) +
+                 ( OrthTime + OrthTime2 | Subject ), data=d)
> print(model, correlation=F)
Linear mixed model fit by REML ['lmerMod']
Formula: elogit_ToTarget ~ (Age..vA..months. + EVT_GSV + DDNotAgeSensitive) *
    (OrthTime + OrthTime2) + (OrthTime + OrthTime2 | Subject)
   Data: d
REML criterion at convergence: 373.2443
Random effects:
 Groups   Name        Std.Dev. Corr
 Subject  (Intercept) 0.4440
          OrthTime    2.7986    0.65
          OrthTime2   1.0893   -0.12 -0.21
 Residual             0.2486
Number of obs: 1060, groups: Subject, 30
Fixed Effects:
                (Intercept)             Age..vA..months.                      EVT_GSV            DDNotAgeSensitive
                  -3.516428                     0.008027                     0.026585                    -0.130812
                   OrthTime                    OrthTime2    Age..vA..months.:OrthTime   Age..vA..months.:OrthTime2
                 -10.282966                     2.193035                     0.070552                     0.001379
           EVT_GSV:OrthTime            EVT_GSV:OrthTime2   DDNotAgeSensitive:OrthTime  DDNotAgeSensitive:OrthTime2
                   0.106536                    -0.037707                     1.532189                     2.627951

In other examples that I've seen, there are columns for Standard Error and t-value in addition to the estimates, but this doesn't appear to be an option that can be specified.  How can I get these?

A: Use summary(model); if you want to extract the fixed-effect coefficient table, use coef(summary(model)).


text:
Q: How can we write an API call to get a list of all products without orders How can we write an API call to get a list of all products without sales
Essentially need to retrieve all prodcuts without sales/orders so far


text:
Q: JavaScript: For loop array in array I need to create a variable which store array in array by for loop to pass chart data to a chart.
Consider I have some JSON data and I am trying to acquire all the data with the below process
var FansChart = [];
    for (var i = 0; i < 3 ; i++) {
        for (var j = 0; j < 33; j++) {
             FansChart.push({
                name : url[i],
                data : data.result[i].trendData[j].value, //api thing doesn't really matter
              });
            }
        }

but it seem I am using the wrong method, how can I correct this?
I wish to be able to call something like:
data.result[2].trendData[23].value

UPDATE one:
var abc =[];
            var FansChart = [];
            for (var i = 0; i < result.length; i++) {
                    for (var j = 0; j < data.result[0].trendData.length; j++) {
                        abc.push(data.result[i].trendData[j].value);
                    }
                  FansChart.push({
                    name : url[i],
                    data : abc

                  });
                  }

I have update my method like above is more like what i want to do, but i realize that all the trendDate have been bonded to varaible abc, how may i separate them?
JSON
errorCode: null,
message: "Success",
result: [{
    urlId: "a279ab1177ab8d7011466e77b79b98f7",
    trendData: [],
    url: "https://www.instagram.com/p/BFQGk2WER56/?taken-by=fishfung_saimei&hl=en"
}, {
    urlId: "a279ab1177ab8d7011466e77b79b98f7",
    trendData: [{
        date: "2016-06-04",
        value: 0
    }, {
        date: "2016-06-21",
        value: 0
    }, {
        date: "2016-06-12",
        value: 0
    }, {
        date: "2016-06-05",
        value: 0
    }, {
        date: "2016-06-07",
        value: 0
    }, {
        date: "2016-06-19",
        value: 0
    }, {
        date: "2016-06-25",
        value: 1527
    }, {
        date: "2016-06-25",
        value: 0
    }, {
        date: "2016-06-11",
        value: 0
    }, {
        date: "2016-06-15",
        value: 0
    }, {
        date: "2016-06-08",
        value: 0
    }, {
        date: "2016-06-27",
        value: 1527
    }, {
        date: "2016-06-27",
        value: 0
    }, {
        date: "2016-06-06",
        value: 0
    }, {
        date: "2016-06-29",
        value: 0
    }, {
        date: "2016-06-09",
        value: 0
    }, {
        date: "2016-06-03",
        value: 0
    }, {
        date: "2016-06-17",
        value: 0
    }, {
        date: "2016-06-24",
        value: 1527
    }, {
        date: "2016-06-24",
        value: 0
    }, {
        date: "2016-06-13",
        value: 0
    }, {
        date: "2016-06-22",
        value: 0
    }, {
        date: "2016-06-01",
        value: 0
    }, {
        date: "2016-06-14",
        value: 0
    }, {
        date: "2016-06-18",
        value: 0
    }, {
        date: "2016-06-26",
        value: 1527
    }, {
        date: "2016-06-26",
        value: 0
    }, {
        date: "2016-06-20",
        value: 0
    }, {
        date: "2016-06-10",
        value: 0
    }, {
        date: "2016-06-23",
        value: 0
    }, {
        date: "2016-06-28",
        value: 0
    }, {
        date: "2016-06-02",
        value: 0
    }, {
        date: "2016-06-16",
        value: 0
    }],
    url: "https://www.instagram.com/p/BFQGk2WER56/?taken-by=fishfung_saimei&hl=en"
}, {
    urlId: "a279ab1177ab8d7011466e77b79b98f7",
    trendData: [{
        date: "2016-06-04",
        value: 0
    }, {
        date: "2016-06-21",
        value: 0
    }, {
        date: "2016-06-12",
        value: 0
    }, {
        date: "2016-06-05",
        value: 0
    }, {
        date: "2016-06-07",
        value: 0
    }, {
        date: "2016-06-19",
        value: 0
    }, {
        date: "2016-06-25",
        value: 1527
    }, {
        date: "2016-06-25",
        value: 0
    }, {
        date: "2016-06-11",
        value: 0
    }, {
        date: "2016-06-15",
        value: 0
    }, {
        date: "2016-06-08",
        value: 0
    }, {
        date: "2016-06-27",
        value: 1527
    }, {
        date: "2016-06-27",
        value: 0
    }, {
        date: "2016-06-06",
        value: 0
    }, {
        date: "2016-06-29",
        value: 0
    }, {
        date: "2016-06-09",
        value: 0
    }, {
        date: "2016-06-03",
        value: 0
    }, {
        date: "2016-06-17",
        value: 0
    }, {
        date: "2016-06-24",
        value: 1527
    }, {
        date: "2016-06-24",
        value: 0
    }, {
        date: "2016-06-13",
        value: 0
    }, {
        date: "2016-06-22",
        value: 0
    }, {
        date: "2016-06-01",
        value: 0
    }, {
        date: "2016-06-14",
        value: 0
    }, {
        date: "2016-06-18",
        value: 0
    }, {
        date: "2016-06-26",
        value: 1527
    }, {
        date: "2016-06-26",
        value: 0
    }, {
        date: "2016-06-20",
        value: 0
    }, {
        date: "2016-06-10",
        value: 0
    }, {
        date: "2016-06-23",
        value: 0
    }, {
        date: "2016-06-28",
        value: 0
    }, {
        date: "2016-06-02",
        value: 0
    }, {
        date: "2016-06-16",
        value: 0
    }],
    url: "https://www.instagram.com/p/BFQGk2WER56/?taken-by=fishfung_saimei&hl=en"
}],

A: Convert i to j in for :
Change :
for (var j = 0; j < 33; i++) {

to :
for (var j = 0; j < 33; j++) {

A: You're missing a semicolon at the 2nd line. It should be for (var i = 0; i < 3; i++) {

A: Here you go..
FansChart.push({
            name : url[i],
            data : data.result[i].trendData[j].value // no comma here
          });

Remove the comma in data : data.result[i].trendData[j].value statement.

A: Remove i++ from second for loop
var FansChart = [];
for (var i = 0; i < 3 ; i++) {
    for (var j = 0; j < 33; j++) {
         FansChart.push({
            name : url[i],
            data : data.result[i].trendData[j].value //api thing doesn't really matter
          });
        }
    }

I hope it will work for you.


text:
Q: What does "extended meaning" mean? I have an assignment and one question confuses me a lot. the question is:

The words below have a literal as well as an extended meaning. Write the literal meaning of the words. Use the following words in sentences of your own using the 'extended' meaning.

*

*angry

*train

*mouth

What does "an extended meaning" mean? And how can I use extended meaning to form a sentence?

A: The use of extended is odd. Without more context, I would guess that what the assignment is talking about is a figurative meaning. (In contrast to literal.)
For instance, the words are not being used in a literal sense in the following sentences:

It was an angry wound.
  They got on board the pity train.
  She was at the mouth of madness.

A: The website vocabulary.com says that extended means:

extended (adj.) beyond the literal or primary sense

So I suppose there are two ways a word could have an extended meaning:

*

*the word could be used in a figurative sense, rather than a literal sense

*the word could have a secondary meaning that we don't immediately associate with the word

As for your exercise, the word mouth seems easy. People have a mouth, and so od lions – but rivers have a mouth as well.

The mouth of the Rhine is at Hoek van Holland by the North Sea.

As for a word like angry, we only need to consult a good dictionary for ideas. From Wordnik:

angry (adj.)

*

*adj. Displaying or feeling anger.

*Inflamed and painful.

*Dark and stormy, menacing.

That third one looks like an extended meaning to me. So, we might say:

When Stella noticed the angry clouds, she called her children inside.

The word train  has dozens of meanings, so it's a little harder to figure out which ones are the "primary" definitions and which might the "extended" meanings. But I will say this about the noun train: a railroad yard has a train, but so does a wedding dress. Moreover, about the verb train: a woman might train a dolphin, but she also might train her hair.


text:
Q: How do you change text with j query inside of a certain span/id=aaa? I posted the start of an example, where the country is US
and it needs to be converted to United States
and the US in TOYS R US can be changed since it matches
https://jsfiddle.net/yy4po40x/
TOYS R US

        123 main street

        US

A:
TOYS R US

    123 main street

    US

Working Demo JSFIDDLE

A: As far as I understood without understanding the matching thing that you said, if you want to change texts inside paragraphs inside span, then here's your solution using jquery:
$(document).ready(function(){
  $('#aaa p:nth-child(2)').html('USA');
});

Whereas, If you want to replace something globally then :
$(document).ready(function(){
      $("body").html($('body').html().replace(/US/g, 'United States'));
)};

But your html is wrongly coded. This is the right way.

        123 main street

        US

You don't actually use span to enclose p tags. Span is for selecting a small area basically which do not change any alignment of the webpage but for the purpose of calling some properties to change something inside it.
The right way to use span is

        123 main street

        US

Hope I could help.


text:
Q: In a disk drive, are tracks and sectors physical or logical implementations? Given a disk drive that has disk sector and track (as given in diagram in Wikipedia), are the 2 structures physically implemented on the drive or are they logical implementations?
I am not asking about any specific disk drive model or any particular version. Any latest disk drive having sector and track would do. It's just I was curious what kind of implementations were those.

A: It may not apply to modern drives any more, but that is exactly how hard drives and floppy drives worked and accessed data.
You can move a read/write head on a surface to a certain track/cylinder (or stack of multiple heads on multiple platters in case of hard drives) with a stepper motor or voice coil.
The circular track is divided into sectors which can be individually read or written when they appear under the head as the surface rotates.
However, as the inner tracks have slower linear velocity than the outer tracks, even in early computing days tracks could have different amount of sectors depending on the location of the track. And to abstract it away, the drive may just present the user with constant amount of cylinders, heads, and sectors, i.e. a virtual or logical geometry that is separate from physical geometry.
In many systems though, even if drives internally have some physical amount of heads, tracks and sectors, and have converted that to some logical geometry other than the physical geometry, they have been mainly accessed in linear fashion for a long time now, so cylinder, heads and sectors are not so important.

A: The properties of the magnetic surface and the disk heads determine the minimal track width, track distance and the tangential length of a bit. So the number of tracks is given by physical limits. The number of sectors is a result of these limits too.
The circumference of an inner track is much smaller than that of an outer track. So there are less sectors on an inner track than on the outmost track.
The disk controller should set the internal number of tracks, sectors and heads.
The external organisation of the disk may be much different. The number of logical sectors per track is constant, there may be more logical heads than physical heads. The number of logical tracks may be different to the physical number.
A later improved version of the same disk model may use another internal physical organisation with different numbers of tracks and sectors.


text:
Q: How do I send CSRFToken in my axios requests using Nuxt and Django on the backend? I'm using Django Rest as a backend api, and each API call requires a CSRF Token in the headers. In my "Applications" tab in Developer Tools, I clearly have a "csrftoken" value and I somehow need to extract that with each subsequent POST request that my Nuxt application does (using Nuxt/Axios)
My settings.py looks like this:
CORS_ORIGIN_WHITELIST = (
    "http://localhost:3000",
    "http://127.0.0.1:3000",
)

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000",
]
CORS_EXPOSE_HEADERS = ['Content-Type', 'X-CSRFToken']
CORS_ALLOW_CREDENTIALS = True

CSRF_COOKIE_SAMESITE = "Lax"
SESSION_COOKIE_SAMESITE = "Lax"
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_HTTPONLY = True

I have tried using js-cookies with Cookies.get("csrftoken") which just returns undefined. Is the cookie not accessible because it's set to HTTPONLY`?
What is the recommended step here? Should I create a view in my django backend to generate a CSRF Token, and then before making each request on the frontend, I call this view in my Django app to fetch the token?
E.g
def get_csrf(request):
    response = JsonResponse({"detail": "CSRF cookie set"})
    response["X-CSRFToken"] = get_token(request)
    return response

Not sure how to proceed..
My Nuxt/Axios requests looks something like this:
const response =
    await this.$axios.$post("/api/portfolios/", stockData,
      { headers: { "X-CSRFToken": /* Need some value here.  */ }
    });

I can however get the cookie using nuxtServerInit in my Nuxt Store:
            async nuxtServerInit({commit}) {
                console.log(this.$cookies.get("csrftoken")) // this works, can store it in some state
            },

I can store the value from nuxtServerInit in a Nuxt store. However, whenever I logout, how do I make sure to extract the new csrftoken from the browser? The nuxtServerInit part above only works if I do a page reload, which isn't ideal.
Appreciate any guidance I can get.

A: Setup axios with default xsrfHeaderName and  xsrfCookieName values via nuxt plugin.
When configured, axios will include in request your csrf header with cookie value if it's present in cookies.

*

*in nuxt.config.js include your new plugin

// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
  '~/plugins/axios',
]

*create plugins/axios.js

There is the option to declare as global default config, or for a nuxt instance.

// content of plugins/axios.js
/*
// This is a global config declaration that works on any axios instance,
// meaning that if you just import axios from 'axios' in any place, you will get those.
// This will also work on the axios instance that nuxt creates and injects.

import axios from 'axios'

axios.defaults.xsrfHeaderName = 'x-csrftoken'
axios.defaults.xsrfCookieName = 'csrftoken'
*/
export default function ({ $axios }) {
  // This is a nuxt specific instance config, this will work in
  // everyplace where nuxt inject axios, like Vue components, and store
  $axios.defaults.xsrfHeaderName = 'x-csrftoken'
  $axios.defaults.xsrfCookieName = 'csrftoken'
}


text:
Q: ClassNotFoundException: SanitizerLogWrapper while starting WebSphere Application server with Liferay I've deployed Liferay 6.1 on WAS 8.5.5. While trying to start the server via Eclipse Juno, I'm getting a ClassNotFoundException which points to com.liferay.portal.kernel.log.SanitizerLogWrapper. Does someone know what the cause might be?
Here are the logs:
[8/6/15 9:09:39:152 EDT] 0000005a webapp        E com.ibm.ws.webcontainer.webapp.WebApp notifyServletContextCreated SRVE0283E: Exception caught while initializing context: {0}
                             java.lang.NoClassDefFoundError: com.liferay.portal.kernel.log.SanitizerLogWrapper
at com.liferay.portal.util.InitUtil.init(InitUtil.java:115)
at com.liferay.portal.spring.context.PortalContextLoaderListener.contextInitialized(PortalContextLoaderListener.java:169)
at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:1678)
at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:414)
at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:88)
at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:169)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:749)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:634)
at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:426)
at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:718)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1175)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1370)
at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:639)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:968)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:774)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2182)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:445)
at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:388)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:116)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$CUInitializer.run(CompositionUnitMgrImpl.java:994)
at com.ibm.wsspi.runtime.component.WsComponentImpl$_AsynchInitializer.run(WsComponentImpl.java:502)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)
Caused by: java.lang.ClassNotFoundException: com.liferay.portal.kernel.log.SanitizerLogWrapper
at java.net.URLClassLoader.findClass(URLClassLoader.java:599)
at com.ibm.ws.bootstrap.ExtClassLoader.findClass(ExtClassLoader.java:204)
at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:743)
at java.lang.ClassLoader.loadClass(ClassLoader.java:720)
at com.ibm.ws.bootstrap.ExtClassLoader.loadClass(ExtClassLoader.java:119)
at java.lang.ClassLoader.loadClass(ClassLoader.java:690)
at com.ibm.ws.classloader.ProtectionClassLoader.loadClass(ProtectionClassLoader.java:62)
at com.ibm.ws.classloader.ProtectionClassLoader.loadClass(ProtectionClassLoader.java:58)
at com.ibm.ws.classloader.CompoundClassLoader.loadClass(CompoundClassLoader.java:584)
at java.lang.ClassLoader.loadClass(ClassLoader.java:690)
at com.ibm.ws.classloader.CompoundClassLoader.loadClass(CompoundClassLoader.java:584)
at java.lang.ClassLoader.loadClass(ClassLoader.java:690)
... 23 more

A: It seems you are missing portal-kernel.jar or portal-service.jar
More here

A: Liferay requires some classes on the global classpath. You can download them as so called "dependencies". Among them is portal-service.jar
If you deployed Liferay according to the Administration Guide for Websphere 8.5, everything should run (I'm linking the 6.2 version of the docs, but I expect no big changes. If you're on CE, you should update anyways, because 6.1 CE is discontinued for quite a while now)


text:
Q: Deploying React App to Heroku / GitHub pages changes styles / CSS I'm relatively new to coding, but I've made half a dozen full-stack apps and in each I've noticed that whenever I deploy an app to Heroku / GitHub Pages, every single element on the page gets smaller than what they were on my localhost. For example, a Navbar will go from say 50px to 30px. The font size for an element will go from 20px to 12px. I have no idea why, I'm guessing the index file isn't reading the CSS files properly when it's being rendered and defaulting to something, but it's irritating and I can't plan how to style my pages because I don't know what the finished product is going to look like. Does anyone have any sort of answer?
My portfolio site on localhost: everything is the size I want it.

My portfolio site deployed on GitHub pages: everything is smaller.

A: On localhost you're zoomed in, do you see that icon at the left side of your address bar? Just reset your zoom on localhost with CMD+0, or on PC I guess it's Ctrl+0 and you'll have a consistent look.
Good luck with your site (:


text:
Q: List implementation in ruby? I'm a bit struggling with the understanding of the Array class in Ruby. I have seen on Google
that an Array class is actually more of a list, but I can't seem to find how it actually works.
I am really concerned with performance issues as I have to deal with large sorted lists, and
I don't want to step over the whole array to add a single element to it.
So I was wondering if there were any real and clear implementation of a list (as in caml for instance), and I am also looking for a good documentation about how Array's method are implemented, regarding optimization matters.
Thanks!

A: A Ruby array offers a full list interface:

*

*push/<< for adding element at the end

*each provides an iterator for list traversal

*sort lets you sort the items with an optional block for a custom comparator

*...

So there's no apparent need to have a special List class or Module - take Java for example, we end up using ArrayList if we need a List all the time because it gives us good performance and the additional benefit of accessing elements by their index. So Ruby (similar to other languages such as Python, PHP or Lua) tries to keep things simple with regards to collection types by offering just three types - Array, Hash and Set - therefore with a rich interface that makes it easy to emulate other collection types such as a List, Queue or Deque etc.
If you'd like to know details about the implementation, I would recommend simply downloading the Ruby sources and investigating the corresponding files (for MRI it's array.c in the top-level directory)  .


text:
Q: Is it dangerous to have a Node.js file on a server that requires my dotenv file? I have a Node.js file that runs at build time and I load in my dotenv file like so:
const env = require("dotenv").config();

I am wondering if adding my dotenv file like this is dangerous? I want to make sure that my dotenv variables are not accessible on the web or through GitHub.


text:
Q: Is passing a redux store & dispatch via thunk a reasonable alternative to directly importing the redux store into a file? According to this, Redux FAQ: Can or should I create multiple stores? Can I import my store directly, and use it in components myself?, one should not import their store directly for use.
In React Components, we could use the connect wrapper.
I have a Client I want to manage all communication with and logic regarding a 3rd party service. Ideally, this client would be able to dispatch and read state from the store.
To avoid directly importing the store, I plan to leverage thunk and do the following:
Action Creator:
export function initializeClient() {
  return async (dispatch, getState) => {

    const { token } = await Api.createToken();

    return Client.initialize(token, dispatch, getState);
  }
}

Within the client, I would essentially do this:
Client
class Client {
  dispatch;
  getState;

  async initializeClient(token, dispatch, getState) {
    this.dispatch = dispatch;
    this.getState = getState;

    // Process token
  }

  // Other functions...
}

What I did might be an anti-pattern, but I feel like it would allow for one to still do server-side rendering and gets past importing the store directly.
My biggest concern is keeping a reference to dispatch and getState for so long, but I can't imagine the functions ever change... so I think that should be fine?

A: It'll run, I guess, but I would recommend putting that client into a custom middleware instead:

Middleware are the right place for persistent connections like websockets in a Redux app, for several reasons:

*

*Middleware exist for the lifetime of the application

*Like with the store itself, you probably only need a single instance of a given connection that the whole app can use

*Middleware can see all dispatched actions and dispatch actions themselves. This means a middleware can take dispatched actions and turn those into messages sent over the websocket, and dispatch new actions when a message is received over the websocket.

*A websocket connection instance isn't serializable, so it doesn't belong in the store state itself


text:
Q: Android PayPal Daylight saving time I have the paypal sdk working perfect in android application using android studio. But the response from a transaction is giving me the time one hour behind the correct time. Here is the logcat where its outputting the wrong time:
{
  "response": {
    "state": "approved",
    "id": "PAY-***********",
    "create_time": "2015-04-29T11:17:42Z",
    "intent": "sale"
  },
  "client": {
    "platform": "Android",
    "paypal_sdk_version": "2.0.2",
    "product_name": "PayPal-Android-SDK",
    "environment": "sandbox"
  },
  "response_type": "payment"
}

Any ideas how i could correct this?


text:
Q: Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model? I've got a couple django models that look like this:
from django.contrib.sites.models import Site

class Photo(models.Model):
    title = models.CharField(max_length=100)
    site = models.ForeignKey(Site)
    file = models.ImageField(upload_to=get_site_profile_path)

    def __unicode__(self):
        return self.title

class Gallery(models.Model):
    name = models.CharField(max_length=40)
    site = models.ForeignKey(Site)
    photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} )

    def __unicode__(self):
        return self.name

I'm having all kinds of fun trying to get the limit_choices_to working on the Gallery model.  I only want the Admin to show choices for photos that belong to the same site as this gallery.  Is this possible?

A: Yes.  You need to override the form that admin uses for the Gallery model, then limit the queryset of the photos field in that form:
class GalleryAdminForm(django.forms.ModelForm):

    class Meta:
        model = Gallery

    def __init__(self, *args, **kwargs):
        super(GalleryAdminForm, self).__init__(*args, **kwargs)
        self.fields['segments'].queryset = Photo.objects.filter(site=self.instance.site)

class GalleryAdmin(django.contrib.admin.ModelAdmin):
    form = GalleryAdminForm

django.contrib.admin.site.register(Gallery, GalleryAdmin)

A: I would delete site field on my Photo model and add a ForeignKey to Gallery. I would remove limit_choices_to from photos fields on Gallery model.
Because you are using ForeignKeys to Sites, that means sites don't share galleries and photos. Therefore having those I mentioned above is already useless.
class Photo(models.Model):
    title = models.CharField(max_length=100)
    gallery = models.ForeignKey(Gallery, related_name='photos')
    file = models.ImageField(upload_to=get_site_profile_path)

    def __unicode__(self):
        return self.title

class Gallery(models.Model):
    name = models.CharField(max_length=40)
    site = models.ForeignKey(Site)

    def __unicode__(self):
        return self.name

Once you set the site on a gallery all its photos will inherit this property. And the site will be accessible as photo_instance.gallery.site:
@property
def site(self):
    return self.gallery.site

This should work as if you had a site field. But I haven't tested it.
Things change or course, if you decide that a gallery or a photo can appear in multiple sites.

A: According to the docs, "limit_choices_to has no effect when used on a ManyToManyField with an intermediate table".  By my reading, that means it has no effect at all, because ManyToManyFields use intermediate tables...
I haven't tried to make it work in the Admin site, but from your own views, you can create a form and override the queryset used to populate the list of choices:
form.fields["photos"].queryset = request.user.photo_set.all()


text:
Q: how do find the line lies on another line I have Line $A$ with points $(1,1)$ and $(8,8)$ and another Line $B$ with points $(2,2)$ and $(4,4)$.  I would like to prove Line $B$ lies on Line $A$.  How can I do this?

A: The points are all on the line $y=x$.

A: In a general version of your situation, with one line determined by points $A$ and $B$ and a second line determined by points $C$ and $D$, the idea from anonymous's answer is a good place to start.  Rather than using the quotient formulation in that answer, which might have division by zero, let's rewrite that with products: $$(x-x_1)(y_2-y_1)=(y-y_1)(x_2-x_1)$$
Now, use that to write an equation for the first line, through $A(x_1,y_1)$ and $B(x_2,y_2)$.  Given that equation, any points $(x,y)$ that satisfy the equation are on the line.  Test points $C$ and $D$ in that equation.  If both $C$ and $D$ satisfy the equation for the line through $A$ and $B$, then all four points are on the same line, so the line through $C$ and $D$ is the same as the line through $A$ and $B$.
In this way, we avoid having to write a second equation and determine whether or not that equation is equivalent to the first equation; instead, we look to see if the points that would determine the second equation satisfy the first equation.

A: Hint:  Take the perpendicular distance and prove that the distance is 0.
Use the 2 point slope form.Equation of the line passing through $(x_{1},y_{1})$ and $(x_{2},y_{2})$ is given bye $$\frac{x-x_{1}}{x_{2}-x_{1}}=\frac{y-y_{1}}{y_{2}-y_{1}}$$ and observe that they are same.

A: In general you can use a determinant expression
$$\begin{vmatrix}x_1&y_1&1\\x_2&y_2&1\\x_3&y_3&1\end{vmatrix}=0$$
to verify that three points $(x_i,y_i)$, $i=1\dots 3$ are collinear. As Hans points out though, that the coordinates of all four points that you have have their abscissas and ordinates identical makes them obviously collinear.


text:
Q: VS Annoying CSS Alert <link href="http://www.../default.css" rel="stylesheet" type="text/css" />

Could not edit 'http://...' because it is not in the Web site.
I get this error box every five minutes, how do I get it to stop telling me this?

A: Well, seems like it's because you're including an href that points to a URL, instead of a relative web path.
Instead of
<link href="http://www.mysite.com/styles/default.css" rel="stylesheet" type="text/css"/>

use
<link href="/styles/default.css" rel="stylesheet" type="text/css"/>

Also, make sure your closing
/>

is valid in terms of your Doctype.

A: <link runat="server" id="defaultCss" rel="stylesheet" type="text/css"/>

and on your code behind
defaultCss.attributes.add("href","http://www..../default.css");

if your css is in your website then you can use
ResolveUrl("~/default.css")

to get the url
or probably best practice is to add it to your app theme folder http://msdn.microsoft.com/en-us/library/ykzx33wh.aspx and then not only will it be automatically added but you'll get intellisense


text:
Q: Creating Gallery for app with subFolders too? I want to add gallery fragment or Activity to my app so i can show the downloaded files such as images and videos.
I am currently using this code for the purpose :
Gallery Class :
class GalleryClass extends AsyncTask < Void, Void, Void > {
    public static ArrayList < String > f = new ArrayList < > ();

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Gallery.gridView.setAdapter(new ImageAdapter(Gallery.context));
    }

    @Override
    protected Void doInBackground(Void...voids) {
        File dir = new File(String.valueOf(Environment.getExternalStoragePublicDirectory("myFolder")));
        File[] FileList = dir.listFiles();
        if (FileList != null) {
            for (File aFileList: FileList) {
                f.add(aFileList.getAbsolutePath());
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        f.clear();
    }

    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        ImageAdapter(Context context1) {
            mContext = context1;
        }

        @Override
        public int getCount() {
            return f.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new ViewGroup.LayoutParams(230, 230));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(0, 0, 0, 0);
            } else {
                imageView = (ImageView) convertView;
            }
            Glide.with(Gallery.context).load("file://" + f.get(position))
                .apply(new RequestOptions()
                    .placeholder(R.drawable.)
                    .error(R.drawable.ic_error)
                )
                .into(imageView);
            return imageView;
        }
    }
}

Gallery Fragment :
    public Gallery() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_gallery, container, false);
        gridView = view.findViewById(R.id.gv);
        context = getActivity();
        GalleryClass process = new GalleryClass();
        process.execute();
        return view;
    }
}

The above code is working fine and it's loading images from the "MyFolder" but the MyFolder contains subfolders too and it is showing the errorplaceholder not the subfolder containing the images, and i want to show that subfolders too in the same view and when i click on that subfolder it will show the images which the folder contains.
How can i achieve same ?

A: This will enlist all folder and subfolder containing png, jpg ,mp4 files.
    String root_sd = Environment.getExternalStoragePublicDirectory("myFolder").toString();
    File file = new File(root_sd);
    File list[] = file.listFiles();

    for (int i = 0; i < list.length; i++) {
        File  mFile = new File(file, list[i].getName());
        File dirList[] = mFile.listFiles();
        if(dirList == null) continue;
        for (int j = 0; j < dirList.length; j++) {
            if(dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".png")||dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".jpg")||dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".mp4")){
                f.add(list[i].getName());
                break;
            }
        }

    }

A: Use this:
File f = new File(path);
File[] files = f.listFiles();
for (File inFile : files) {
    if (inFile.isDirectory()) {
        // is directory
    }
}


text:
Q: How do I make this sentence use a true past tense? Here is a sentence that confounds even me

Sir Jony Ive, KBE oversees the design engineering of the first iPhone in 2007 and all of its versions ever since.

What would be the right tense form for oversees here?

A: One possible conjugation is "has overseen," which changes the verb tense of the sentence from present to present perfect. The present perfect tense indicates that the subject both performed the verb in the past and continues to perform the verb (Sir Ive oversaw design engineering and still oversees design engineering).
Another option is to make your predicate compound (with two verbs).

Sir Jony Ive, KBE, oversaw the design engineering of the first iPhone in 2007, and continues to manage designs of Apple products to this day.

Also consider rewording the sentence to better group the objects.

Sir Jony Ive, KBE, has overseen the design engineering of every iPhone since its inception in 2007.


text:
Q: WCF Service Reports the Wrong DNS Identity from an X509 Certificate I'm having an odd problem relating to the service certificate for an IIS-hosted WSHttp WCF service.
This service uses message security with certificate authentication for both client and server. The service is hosted at a url similar to this:
http://services.mydomain.com/client.svc

The service's certificate has a subject name of:
CN = services.mydomain.com
OU = Domain Control Validated
O = services.mydomain.com

And a Subject Alternative Name of:
DNS Name=services.mydomain.com
DNS Name=www.services.mydomain.com

However, when the WCF client connects, the service reports back a DNS identity of www.services.mydomain.com, rather than the subject name of services.mydomain.com. This causes the WCF client to reject the response since it's connecting to services.mydomain.com and is expecting that to be the name that comes back.
The site that contains this application has both HTTP and HTTPS bindings, but neither of them have host names (it accepts all connections). What can I change to get the service to report the right identity?
What can I change to get the WCF service

A: For others who might be having this issue (especially with GoDaddy-issued certificates like mine, which have the forced www. prefix in the alternative name), there is a known bug in WCF that causes it to use the last DNS name in the Subject Alternative Name as the identity. The workaround, unfortunately, seems to be specifying the www. prefix as the identity for the client's endpoint.


text:
Q: Kubernetes Ingress path rewrite dosen't work as expected I have an ingress, defined as the following:
Name:             online-ingress
Namespace:        default
Address:
Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
  Host          Path  Backends
  ----          ----  --------
  jj.cloud.com
                /online/(.*)   online:80 (172.16.1.66:5001)
                /userOnline    online:80 (172.16.1.66:5001)
Annotations:    nginx.ingress.kubernetes.io/rewrite-target: /$1
Events:
  Type    Reason          Age                From                      Message
  ----    ------          ----               ----                      -------
  Normal  AddedOrUpdated  29m (x4 over 74m)  nginx-ingress-controller  Configuration for default/online-ingress was added or updated

If I test it with no rewrite, it's ok.
curl -X POST jj.cloud.com:31235/userOnline -H 'Content-Type: application/json' -d '{"url":"baidu.com","users":["ua"]}'
OK

However, if I try to use rewrite, it will fail.
curl -X POST jj.cloud.com:31235/online/userOnline -H 'Content-Type: application/json' -d '{"url":"baidu.com","users":["ua"]}'

<title>404 Not Found</title>

404 Not Found

nginx/1.21.3

And it will produce the following error logs:
2021/11/03 10:21:25 [error] 134#134: *63 open() "/etc/nginx/html/online/userOnline" failed (2: No such file or directory), client: 172.16.0.0, server: jj.cloud.com, request: "POST /online/userOnline HTTP/1.1", host: "jj.cloud.com:31235"
172.16.0.0 - - [03/Nov/2021:10:21:25 +0000] "POST /online/userOnline HTTP/1.1" 404 153 "-" "curl/7.29.0" "-"

Why the path /online/userOnline doesn't match /online/(.*) and rewrite it to /userOnline? Or are there some other errors?
Here is the yaml:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: online-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  rules:
    - host: jj.cloud.com
      http:
        paths:
          - path: /online(/|$)/(.*)
            pathType: Prefix
            backend:
              service:
                name: online
                port:
                  number: 80
          - path: /userOnline
            pathType: Prefix
            backend:
              service:
                name: online
                port:
                  number: 80
  ingressClassName: nginx

When I checked the generated nginx config, I found (default-online-ingress.conf):
location /online(/|$)/(.*) {

It seems lost of the modifier for regex match, like this:
location ~* "^/online(/|$)/(.*)" {

If it's true, how to make rewrite take effect and generate correct nginx config?

A: If I understood your issue correctly, you have a problem with captured groups.
According to Nginx Rewrite targets it seems to me,

*

*your patch should be path: /online(/|$)(.*)

*your rewrite-target: should be rewrite-target: /$2

*in addition, if you use nginx ingress, I believe you should specify that in annotation section as kubernetes.io/ingress.class: nginx

yaml:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: online-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  rules:
    - host: jj.cloud.com
      http:
        paths:
          - path: /online(/|$)(.*)
            pathType: Prefix
            backend:
              service:
                name: online
                port:
                  number: 80
          - path: /userOnline
            pathType: Prefix
            backend:
              service:
                name: online
                port:
                  number: 80
  ingressClassName: inner-nginx


text:
Q: Java output XML file and CDATA I am having a problem with the javax.xml.transform.Transformer class and its setOutputProperty method. I'm trying to get a XML output
   <name>
  <text>XXXXXXXXXX</text>
</name>
<questiontext format="html">
  <text><![CDATA[YYYYYYYYYYY]]></text>
</questiontext>

But using the:
        Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "text");

causes for the both of text nodes to be embedded by CDATA tags like so:
    <name>
  <text><![CDATA[XXXXXXXXXX]]></text>
</name>
<questiontext format="html">
  <text><![CDATA[YYYYYYYYYYY]]></text>
</questiontext>

So i guess i need a way to specify the parent of the text element but i haven't found a way to do so and the javadocs don't specify which notation is used. Also i am not in a position to change the output XML format.

A: You can't - the OutputKeys.CDATA_SECTION_ELEMENTS output property corresponds to the XSLT cdata-section-elements attribute of <xsl:output>, and that only allows you to define the elements in terms of QNames, not match expressions.
But it shouldn't matter since <foo>text</foo> and <foo><![CDATA[text]]></foo> are identical as far as an XML parser is concerned.


text:
Q: How to create directory in docker image? I tried mkdir -p it didn't work.
I have the following Dockerfile:
FROM jenkins/jenkins:2.363-jdk11

ENV PLUGIN_DIR /var/jenkins_home/plugins

RUN echo $PLUGIN_DIR

RUN mkdir -p $PLUGIN_DIR

RUN ls $PLUGIN_DIR

# WORKDIR /var/jenkins_home/plugins # Can't use this, as it changes the permission to root
# which breaks the plugin installation step
# # COPY plugins.txt /usr/share/jenkins/plugins.txt
# # RUN jenkins-plugin-cli -f /usr/share/jenkins/plugins.txt --verbose
#
#
# # disable the setup wizard as we will set up jenkins as code
# ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false
#
# ENV CASC_JENKINS_CONFIG /configs/jcasc.yaml

The build fails!
docker build -t jenkins:test.1 .
Sending build context to Docker daemon   51.2kB
Step 1/5 : FROM jenkins/jenkins:2.363-jdk11
 ---> 90ff7cc5bfd1
Step 2/5 : ENV PLUGIN_DIR /var/jenkins_home/plugins
 ---> Using cache
 ---> 0a158958aab0
Step 3/5 : RUN echo $PLUGIN_DIR
 ---> Running in ce56ef9146fc
/var/jenkins_home/plugins
Step 4/5 : RUN mkdir -p $PLUGIN_DIR
 ---> Using cache
 ---> dbc4e12b9808
Step 5/5 : RUN ls $PLUGIN_DIR
 ---> Running in 9a0edb027862

I need this because Jenkins deprecated old plugin installation method. The new cli installs plugins to /usr/share/jenkins/ref/plugins instead.
Also:
+$ docker run -it --rm --entrypoint /bin/bash --name jenkins jenkins:test.1
jenkins@7ad71925f638:/$ ls /var/jenkins_home/
jenkins@7ad71925f638:/$

A: The official Jenkins image on dockerhub declare VOLUME /var/jenkins_home, and subsequent changes to that directory (even in derived images) are discarded.
To workaround, you can execute mkdir as ENTRYPOINT.
And to verify that its working you can add an sleep to enter into the container and verify. It work !.
FROM jenkins/jenkins:2.363-jdk11

ENV PLUGIN_DIR /var/jenkins_home/plugins

RUN echo $PLUGIN_DIR

USER root

RUN echo "#!/bin/sh \n mkdir -pv $PLUGIN_DIR && sleep inf" > ./mkdir.sh

RUN chmod a+x ./mkdir.sh

USER jenkins

ENTRYPOINT [ "/bin/sh", "-c", "./mkdir.sh"]

after

*

*docker build . -t <image_name>

*docker run -d <image_name> --name <container_name>

*docker exec -it <container_name> bash
and you will see your directory
Sources:

*

*https://forums.docker.com/t/simple-mkdir-p-not-working/42179

*https://hub.docker.com/_/jenkins


text:
Q: The use of LVM over JBOD or RAID, is possible or not recommended? I am installing a 5 node Cassandra installation and will have 10 SSD 1.9 TB drives available per node. I want to use LVM to combine the 10 drives and distribute the disk space needed for each node.
The only documentation that I can find for Cassandra says JBOD or RAID. Can I use LVM or is that going to cause issues within Cassandara?
This is more of an informational question before I get started, I haven't actually tried anything yet.

A: Yes, you can use LVM, and we have done so with one of our clusters. If using LVM, be sure the devices are striped instead of linear. If you use linear, the first device will get consumed, then the second, then the third, etc. So, many devices could be sitting idle while others very busy. The downside to using LVM in striped mode is that if you have to modify the configuration (either grow or shrink the LVM size), you can't (i.e. you can't expand a striped volume). We have also used JBOD as well. With JBOD, you'll have directories duplicated on every device and sometimes sstables will reside on one v.s. the other - unpredictable and somewhat "messy". As sstables reside on a device, you don't really get "striping" per say, either. sstables are attempted to be distributed evenly across the devices. Also, as the individual devices are smaller, you could run into a space/compaction problem if there is not enough room on, say, one of the devices to compact the sstables that exist. So for me, personally, I would choose LVM as it's much more clean. I believe you might see some slight overhead with using LVM as I believe LVM may batch up some operations before performing them, but it hasn't seemed significant to me. To me, LVM is a bit less "messy".
-Jim


text:
Q: Combine Dic values less than x% to a single other slice piechart Hello I have my datadict as below
pDict = {'"Streptococcous targeted"': 678000 , '"s.coccous file read"': 6780 , '"Mycobacterium Collection being analysed"': 80 , '"Mycobacterium Collection being analysed"': 8560 , '"S. viridans encountered "':450 , '"S. thermophilus Analysis intiated"':300 }

    labels = sorted(pDict.keys())
    sizes = pDict.values()
    k = len(pDict.keys())

    # Build Pie chart
    list = plt.cm.gist_rainbow(np.linspace(0, 1, k))
    ax1 = fig.add_subplot(1,1,1,axisbg = 'grey')
    ax1.pie(sizes, labels = labels, colors = list,
        autopct='%1.1f%%', startangle=90)

I would like to combine the dic values less than 10 % as Others and plot them in a pie chart using pyplot how can i combine the  values less than 10% to others
Output pie graph should contain the results as below :
'"Streptococcous targeted"': 678000 , '"s.coccous file read"': 6780 ,  '"Mycobacterium Collection being analysed"': 8560 , '"others" :800

Thanks

A: You just need to filter pDict first, like this:
psum = sum(pDict.values())
pthreshold = psum * 0.1

includedict = dict(k,v for k,v in pDict.items() if v >= pthreshold)
others = dict(k,v for k,v in pDict.items() if v < pthreshold)

Then everything else the same.
There might be a way to do this in one step, not sure, but that works.


text:
Q: Error when trying to copy variable in constructor of a class I'm using wxWidgets, but I think this to my question there is no difference.
The problem is that I need to copy and keep in a different place the memory the socketConnect, when initialization the threadReadPacket in threadWaitConnection::Entry.
I'm currently trying to pass this value by the constructor, but I can not.
Some returns error messages:
main.cpp:97:70: error: within this context
         threadReadPacket *thread = new threadReadPacket(socketConnect);
                                                                      ^
main.cpp:22:5: error:   initializing argument 1 of 'threadReadPacket::threadReadPacket(wxSocketBase)'
     threadReadPacket(wxSocketBase setSocket) {
     ^

Code:
/* Thread */
// threadReadPacket
class threadReadPacket : public wxThread {
public:
    threadReadPacket(wxSocketBase setSocket) {
        socket = setSocket;
    };
    virtual ~threadReadPacket();

    virtual void *Entry();

private:
    wxSocketBase socket;
};

threadReadPacket::~threadReadPacket() {

}

threadReadPacket::ExitCode threadReadPacket::Entry() {
    /* [...]
    Lots and lots of lines of code
    [...] */
}

// threadWaitConnection
class threadWaitConnection : public wxThread {
public:
    threadWaitConnection(wxSocketServer *setSocket) {
        socket = setSocket;
    };
    virtual ~threadWaitConnection();

    virtual void *Entry();

private:
    wxSocketServer *socket;
};

threadWaitConnection::~threadWaitConnection() {

}

threadWaitConnection::ExitCode threadWaitConnection::Entry() {
    wxPrintf("Waiting for connection...\n");
    wxSocketBase socketConnect;
    socket->AcceptWith(socketConnect, true);

    if (socketConnect.Ok()) {
        wxPrintf("Success on connect\n");
        threadReadPacket *thread = new threadReadPacket(socketConnect);

        if (thread->Run() != wxTHREAD_NO_ERROR) {
            wxPrintf("Can't start thread!");
            return NULL;
        }
    } else {
        wxPrintf("Not connected\n");
        return NULL;
    }

    // Finish
    socketConnect.Close();

    return NULL;
}

A: See this:
/usr/include/wx-3.0-unofficial/wx/socket.h:303:29: error: 'wxSocketBase::wxSocketBase(const wxSocketBase&)' is private
     wxDECLARE_NO_COPY_CLASS(wxSocketBase);

This means the socket object can't be copied since it's copy constructor is private.
You code should keep a reference to the socket object instead (or a pointer).

A: Do not know if it was the most elegant solution, but it was the only one that worked.
I copied the memory of the socket in the heap and passed her position to the constructor.
That way I can store multiple socket and uses them way indepedent.


text:
Q: what is the difference betweeen Tcp protocol and Remote Procedure Call? can anyone please explain which protocol is more scalable and what the difference is between

*

*TCP (TRANSMISSION CONTROL PROTOCOL),and

*RPC(REMOTE PROCEDURE CALL).

A: RPC - Remote Procedure Call basically is a form of inter-process communication that allows one program to directly call procedures in another program either on the same machine or another machine on the network.
For more details see the wikipedia article: Remote procedure call
RPC runs on top of (uses) TCP. TCP allows computers to send arbitrary length data to each other with guaranteed delivery.  RPC operates at the same level as POP, SMTP, and other protocols.  Those protocols also run on top of TCP.
TCP is a lower level protocol.  Since RPC runs on top of TCP your question about scalability is not relevant.


text:
Q: Normalising vhost name from varnish for statsd The setup
I am collecting statistics from Varnish with Logstash, which is configured to increment statsd counters based on the vhost in the server logs and the result code.  I also have carbon creating whisper archives for graphite.
I'm reading logs from varnishncsa which is configured to add vhost and request disposition to the standard logs:
VARNISHNCSA_LOG_FORMAT="%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\" %{Host}i %{Varnish:hitmiss}x"

My logstash shipper config looks like this:
input {
  file {
    path => "/var/log/varnish/varnishncsa.log"
    type => varnish
  }
}

filter {
  grok {
    type => varnish
    pattern => "%{COMBINEDAPACHELOG} %{NOTSPACE:vhost} %{WORD:varnish_handling}"
    pattern => "%{COMBINEDAPACHELOG}"
  }

  mutate {
    rename => [ 'response', 'status' ]
  }
}

output {
  statsd {
    type => varnish
    host => "my-statsd-host"
    port => 8125
    sender => "%{@fields.vhost}"
    increment => "varnish.response.%{@fields.status}"
    increment => "varnish.handling.%{@fields.varnish_handling}"
  }
}

The problem
Hundreds of distinct counters are being created by carbon due to variations in the domain entered into users' browsers.  So, for example, I have
www_mywebsite_com
WWW_MyWebsite_Com
www_mywebsite_net    <-- an alias
...etc...

Obviously these are then missed by my graphs, which only look at statistics under the vhost's canonical name.
What I'd like is for some canonicalising process to happen beforehand.  I can write a script to take a 'raw' domain and spit out a 'real' vhost name, but I'm not sure how to integrate that.  Do I put it in the logstash config, or in statsd, or carbon?  Could I do something with carbon's storage aggregation feature?
Update:  I've worked around the worst cases by running carbon's aggregator daemon in front of the cache, and adding rules to rewrite-rules.conf.  However, there's very little documentation for that file, and I can't do more powerful things like smash everything down to lowercase.

A: you can lowercase a field with the mutate filter:
filter {
  mutate {
    lowercase => [ "fieldname" ]
  }
}

Logstash 1.1.13 Docs
Cheers,
Jan


text:
Q: Tooltip in .Net I have a DataGridView in a Winforms application containing a collection of items. Each item has an image and various other details. I know it is possible in WPF, but can you get a tooltip to display an image and a more structured set of details then just plain text?
Thanks.

A: You'd have to draw it yourself, look at ToolTip.OwnerDraw.
http://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.ownerdraw.aspx


text:
Q: replacing  elements with an image using jQuery I am having difficulty replacing a string (URL) with an image using jquery.  I want function to run on page load and replace a text string with an image. I need it to work on many different "strings" contained in <event-description>
http://example.com/pageone.html
 </event-description>on the page. This is what I have:
jQuery( document ).ready(function( $ ) {

       $('.event-description p').each(function () {

       string = $(this).text('http://example.com/pageone.html');
       $(this).html('');

       string = $(this).text('http://example.com/pagetwo.html');
       $(this).html('');

    });

});

Any Help would be appreciated!

A: You have to use a condition to compare the text of each p.

jQuery( document ).ready(function( $ ) {

  $('.event-description p').each(function () {

    var string = $(this).text();

    if($(this).text() == 'http://example.com/pageone.html'){
      $(this).html('');
    }

    if($(this).text() == 'http://example.com/pagetwo.html'){
    $(this).html('');
    }
  });
});

http://example.com/pageone.html

http://example.com/pagetwo.html

A: This should get you going. Just keep in mind since I am using the same image in the loop, the image will be same for all the
 element. You can have an object mapping pointing to the exact image you need in there to make it dynamic or use data attribute which is recommended.
See below:

, data-imgurl is image(logo) name here
Note: This adds image inside the
 tag you have. If you want remove
 use   $(this).parent().html(...)

$(function(){ //shorhand for document.ready function (same as yours)
    $('.event-description p').each(function () {
           var $this = $(this);

           //take the current string present in `<p>` tag
           var currentString = $this.text();
           //get data attribute to get the image name
           var imgUrl = $this.data('imgurl');

           $(this).html('');
           //replace with image tag with alt attribute as previous string
    });
});

http://example.com/pageone.html

http://example.com/pagetwo.html

A: You can use .replaceWith( function )

$('.event-description p').replaceWith(function(idx, txt) {
  return $('', {width: "75", src: txt.trim(), alt: txt.trim()});
})

http://example.com/pageone.html

http://example.com/pagetwo.html


text:
Q: OpenCV Object Detection Bounding Box I am working on Real Time object Detection using SVM in OpenCV. My objects include, book, mug, box, monitor and negative training samples.

*

*Feature Detector - SURF

*Sample of Each Positive Images - 200 each (acquired from Web)

*Negative Sample - 400 images

After training SVM I can correctly recognise the frame containing the object. But I am unable to place a correct bounding box around the object.
For a single object and a scene image, http://docs.opencv.org/doc/tutorials/features2d/feature_homography/feature_homography.html this tutorial from OpenCV gives insight on how to perform detection and placing of the bounding box.
Now in my case, I have 200 cropped image of the object, How can I determine the correct location and the size of the correct bounding box around the object in the environment. That is how I know which image from the training set is the best match.

A: If you now, from your SVM, which object is propably in the Image you can just use an Image that contains only your Object as "object image" and your current sample as "scene image".
Than you can follow the Example "Features2D + Homography to find a known object" (that you already mentioned) to find the Position of your Object in the Scene. If you want to draw only the Bounding Box (and not the matched features) just extract the Corner Points from your Object (Code from the Example):
 //-- Get the corners from the image_1 ( the object to be "detected" )
std::vector<Point2f> obj_corners(4);
obj_corners[0] = cvPoint(0,0);
obj_corners[1] = cvPoint( img_object.cols, 0 );
obj_corners[2] = cvPoint( img_object.cols, img_object.rows );
obj_corners[3] = cvPoint( 0, img_object.rows );

and convert them into scene coordinates
std::vector<Point2f> scene_corners(4);

perspectiveTransform( obj_corners, scene_corners, H);

assuming you have already computed the Homography Matrix H.
Now you have the Corner Point in Scene Coordinates and can simply draw the Lines between the Corner Points to get your Bounding Box (Code from the Example):
//-- Draw lines between the corners (the mapped object in the scene - image_2 )
  line( img_matches, scene_corners[0] + Point2f( img_object.cols, 0), scene_corners[1] + Point2f( img_object.cols, 0), Scalar(0, 255, 0), 4 );
  line( img_matches, scene_corners[1] + Point2f( img_object.cols, 0), scene_corners[2] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
  line( img_matches, scene_corners[2] + Point2f( img_object.cols, 0), scene_corners[3] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
  line( img_matches, scene_corners[3] + Point2f( img_object.cols, 0), scene_corners[0] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );

Important is that your "object_image" contains only the Object and nothing else.
If you want to get the best Sample from your Class you must compute scores for each sample. This can be done using the Method described in: "Probability Estimates for Multi-class Classification by Pairwise Coupling" from Wu et. al. which you can find here.
However this could be too slow for a real-time application.


text:
Q: Median based on number of entries instead of values I'm writing a computer program that provides some useful statistical information about files. Calculating the mean is trivial, and the mode at least has a simple definition, but the median is proving tricky. I remember its general definition from school, but there is some ambiguity.

Median: the "middle number".

But what does that mean? Is it the middle entry or the middle value?
The Wikipedia page for mean uses the sample data set 1, 2, 2, 6, 7, 8 and gives the median as 4 because the mean of the two middle entries (2 and 6) is 4.
But what about 6? The number 6 has the same number of values above (7,8) as it does below (1,2).
This is a pretty useful statistic as well. Is there a name for this?

A: The notion you are looking for is sample median (as opposed to population median).
Sort the sample values, respecting multiplicity. So if we got $7.8$ three times, we write it down $3$ times. One can use non-decreasing order or non-increasing order, it doesn't matter.
If the number of sample values is odd, say $2k+1$, then the sample median is the "middle" value, that is, the $(k+1)$-th value counting from the bottom (or top) of the sorted list.
If the number of sample values is odd, say $2k$, then the sample median is the ordinary average of the two "middle" values. the $k$-th and the $(k+1)$-th.


text:
Q: membership issue after online hosting I have a shopping cart asp.net application presently i manage login system by simply making a DB table with 2 field username and password and in my web.config file redirect all the user to login page by authentication and authorization tag
 <authentication mode="Forms" >
 <forms  defaultUrl="default.aspx" loginUrl="login1.aspx"   cookieless="AutoDetect"  ></forms>
      </authentication>
      <authorization>
        <deny users="?"/>
      </authorization>

and on my login page simply compare username/pwd entered by user with database entry and if the user is correct calling the function
FormsAuthentication.RedirectFromLoginPage(username, true);

that redirect the user to home page it works very fine on my local system and i have no issue.But recently i hosted my application online and there is some issue with my login system.When i login into the site its ok but after some time user is automatically thrown out of site to the login page and he has to login again.

A: It sounds like your users are bumping up against a cookie expiry. Add the following attributes to your <forms> element:
<forms defaultUrl="default.aspx" loginUrl="login1.aspx" cookieless="AutoDetect" slidingExpiration="true" timeout="60" />

By default, sliding expiration SHOULD be set to true, but if it's not, 30 minutes after a user logs in, their authentication will expire no matter if they've visited other site pages since that time. By default, the timeout period is also supposed to be set to 30 minutes from last refresh, so if your user is idle for 30 minutes, they will have to renew the authentication cookie in order to access secured content. You can extend this to whatever value you like, such as "60" in the above example.
You can find out more about these attributes at the MSDN reference page.


text:
Q: GET Request Blocked even though AllowGet is set in the controller I'm getting the following error returned intermittently from my several of my controllers:

"This request has been blocked because sensitive information could be
  disclosed to third party web sites when this is used in a GET request.
  To allow GET requests, set JsonRequestBehavior to AllowGet."

But in the return statement I do set JsonRequestBehavior to AllowGet
return Json(new {Success = true, Plan = populatedPlan}, JsonRequestBehavior.AllowGet);

I found the following article which describes a vulnerability when returning JSON with GET Requests.
https://haacked.com/archive/2009/06/25/json-hijacking.aspx/
I checked my code and some of the controllers were returning just a single JS array so I fixed those to return an object with the array assigned to a propery on that object. However, not all my controllers are doing this, like the one in my code snippet - that returns a JS object - but the response is still occasionally blocked.
How can I stop this error from happening?
[Edit] This is happening about 1 in every 200 requests. I'm just confused as to why it's happening when I'm already doing what the error message is explicitly telling me to do.

A: Make sure you don't have another JSON return without JsonRequestBehavior.AllowGet before reaching return Json(new {Success = true, Plan = populatedPlan}, JsonRequestBehavior.AllowGet);.