text:
Q: quick sort python recursion This is my quick sort code, the partition function works well, but I got a problem while calling the recursion. The pos changes every time it starts the function and then the list limits are change as well. How to fix that?
def partition(lst, start, end):

    pos=0
    if len(lst)<2:
        return
    for i in range(len(lst[start:end])):
        if lst[i] < lst[end]:
            lst[i],lst[pos]=lst[pos],lst[i]
            pos+=1

        elif i==(len(lst[start:end])-1):
            lst[end],lst[pos]=lst[pos],lst[end]

    return pos

def quick_sort_recursive(lst, start, end):

        pos=partition(lst, start, end)
    if start<=pos<=end :
        quick_sort_recursive(lst, start, pos-1)
        quick_sort_recursive(lst, pos+1, end)
    else:
        return lst

A: There are numerous problems in your code, here are some fixes just to make it work:
def partition(lst, start, end):
    pos = start                           # condition was obsolete, loop won't
                                          # simply run for empty range

    for i in range(start, end):           # i must be between start and end-1
        if lst[i] < lst[end]:             # in your version it always goes from 0
            lst[i],lst[pos] = lst[pos],lst[i]
            pos += 1

    lst[pos],lst[end] = lst[end],lst[pos] # you forgot to put the pivot
                                          # back in its place
    return pos

def quick_sort_recursive(lst, start, end):
    if start < end:                       # this is enough to end recursion
        pos = partition(lst, start, end)
        quick_sort_recursive(lst, start, pos - 1)
        quick_sort_recursive(lst, pos + 1, end)
                                          # you don't need to return the list
                                          # it's modified in place

Example:
example = [3,45,1,2,34]
quick_sort_recursive(example, 0, len(example) - 1)
print example

Gives:

python test.py
[1, 2, 3, 34, 45]

A: I think in a pure recursive implementation the partition aux function is not needed:
def quicksort_recursive(a):
    if len(a) == 0:
        return a
    p = len(a) // 2
    l = [i for i in a if i < a[p]]
    m = [i for i in a if i == a[p]]
    r = [i for i in a if i > a[p]]
    return quicksort_recursive(l) + m + quicksort_recursive(r)

A: Trivial example of Quick Sort algorithm:
*
###  QUICKSORT
A=[44,5,22,0,323,995,94,4,7,15]
def main():
    r=len(A)-1
    p=0
    Result=QuickSort(A,p,r)
    print(Result)
def QuickSort(A,p,r):

    if p<r:
        q=partition(A, p, r)
        QuickSort(A, p, q-1)
        QuickSort(A, q+1, r)
    return A
def partition(A,p,r):
    x=A[r]
    i=p-1
    for j in range(p,r):
        if A[j]<=x:
            i=i+1
            a,b=A.index(A[i]), A.index(A[j])
            A[a],A[b]=A[b],A[a]
    d,c=A.index(A[i+1]),A.index(A[r])
    A[c],A[d]=A[d],A[c]
    return i+1
main()

*

A: recursive Quicksort algorithm
def quick_sort(array):
    if len(array) < 2:
        return array
    else:
        pivot = array[0]
        less = quick_sort([i for i in array if i < pivot])
        greater = quick_sort([i for i in array if i > pivot])
        return less + [pivot] + greater

A: def qsort(array):
    if not array:
        return []

    p, *xs = array
    lesser = [x for x in xs if p<x]
    greater = [x for x in xs if p>=x]

    return qsort(lesser) + [p] + qsort(greater)

qsort([3, -5, 3, 5, 1, 7, 8, 2, -2])

The approach is not very different from Luis Sobrecueva. I would argue its slightly more pythonic.

A: ~Returning recursively the partitions~

def quick_sort(nums):
  less = []
  equal = []
  greater = []

  if len(nums) > 1: # array len greater than 1 the exe
    pivot = nums[len(nums) // 2] #pivot at mid point
    for i in nums:
      if i < pivot: less.append(i)
      elif i == pivot: equal.append(i)
      elif i > pivot: greater.append(i)
    return quick_sort(less) + equal + quick_sort(greater)
  else:
    return nums # else return array


text:
Q: Entering emoji fails in django + mysql even with utf8mb4_unicode_ci I'm trying to insert an emoji into my title column in my django + MySQL app. I already went into PhpMyAdmin and I did the following:

*

*changed the charset of the column to utf8mb4_unicode_ci

*inserted an emoji

But when I open this object in the django admin, the emoji is missing:

And if I try to enter the emoji and save, I get this exception:
MySQLdb._exceptions.OperationalError: (1366, "Incorrect string value: '\\\\xF0\\\\x9F\\\\x92\\\\xA9' for column 'title' at row 1")

What am I missing?

A: What's missing is the charset option for the mysql database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        ...
        'OPTIONS': {
            ...
            'charset': 'utf8mb4',
        },
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tkinter tips - Python - GUI I just started a COMP project (Intro course) where we have been learning Python and I'm planning to code a calendar and a task manager. I just started using Tkinter and the GUI didn't look as good I thought it could be. I was wondering if there any tips to improve GUIs that use Tkinter and whether there are other better (and free) alternatives.
Thank you!

A: When possible, use the ttk versions of the widgets, being specific as to what is being imported:
from tkinter.ttk import LabelFrame

To import the LabelFrame widget, as an example.
The ttk versions of the standard widgets behave similar to their tk cousins, with a few differences.  Certain options are not available, for example padx/pady/ipadx/ipady options get reduced to padding.  Since you're using 'os native' widgets, certain visual options wouldn't even make sense.


text:
Q: /usr/bin/sudo: Permission denied when calling sudo from sh script via telegra-cli with lua script Im trying to run my .sh scipt status.sh via a telegram message:
Ubuntu 20.04.1 LTS server
Telegram-cli with a lua script to action status.sh script
when i send the message "status" to my server via telegram it actions the status.sh script, in this script i have a bunch of stuff that gathers info for me and sends it back to telegram so i can see what the status of my server is, however (i recently did a fresh install of the server) for some reason if the script has a line of code starting with sudo i get:
line 38: /usr/bin/sudo: Permission denied
if i run the script from the command line ./status.sh it runs without any problem!? so im thinking its because it is being called from telegram or lua!?
example of code that generates the error: sudo ifconfig enp0s25 >> file
on the other hand this line works without a problem:
sudo echo Time: $(date +"%H:%M:%S") > file
/usr/bin has 0755 permission set
sudo has 4755 permission set

A: The following command
sudo ifconfig enp0s25 >> file

would not work if file requires root privilege to be modified.
sudo affects ifconfig but not the redirection.
To fix it:
sudo sh -c 'ifconfig enp0s25 >> file'

A: As mentioned in Egor Skriptunoff's answer, sudo only affects the command being run with sudo, and not the redirect.
Perhaps nothing is being written to file in your case because ifconfig is writing the output you are interested in to stderr instead of to stdout.
If you want to append both stdout and stderr to file as root, use this command:
sudo sh -c 'ifconfig enp0s25 >> file 2>&1'

Here, sh is invoked via sudo so that the redirect to file will be done as root.
Without the 2>&1, only ifconfig's stdout will be appended to file. The 2>&1 tells the shell to redirect stderr to stdout.
If file can be written to without root, this may simplify to
sudo ifconfig enp0s25 >> file 2>&1


text:
Q: textarea html tag not taking space between words I have a contact form with standard input fields, in which all fields working well but when i try to put something in message box (textarea input tag ) it is not taking space between two words..

A: In the file mb.bgndGallery.js, there is the following function:
keyboard:function(el){
            $(document).on("keydown.bgndGallery",function(e){
                switch(e.keyCode){
                    case 32:
                        if(el.opt.paused){
                            $.mbBgndGallery.play(el);
                            el.opt.paused=false;
                        }else{
                            el.opt.paused=true;
                            $.mbBgndGallery.pause(el);
                        }
                        e.preventDefault();
                        break;
     }
  });
}

Keystroke '32' is representing the 'spacebar' and this one is causing troubles. You either remove this case or disable the keyboard functionality of this plugin (at the top of the file).
$.mbBgndGallery ={
        name:"mb.bgndGallery",
        author:"Matteo Bicocchi",
        version:"1.8.0",
        defaults:{
            activateKeyboard:false

        }


text:
Q: Angle between unit vectors I need to find the angle between two unit vectors $\overrightarrow{m}$ and $\overrightarrow{n}$ if the vectors $\overrightarrow{p}=\overrightarrow{m}+2\overrightarrow{n}$ and $\overrightarrow{q}=5\overrightarrow{m}-4\overrightarrow{n}$ are perpendicular to each other.
I have no idea how to approach the problem. All I can think of from the presented information is that the angle between $\overrightarrow{p}$ and $\overrightarrow{q}$ is $\frac{\pi}{2}$ and that the angle between the two unit vectors is $cos(\overrightarrow{m}.\overrightarrow{n})$

A: Calculating the dot product we get
$$\vec{p}\cdot \vec{q}=5\vec{m}^2+10\vec{m}\cdot \vec{n}-4\vec{m}\cdot \vec{n}-8\vec{n}^2=0$$
We get $$\vec{m}\cdot \vec{n}=\frac{1}{2}$$

A: Since $p, q$ are perpendicular and $m, n$ have unit length,
$$ 0 = \langle p, q \rangle = \langle m + 2n, 5m - 4n \rangle = 5|m|^2-4\langle m,n\rangle + 10 \langle n, m\rangle - 8|n|^2  = -3 + 6 \langle m , n\rangle. $$
This, combined with the fact that
$$ \cos \alpha = \frac{\langle m, n \rangle}{|m||n|} = \langle m, n \rangle $$
should allow you to find the required angle $\alpha$.


text:
Q: When to add an op amp buffer to a voltage reference IC? The circuit below is from a TI reference design, but my question is generic. I'm generating a voltage reference to add a DC bias to an AC signal for ADC purpose. Could I use the output of the voltage reference IC, in this case LM4041, directly instead of making it passing through an op amp buffer? How do I decide that?

A:
Could I use the output of the voltage reference IC, in this case
  LM4041, directly instead of making it passing through an op amp
  buffer?

Not if you want low noise and some decent degree of accuracy. For low noise note the RC on the output of the op-amp - it has a low pass frequency of about 16 kHz so, any noise above that coming from the op-amp or voltage reference is progressively attenuated. There's no reason why the 100 nF couldn't be 10 uF (if the op-amp can handle the RC without oscillating) and get a 3 dB noise point of 160 Hz (even better for noise).
So, given that the LM4041 produces circa 20 uV RMS of wide-band noise it seems sensible to use an RC circuit.
I'm not a big fan of op-amp buffers because they can bring all sorts of errors to the party but the RC is a must in my book because it simultaneously keeps noise down and offers a low impedance to the ADC at frequencies above where the raw output from the 4041 can't deliver low impedance (look at figures 7 and 8 in the TI data sheet).


text:
Q: Which R and RStudio version to install for Windows 32 bit? I'm taking a course on R programming and it requires me to install "devtools" package. I was using Anaconda to learn Python and used the same to use R. But I wasn't able to install the package and came to know that Anaconda only supports certain versions of RStudio. So, now I'll have to download R and RStudio separately. My system info -
Windows edition - Windows 7 professional
System type - 32-bit OS
Can someone help me with the version of R and RStudio I should download now?
Thanks in Advance!

A: The last version of RStudio to support a 32-bit OS was 1.1.463. You can download it from here (scroll down until you find it).
You should be able to install the latest release of R from here, just make sure that you install the 32-bit version.
From experience, R/Rstudio 1.1.463 works OK on 32-bit computers, but you might run into som troubles, both with R itself and some packages that rely on newer versions of RStudio. You might find some help here should you experience troubles with R itself.
I hope this helps. But in any case, your best option would be to upgrade your system if possible.

A: As mentioned in jpiversen answer, your specs seem a bit outdated.
But RStudio luckily also has a cloud version, so you don't need to install anything.
You might want to look into that.


text:
Q: AngularJS: can't access object property from factory I have a beginner issue with my AngularJS very simple code: I'm trying to pass data from a factory to a controller and print the object returned to my view, here's my code:
angular.module('app').factory('blogFactory',function(){
   return {
        //EDIT
        post:{"author":"Bob","name":"smith","content":"some content"},
        read: function(){
            return this.post;
        }
   }
});

In the controller:
angular.module('app').controller('MainCtrl',['$scope','blogFactory'], function($scope, blogFactory){
   $scope.datas = blogFactory.read();
   console.log($scope.datas);});

When I console.log($scope.datas it logs the object fine. In the view I 'm unable to access the object's properties:

{{data.name}}
 //Doesn't display anything

{{data}}
     // Displays the object

Does anyone has any idea? Thanks in advance

A: You don't have any property called name in  $scope.datas
{"author":"Bob","content":"some content"}

You must be printing datas.author.
That's why
{{data.name}}
 doesn't display any data.
As per your factory code, post is an object. But in your view you are using

Which is not required. Just datas is enough to get that individual post

A: This code works fine I have tested it:
var app = angular.module('app',[])
app.factory('blogFactory',function(){
return {
    post:{"author":"Bob","content":"some content"},
    read: function(){
        return this.post;
    }
}
});

app.controller('MainCtrl', function($scope,blogFactory){
  alert();
$scope.datas = blogFactory.read();
console.log($scope.datas);
})

For the view:

{{data.name}}

{{data}}


text:
Q: Gradle Lombok constructor annotation fail I'm trying to use Lombok in Android Studio with no luck. I'm working on a git project and since the project decided to use Lombok I could not build it. The build fails on compileDevelopmentDebugJava task and the error message says:
Error:A default public constructor with no argument must be declared if a custom constructor is declared.
Error:Execution failed for task ':app:compileDevelopmentDebugJava'.
> Compilation failed; see the compiler error output for details.

It doesn't matter if I build in Android Studio or CMD, the error stays the same.
Versions used:

*

*Android Studio 1.2 beta 3

*Gradle 2.3.9

*Lombok 1.12

*Java JDK 1.7


text:
Q: d3.js: Passing data from parent to child nodes I am using d3 to make a stacked bar chart.
The data is an array with one object for each bar (e.g 'likes').  Then each object contains an array of values which drive the individual rectangles per bar:
data =  [{
          key = 'likes', values = [
            {key = 'blue-frog', value = 1},
            {key = 'goodbye', value = 2}
          ]
        }, {
          key = 'dislikes, values = [
            {key = 'blue-frog', value = 3},
            {key = 'goodbye', value = 4}
          ]
        }]

The chart is working fine, like so:
// Create canvas
bars = svg.append("g");

// Create individual bars, and append data
// 'likes' are bound to first bar, 'dislikes' to second
bar = bars.selectAll(".bar")
        .data(data)
        .enter()
        .append("g");

// Create rectangles per bar, and append data
// 'blue-frog' is bound to first rectangle, etc.
rect = bar.selectAll("rect")
        .data(function(d) { return d.values;})
        .enter()
        .append("rect");

I would like to create tooltips per rectangle which say things like "Likes: 2"  This involves binding information about the bar keys to the rectangles.  I have not found a way to do this (other than changing the data).  Can you see an elegant solution?
Also, I'm not sure I have described this question in the best way.  Let me know if you have any suggestions for a better title.

A: Not sure if you'd consider this an elegant solution, but it avoids changing your data.
It draws on a few key 'features':

*

*You are at liberty to get a reference to & then use the selection array (but to use this array you need to know the current selection group - see last point)

*Through the .parentNode property, you can get the DOM element of the parent node

*Through the __data__ property, you can get to the associated data of the parent node

*The data access function function(d,i){....} can be supplied in a 3-parameter form: function(d,i,j){....} where j is the current selection group.

So, in your example, you could get the selection array:
var selection = bar.selectAll("rect")
  .data(function(d) { return d.values;})
  .enter();

From the selection array, you could get at the data in question:
selection
  .append("li")
  .text(function(d,i,j) {
    return selection[j].parentNode.__data__.key;
  }

Easier to see a full example, rather than code snippets in this case:
http://bl.ocks.org/4199266
As I mention on the gist - I recall reading about this 3-parameter form of the data accessor function, but can't for the life of me remember where - I would welcome being pointed at source material that documents this 'feature'.

A: Have you looked at Tipsy?
It might do exactly what you need, and it does a large part of the work for you.  For example, just adding this block of text:
$('svg circle').tipsy({
  gravity: 'w',
  html: true,
  title: function() {
    var d = this.__data__;
var pDate = d.date;
    return 'Date: ' + pDate.getDate() + " " + monthNames[pDate.getMonth()] + " " + pDate.getFullYear() + '<br>Value: ' + d.value;
  }
});

Gets you tooltips with all the appropriate data for the D3 Example: Line Chart with Tipsy Tooltips.


text:
Q: PHP Redirect to another page after login Even though the if condition ($num>0) is true, I am not being redirected to the welcome.php, any help from fellow developers?
if(isset($_POST['login'])){
$password=$_POST['password'];
$email=$_POST['email'];
$ret= mysqli_query($con,"SELECT * FROM users WHERE email='$email' and password='$password'");
$num=mysqli_fetch_array($ret);

if($num>0)
{
$extra="welcome.php";
$_SESSION['login']=$_POST['email'];
$_SESSION['id']=$num['id'];
$_SESSION['full_name']=$num['full_name'];

$host=$_SERVER['HTTP_HOST'];
$uri=rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
header("Location:http://$host$uri/$extra");
exit();
}

After login button is clicked, with the correct attributes, Im stuck on the same page, just blank white page.
   <form name="login" action="" method="post">

                      <input class="uk-input" name="email" type="email" placeHolder="Enter your e-mail">

                      <input class="uk-input" name="password" type="password" placeHolder="Enter your password">

           <input type="submit" name="login" value="LOG IN" >

    </form>

A: replace header("location:http://$host$uri/$extra");
with header("Location: http://$host$uri/$extra");


text:
Q: "USB Needs more power." - Mac Pro with 7 Keyboards? I am in the process of setting up a MacPro whose sole purpose is to run VMs on each of the six possible screens each with it's own keyboard and mouse.
So what I have is six DVI monitors with six dual-link display-port to DVI/USB adapters and an Anker 10 port USB hub/charger to power them all.  The VMs are to be each assigned their own keyboard through virtualbox USB filters.
Originally the monitors were having some trouble coming up all at once (and in order) with a Macally 7 port hub so I'd thought the issue was the amount of power the hub was outputting.  Additionally none of the keyboards except for the one attached directly to the MacPro itself were being recognized so more power was figured necessary.
However even with the more powerful Anker USB Hub the system will not work with the extra keyboard and mouse attached through the hub with a single monitor running.  The "USB Needs more power." message still comes up. These all happened to be old extra Apple keyboards.  I've also tried with a couple of non-Apple specific keyboards and it appears that they only work when hooked up directly to the MacPro even though the USB power message does not come up. Next I'll be trying separate hubs for the display port hookups and the keyboards and mice to see if it is some sort of weird dual-link display-port to dvi issue.
Will MacPros only recognize a single Apple Keyboard? Only keyboards hooked up directly? Is this by chance a software issue I can disable or work around with extra software?

A: This kind of applies to all hardware, not just apple computers. I did a search for Anker USB Hub. None of the results showed a powered USB Hub. They all relied on the USB Bus for power.
The average USB port has about 500 mA available. (900 mA in USB3.0) USB Keyboard uses between 50 mA and 100 mA. The USB hub itself also needs power, more if it's got all those pretty LED's on it. This puts the load between 400 mA (idle?) and 800 mA (all in use?)
So, it seems like your using more power than a single USB port can provide. You may just need to upgrade to a hub that supplies it's own power to devices. Which would require a hub with an AC adaptor.

A: For whatever reason, the display port to DVI adapters draw power as well but don't transmit enough power to hook up a Mac keyboard (which is also a hub) but will allow a single low power USB device.

What I ended up doing was hook up the MacAlly AC powered hub to the displayport to DVI adapters. Without the keyboards plugged into the dp->DVI adapters the screens come up easier.  The keyboards are all separately attached to the Anker powered hub which is hooked up to the MacPro. With six extra keyboards and mice attached to that they are all now appearing so I can filter them and lock them to specific Virtualbox VMs.


text:
Q: Measuring the CPU frequency scaling effect Recently I am trying to measure the effect of the cpu scaling. Is it accurate if I use this clock to measure it?
    template<std::intmax_t clock_freq>
    struct rdtsc_clock {
        typedef unsigned long long rep;
        typedef std::ratio<1, clock_freq> period;
        typedef std::chrono::duration<rep, period> duration;
        typedef std::chrono::time_point<rdtsc_clock> time_point;
        static const bool is_steady = true;

        static time_point now() noexcept
        {

            unsigned lo, hi;
            asm volatile("rdtsc" : "=a" (lo), "=d" (hi));

            return time_point(duration(static_cast<rep>(hi) << 32 | lo));
        }
    };

Update:
According to the comment from my another post, I believe redtsc cannot use for measure the effect of cpu frequency scaling because the counter from the redtsc does not affected by the CPU frequency, am i right?

A: From the comment in my another post, in short, redtsc cannot use for measure the effect of cpu frequency scaling because the counter from the redtsc does not affected by the CPU frequency.


text:
Q: Does Apache Airflow has rule editor Does apache airflow has rule editor, where we can define multiple rules like "(x>y) && (z==a)" etc.. and later we can integrate these rules in the workflow steps similar to Drools workbench editor?

A: No, depending on what you need to implement you can use variables to store some data. You can mainly store strings or a json structure.
Using those you can define some kind of structure that will be read inside the DAG. You can even create different tasks dynamically from the value of a Variable.


text:
Q: Creating XML from SQL data I have a huge XML, with over 150 element and attributes. I need to populate only a handful of them ( 5 or 6) elements with data from a  SQL server 2008 tables. This created xml need to be passed to a webservice ( to ESB)  and this has to happen on a daily schedule.
I think, it does not make sense to use XML Path here to create the XML and use SSIS. Can anyone suggest an approach?
This is the sample XML. I need just the names, address and a few ids populated
<?xml version="1.0" encoding="UTF-8"?>
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Customer.xsd">
<CustomerData>
        <StoreID></StoreID>
        <FirstName></FirstName>
        <LastName></LastName>
        <Gender></Gender>
        <BirthMonth></BirthMonth>
        <BirthYear></BirthYear>
        <BirthDay></BirthDay>
        <IsEmployee></IsEmployee>
        <customerID></customerID>
        <EmailAddress></EmailAddress>
        <PhoneNumber></PhoneNumber>
        <EmailSignUp></EmailSignUp>
        <CatalogSignup></CatalogSignup>
        <Addresses>
            <BillingAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City></City>
                <State></State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </BillingAddress>
            <CatalogSignupAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City></City>
                <State></State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </CatalogSignupAddress>
            <StoredAddresses>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
            </StoredAddresses>
        </Addresses>
        <Hobbies_Enjoys>
            <Hobby></Hobby>
            <Enjoy></Enjoy>
        </Hobbies_Enjoys>
        <FavoriteFossilProducts>
            <ProductType></ProductType>
            <ProductType></ProductType>
        </FavoriteFossilProducts>
        <AgeRange></AgeRange>
        <PreferredEmailFormat></PreferredEmailFormat>
        <SavedCreditCards>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
        </SavedCreditCards>
        <PurchasedProductList>
            <SKU></SKU>
            <SKU></SKU>
        </PurchasedProductList>
        <OrderHistory>
            <Orders>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
            </Orders>
        </OrderHistory>
        <WishLists>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
        </WishLists>
    </CustomerData>
    <CustomerData>
    </CustomerData>
</Customer>

A: One approach is to take an empty version of your XML document and assign it to an NVARCHAR(MAX) variable.  For each node or parameter you wish to populate, put a "token" and use the replace function to populate the value.  For example:
DECLARE @xml NVARCHAR(MAX)

SET @xml = N'<Company name="~company_name~">
<Department name="~dept_name~">
<Employee name="~employee_name~" title="~employee_title~" />
</Department>
</Company>'

SET @xml = REPLACE(@xml,N'~company_name~','Microsoft')
SET @xml = REPLACE(@xml,N'~dept_name~','Executive')
SET @xml = REPLACE(@xml,N'~employee_name~','Satya Nadella')
SET @xml = REPLACE(@xml,N'~employee_title~','CEO')

SELECT CAST(@xml AS XML)

Here's a more traditional approach.  You'll need an arbitrary value in the cells you wish to update:
DECLARE @example_data TABLE
(FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255) NOT NULL,
Gender CHAR(1) NOT NULL,
City VARCHAR(255) NOT NULL,
[State] CHAR(2) NOT NULL)

INSERT INTO @example_data
        ( FirstName , LastName , Gender , City , [State])
VALUES  ( 'Satya' , -- FirstName - varchar(255)
          'Nadella' , -- LastName - varchar(255)
          'M' , -- Gender - char(1)
          'Redmond' , -- City - varchar(255)
          'WA'  -- State - char(2)
        )
INSERT INTO @example_data
        ( FirstName , LastName , Gender , City , [State])
VALUES  ( 'Larry' , -- FirstName - varchar(255)
          'Ellison' , -- LastName - varchar(255)
          'M' , -- Gender - char(1)
          'Woodside' , -- City - varchar(255)
          'CA'  -- State - char(2)
        )

DECLARE
@customer_xml XML,
@xml XML,
@temp NVARCHAR(255),
@FirstName VARCHAR(255),
@LastName  VARCHAR(255),
@Gender CHAR(1),
@City VARCHAR(255),
@State CHAR(2)

SET @customer_xml = '<?xml version="1.0" encoding="UTF-8"?>
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Customer.xsd">
<CustomerData>
        <StoreID></StoreID>
        <FirstName>a</FirstName>
        <LastName>b</LastName>
        <Gender>c</Gender>
        <BirthMonth></BirthMonth>
        <BirthYear></BirthYear>
        <BirthDay></BirthDay>
        <IsEmployee></IsEmployee>
        <customerID></customerID>
        <EmailAddress></EmailAddress>
        <PhoneNumber></PhoneNumber>
        <EmailSignUp></EmailSignUp>
        <CatalogSignup></CatalogSignup>
        <Addresses>
            <BillingAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City>d</City>
                <State>e</State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </BillingAddress>
            <CatalogSignupAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City></City>
                <State></State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </CatalogSignupAddress>
            <StoredAddresses>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
            </StoredAddresses>
        </Addresses>
        <Hobbies_Enjoys>
            <Hobby></Hobby>
            <Enjoy></Enjoy>
        </Hobbies_Enjoys>
        <FavoriteFossilProducts>
            <ProductType></ProductType>
            <ProductType></ProductType>
        </FavoriteFossilProducts>
        <AgeRange></AgeRange>
        <PreferredEmailFormat></PreferredEmailFormat>
        <SavedCreditCards>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
        </SavedCreditCards>
        <PurchasedProductList>
            <SKU></SKU>
            <SKU></SKU>
        </PurchasedProductList>
        <OrderHistory>
            <Orders>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
            </Orders>
        </OrderHistory>
        <WishLists>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
        </WishLists>
    </CustomerData>
</Customer>'

DECLARE xml_cursor CURSOR FOR
SELECT FirstName , LastName , Gender , City , [State]
FROM @example_data

OPEN xml_cursor

FETCH NEXT FROM xml_cursor into @FirstName, @LastName, @Gender, @City, @State

WHILE @@fetch_status = 0
BEGIN
    SET @xml = @customer_xml

    SET @xml.modify('
    replace value of (/Customer/CustomerData/FirstName[1]/text())[1]
    with sql:variable("@FirstName")
  ')

    SET @xml.modify('
    replace value of (/Customer/CustomerData/LastName[1]/text())[1]
    with sql:variable("@LastName")
  ')

    SET @xml.modify('
    replace value of (/Customer/CustomerData/Gender[1]/text())[1]
    with sql:variable("@Gender")
  ')

    SET @xml.modify('
    replace value of (/Customer/CustomerData/Addresses/BillingAddress/City[1]/text())[1]
    with sql:variable("@City")
  ')

    SET @xml.modify('
    replace value of (/Customer/CustomerData/Addresses/BillingAddress/State[1]/text())[1]
    with sql:variable("@State")
  ')

    select @xml

    FETCH NEXT FROM xml_cursor into @FirstName, @LastName, @Gender, @City, @State
END

This approach does not require a value in the nodes to be updated.  It simply inserts a new node, then deletes the old node:
DECLARE @example_data TABLE
(FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255) NOT NULL,
Gender CHAR(1) NOT NULL,
City VARCHAR(255) NOT NULL,
[State] CHAR(2) NOT NULL)

INSERT INTO @example_data
        ( FirstName , LastName , Gender , City , [State])
VALUES  ( 'Satya' , -- FirstName - varchar(255)
          'Nadella' , -- LastName - varchar(255)
          'M' , -- Gender - char(1)
          'Redmond' , -- City - varchar(255)
          'WA'  -- State - char(2)
        )
INSERT INTO @example_data
        ( FirstName , LastName , Gender , City , [State])
VALUES  ( 'Larry' , -- FirstName - varchar(255)
          'Ellison' , -- LastName - varchar(255)
          'M' , -- Gender - char(1)
          'Woodside' , -- City - varchar(255)
          'CA'  -- State - char(2)
        )

DECLARE
@customer_xml XML,
@xml XML,
@temp NVARCHAR(255),
@FirstName VARCHAR(255),
@LastName  VARCHAR(255),
@Gender CHAR(1),
@City VARCHAR(255),
@State CHAR(2)

SET @customer_xml = '<?xml version="1.0" encoding="UTF-8"?>
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Customer.xsd">
<CustomerData>
        <StoreID></StoreID>
        <FirstName></FirstName>
        <LastName></LastName>
        <Gender></Gender>
        <BirthMonth></BirthMonth>
        <BirthYear></BirthYear>
        <BirthDay></BirthDay>
        <IsEmployee></IsEmployee>
        <customerID></customerID>
        <EmailAddress></EmailAddress>
        <PhoneNumber></PhoneNumber>
        <EmailSignUp></EmailSignUp>
        <CatalogSignup></CatalogSignup>
        <Addresses>
            <BillingAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City></City>
                <State></State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </BillingAddress>
            <CatalogSignupAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City></City>
                <State></State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </CatalogSignupAddress>
            <StoredAddresses>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
            </StoredAddresses>
        </Addresses>
        <Hobbies_Enjoys>
            <Hobby></Hobby>
            <Enjoy></Enjoy>
        </Hobbies_Enjoys>
        <FavoriteFossilProducts>
            <ProductType></ProductType>
            <ProductType></ProductType>
        </FavoriteFossilProducts>
        <AgeRange></AgeRange>
        <PreferredEmailFormat></PreferredEmailFormat>
        <SavedCreditCards>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
        </SavedCreditCards>
        <PurchasedProductList>
            <SKU></SKU>
            <SKU></SKU>
        </PurchasedProductList>
        <OrderHistory>
            <Orders>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
            </Orders>
        </OrderHistory>
        <WishLists>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
        </WishLists>
    </CustomerData>
</Customer>'

DECLARE xml_cursor CURSOR FOR
SELECT FirstName , LastName , Gender , City , [State]
FROM @example_data

OPEN xml_cursor

FETCH NEXT FROM xml_cursor into @FirstName, @LastName, @Gender, @City, @State

WHILE @@fetch_status = 0
BEGIN
    SET @xml = @customer_xml

    SET @xml.modify('
    insert <FirstName>{ xs:string(sql:variable("@FirstName")) }</FirstName>
    before (/Customer/CustomerData/FirstName)[1]
    ')

    SET @xml.modify('
    delete /Customer/CustomerData/FirstName[2]
    ')

    SET @xml.modify('
    insert <LastName>{ xs:string(sql:variable("@LastName")) }</LastName>
    before (/Customer/CustomerData/LastName)[1]
    ')

    SET @xml.modify('
    delete /Customer/CustomerData/LastName[2]
    ')

    SET @xml.modify('
    insert <Gender>{ xs:string(sql:variable("@Gender")) }</Gender>
    before (/Customer/CustomerData/Gender)[1]
    ')

    SET @xml.modify('
    delete /Customer/CustomerData/Gender[2]
    ')

    SET @xml.modify('
    insert <City>{ xs:string(sql:variable("@City")) }</City>
    before (/Customer/CustomerData/Addresses/BillingAddress/City)[1]
    ')

    SET @xml.modify('
    delete /Customer/CustomerData/Addresses/BillingAddress/City[2]
    ')

    SET @xml.modify('
    insert <State>{ xs:string(sql:variable("@State")) }</State>
    before (/Customer/CustomerData/Addresses/BillingAddress/State)[1]
    ')

    SET @xml.modify('
    delete /Customer/CustomerData/Addresses/BillingAddress/State[2]
    ')

    select @xml

    FETCH NEXT FROM xml_cursor into @FirstName, @LastName, @Gender, @City, @State
END

A: you can also use FLWOR which will allow you to generate the xml in one go by using a template and adding data only to the elements you want.
You won't need to create tables or stored procedures. For example:
declare @x xml
set @x=(select FirstName, LastName from kc_consumer for xml path('CustomerData'))

SELECT @x.query('
for $a in /CustomerData
  return
<CustomerData>
<StoreID></StoreID>

<FirstName>{data($a/FirstName)}</FirstName>
<LastName>{data($a/LastName)}</LastName>

<Gender></Gender>
<BirthMonth></BirthMonth>
<BirthYear></BirthYear>
<BirthDay></BirthDay>
<IsEmployee></IsEmployee>
<customerID></customerID>
</CustomerData>
')

I'm just including a few nodes for readability, you just need to paste the rest of them.


text:
Q: find and replace if 2 columns are the same So I have this table, if cell in column P matches cell in column V, replace Q cell with value from column W.

I found this vba script, but doesn't do what I really need I cant figure out how to edit it.
https://www.extendoffice.com/documents/excel/1873-excel-find-and-replace-multiple-values-at-once.html
Can you help me ?

A: Consider:
Sub Substi_toot()
    Dim i As Long, N As Long

    N = Cells(Rows.Count, "P").End(xlUp).Row
    For i = 1 To N
        If Cells(i, "P") = Cells(i, "V") Then Cells(i, "Q") = Cells(i, "W")
    Next i
End Sub


text:
Q: jQuery Ajax: get specific object value I'm accessing a dictionary REST API using Ajax.
$.ajax({
  url: "http://api.wordnik.com//v4/word.json/cat/definitions?api_key=mykey&includeRelated=false&includeTags=false&limit=1",
  dataType : 'json',
  success: function(data) {
    //called when successful
    alert(data.word);
  },
  error: function(e) {
    //called when there is an error
    console.log(e.message);
  }
});

The response:
[
  {
    "textProns": [],
    "sourceDictionary": "ahd-legacy",
    "exampleUses": [],
    "relatedWords": [],
    "labels": [],
    "citations": [],
    "word": "cat",
    "text": "A small carnivorous mammal (Felis catus or F. domesticus) domesticated since early times as a catcher of rats and mice and as a pet and existing in several distinctive breeds and varieties.",
    "sequence": "0",
    "score": 0.0,
    "partOfSpeech": "noun",
    "attributionText": "from The American Heritage® Dictionary of the English Language, 4th Edition"
  }
]

In my test example I get an alert undefined on success. Most Ajax examples I saw use loops but I'm returning one result. How can I extract the word and text values from the objects?

A: As you can see your response starts with [ and ends with ]. So your response is an array. Then, inside the array, you get objects (starting with { and ending with }). So your data is an array, which can be accessed with data[x] (x being the index), and each member of the selected object can be accessed with the .dot notation: .word, .text etc. So in your case, if there's only one result, you can do data[0].word.

A: The response is an object inside of an array. Try data[0].word

A: You want to change the success function like this,
success: function(data) {
  alert(data[0].word);
}

I verified the value coming correctly.
jQuery AJAX


text:
Q: logging.getLogger('name').setLevel() does not seem to work I have here my example code trying to set a default logger level to info, and although the object says it's level is info, I still get nothing from logger.info()
Running python3.6:
import logging
a = logging.getLogger('a')
a.info('bla') # should be ignored as a's level is warning
a.warning('bla')
a.setLevel('INFO')
a.info('bla') # should now work, but still nothing is shown...

Running from iPython:
In [1]: import logging
   ...: a = logging.getLogger('a')
   ...: a
Out[1]: <Logger a (WARNING)>
In [2]: a.info('bla') # should be ignored as a's level is warning
In [3]: a.warning('bla')
bla
In [4]: a.setLevel('INFO')
# nothing
In [5]: a
Out[5]: <Logger a (INFO)>
In [6]: a.info('bla') # should now work, but still nothing is shown...
# **still nothing...**


text:
Q: Python dependency analyzer library I need a way to find the dependencies for each of my Python package's sub-modules at runtime so I can initialize them in a proper order (see my current [EDIT: former] solution here, which doesn't work to well), so at first I used the standard Python module modulefinder, but that was way too slow (~1-2 seconds per module).
My next choice was to analyze all the globals of each module, and find from those globals which sub-module each sub-module depends upon. (This is my current solution EDIT: I have a better solution now - see my answer). This algorithm is much faster than modulefinder (it takes <200ms per module), but it only works for relative imports, instead of the fully-qualified import style, which is unacceptable.
So, what I need is either:

*

*A quicker alternative to modulefinder

*An alternative algorithm

NOTE: I call my dependency analyzer at the start of each module, like so:
# File my_package/module3.py

import my_package.module1 # Some misc. module
import my_package.module2 # Some other misc. module
import my_package.dependency_analyzer

my_package.dependency_analyzer.gendeps()

(Just in case it helps you any.)
Thank you!
EDIT: I have a solution now - see my answer.

A: I think I have a solution to my own question :)
Here's what would go into the dependency_analyzer module talked about above:
import sys
from sys import _getframe as getframe
import atexit

examined_modules = []

def gendeps():
    """Adds the calling module to the initialization queue."""
    # Get the calling module's name, and add it to the intialization queue
    calling_module_name = getframe(1).f_globals['__name__']
    examined_modules.append(calling_module_name)

def init():
    """Initializes all examined modules in the correct order."""

    for module in examined_modules:
        module = sys.modules[module]
        if hasattr(module, 'init'):
            module.init()
        if hasattr(module, 'deinit'):
            # So modules get de-initialized in the correct order,
            # as well
            atexit.register(module.deinit)

Now, at the start of each module (after all the import statements - this is crucial), a call to gendeps is placed. This algorithm works because each time a module is imported, that call to gendeps is executed. However, since all of the import statements are placed before the call to gendeps in your own module, the least-dependent modules are placed in the initialization queue first, and the most-dependent modules are placed in the initialization queue last.


text:
Q: Can we Debug Xaml in WPF? Can we Debug Xaml in WPF? Is there any external tool or VS plugin which can do that?

A: I've occassionally found these tricks here useful...
http://www.wpftutorial.net/DebugDataBinding.html
...particularly the second one where you use a dummy value converter to break in to the debugger.  It's useful for seeing exactly what objects are being bound, etc.

A: I don't agree with others that it's not possible to debug XAML, but it's true that there are no powerful tools available for this.
As Mark says in this post - http://markegilbert.wordpress.com/2008/03/15/debugging-xaml/

So, the simple answer is yes, you can
  debug problems with XAML.  The longer,
  more qualified answer is that while
  it's possible, the support isn't
  terribly robust yet but should improve
  with newer dev environments (Visual
  Studio, Expression Blend, etc.).

Tips on how to debug and learn about WPF(Josh Smith):
http://joshsmithonwpf.wordpress.com/2007/03/29/tips-on-how-to-debug-and-learn-about-wpf/
Wayback Link | Get line numbers of XAML issues (Peter Himschoot):

Simply add this to your project file:

<!-- under the <PropertyGroup> tag -->
<XamlDebuggingInformation>true</XamlDebuggingInformation>

Now we at least get line number information on the problem :)

More descriptive XAML exception details (Rob Relyea)
More on XamlParseException (Laurent Bugnion)

*

*

Wayback Link | XAML Runtime Parsing Exceptions (c/o Erno de Weerd)

*

*

Wayback Link | How to debug triggers using Trigger-Tracing(Dan Lamping)

*

*

Debugging Dynamic XAML in Silverlight (Julia Lerman)
Just use google/StackOverflow to know how to debug specific XAML issues.

A: XAML is a declarative language and not imperative so I don't see how debugging it could be possible.

A: No it is not possible.


text:
Q: Android:Keyboard not shown using code in emulator This code is to show and hide Android Keyboard on a button click.
public void keyClickHandler(View v) {
    EditText editText = (EditText) findViewById(R.id.KeyBoard);
    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    if (keyboard) {
        mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        keyboard = false;
    } else {
        mgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
        keyboard = true;
    }

    Log.d("SET", "Focus");
}

But it is not working in emulator
I got found that it is working in the phone,but not in the emulator

A: I don't know how the rest of your code is, but you can try something like this:
public void onClick(View v)
{
    EditText editText = (EditText) findViewById(R.id.KeyBoard);
    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

     switch(v.getId())
     {
         case R.id.yourButtonId:
            if(keyboard)
            {
                mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                keyboard = false;
            }
            else
            {
                mgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                keyboard = true;
            }

            Log.d("SET", "Focus");
            break;
     }
}

For this to work you have to implement your class with onClickListener and in onCreate set your button to something like this:
Button yourButton = (Button) findViewById(R.id.yourButtonId);
yourButton.setOnClickListener(this);


text:
Q: When I link to Google Maps on a website, Mobile Safari opens the Maps app but doesn't zoom correctly This is a follow up to another question.  Issue is I link to something like http://maps.google.com/?daddr=49.89793,-97.20494 and the location is passed correctly however the map is fully zoomed out so I see all of North and South America.  I have tried adding a couple different parameters to the URL but none seem to be working.  "z=13" sets the zoom to 13 but not on mobile, only a full URL like http://maps.google.com/?daddr=49.89793,-97.20494&z=13

A: Zoom seams to work on a mobile in combination with the q-Parameter, only:
http://maps.google.com/?q=49.89793,-97.20494&z=13
Since using daddr (Destination Address) is waiting for a saddr (Start Address) to determine the zoom level.

A: At least in Mobile Safari, you can pass saddr=Current+Location and Google Maps will use the current location to provide routing options and set the map scale.


text:
Q: Javascript error.. Why does theLogin Form flash for a second? I have a login form that pops up (onclick) but when I click into any page on the site it flashes for a second. It is generated using this plugin for wordpress http://wordpress.org/extend/plugins/flexible-frontend-login/
http://oilfieldconference.com
To recreate simply load the site and click on the Calendar link in the navbar.. You will see the login form flash.. I dont see anything in the console..

Relevant Javascript (I think.. taken from console/resources):
jQuery(document).ready(function($) {
// $() will work as an alias for jQuery() inside of this function

// Add an empty container for overlay
$(document).ready( function($) {
    $('html').prepend('

');
} );

$(document).ready(function() {

     //select all the a tag with name equal to ffl-modal
     $('a[name=ffl-modal]').click(function(e) {
         //Cancel the link behavior
         e.preventDefault();
         //Get the A tag
         var id = $(this).attr('href');

         //Get the screen height and width
         var maskHeight = $(document).height();
         var maskWidth = $(window).width();

         //Set height and width to mask to fill up the whole screen
         $('#ffl-mask').css({'width':maskWidth,'height':maskHeight});

         //transition effect
         $('#ffl-mask').fadeIn(600);
         $('#ffl-mask').fadeTo("fast",0.8);

         //Get the window height and width
         var winH = $(window).height();
         var winW = $(window).width();

         //Set the popup window to center
         $(id).css('top',  winH/2-$(id).height()/2);
         $(id).css('left', winW/2-$(id).width()/2);

         //transition effect
         $(id).fadeIn(1000);

     });

     //if close button is clicked
     $('.ffl-window .ffl-close').click(function (e) {
         //Cancel the link behavior
         e.preventDefault();
         $('#ffl-mask, .ffl-window').hide();
     });

     //if mask is clicked
     $('#ffl-mask').click(function () {
         $(this).hide();
         $('.ffl-window').hide();
     });

});

// calculate mask when user resizes window
$(document).ready(function () {
    $(window).resize(function () {

         var box = $('#ffl-boxes .ffl-window');

         //Get the screen height and width
         var maskHeight = $(document).height();
         var maskWidth = $(window).width();

         //Set height and width to mask to fill up the whole screen
         $('#ffl-mask').css({'width':maskWidth,'height':maskHeight});

         //Get the window height and width
         var winH = $(window).height();
         var winW = $(window).width();

         //Set the popup window to center
         box.css('top',  winH/2 - box.height()/2);
         box.css('left', winW/2 - box.width()/2);

    });
});

 $(document).ready(function() {

    // find all instances of flexible-frontend-login to append individual links
    $('a[name=ffl-popup]').each(function(){
        // get the tags from link
        var id = $(this).attr('href');
        // set linked div to hidden
        $(id).hide();
    });

    // select a tags with name equal to ffl-popup
    $('a[name=ffl-popup]').click(function(e) {
        // cancel link behavior
        e.preventDefault();
        // get the tags from link
        var id = $(this).attr('href');
        // Set visibility
        $(id).css('display', 'block');
    });

     //if close button is clicked
     $('.ffl-close-popup-link').click(function(e) {
         //Cancel the link behavior
         e.preventDefault();
         // get parent id
         var id = $(this).parents('div:eq(0)').attr('id');
         // and hide it
        $('#'+id).hide();
      });

 });

});

A: Since you didn't post the javascript or anything, my best guess is you are making display none in the javascript and it doesn't run until after page load? Maybe go into your css and make it display none and onclick display:block?

A: I believe I have a solution for you, but it involves editing the class files of the plugin you are using.  I looked at the JS.  It is not what is at issue.. what is at issue is the div in question is being generated on the page before the js then hides it.  To fix that, do the following.  Note that this is untested because I don't have wordpress and the plugin in question installed on my machine:
Go into flexible-frontend-login\includes\classes\class.FrontendLogin.php and find line 49, which should be this:
$html .= "
horizontal_position} ffl-{$this->vertical_position}'>";

Replace it, or edit it to be like this.  Either works really:
$html .= "
horizontal_position} ffl-{$this->vertical_position}' style='display: none;'>";

This edit causes the div in question to be hidden at generation, instead of hidden later in the js.


text:
Q: How to pull two columns (with headers) from CSV and show them side by side? I apologize if this has already been covered, but I did spend a bit of time looking for this answer on the site.
I am looking for a way to pull two columns out of a csv file (the only two of about twenty) that are important to my project) and display them.
The result should be like so (where server and warranty are two columns separated by several more):
Server    Warranty
DP123     Current
DP124     Current
DP125     Expired

A: You could use the the read_csv() function from the pandas data analysis library, define the subset of disired columns as a list and hand that to the 'usecols' function parameter:
import pandas as pd

df = pd.read_csv('somefile.csv', usecols=['Server','Warranty'])

print(df)


text:
Q: Sending Email using hosting Mail I am trying to send Email from my company mail , when i use this code
i got
  public String SendMail(String Email)
        {
        try
        {
            var client = new SmtpClient("smtp.gmail.com",587)
            {
                Credentials = new System.Net.NetworkCredential("************@itsans.com", "*********"),
                EnableSsl = true
            };
           // client.UseDefaultCredentials = false;
            String VerCode = CreateRandomCode(4);

            AppUserBusiness appuser = new AppUserBusiness();
            String InsertVer = appuser.ForgotPassword(Email, VerCode);

            if (InsertVer == "Done")
                client.Send("*********@itsans.com", Email, "iBlink Verification", "Your Verification Code is :" + VerCode);

            return InsertVer;
        }
        catch (Exception Ex)
        {

            Logging.WriteToFile(Ex.Message, Ex.StackTrace);
            return "Fail";
        }

    }

{"Unable to connect to the remote server"}
{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 72.167.238.29:587"}


text:
Q: anova.mer Mod(mod_null, mod_eins) : models were not all fitted to the same size of dataset I have seen that some guys had this problem, too, but I really didn't understand the given answers.
I did some linear mixed models starting with the "intercept only" model. Subsequently I wanted to add more variables. When I try to compare the models, the R out put was "models were not all fitted to the same size of dataset". What do I have to do to fit data at the same dataset?
The R syntax is:
mod_zero <- lmer(quality ~ 1 + (1|subject_id))
summary(mod_zero)
mod_one <- lmer(quality ~ ps + an + int + ch + boredom + (1|subject_id),dat)
summary(mod_one)
anova(mod_zero, mod_one)

Adding na.rm=T did not help. Does anyone have an idea?

A: The error is likely caused by the presence of missing data in one or more predictors in the second model. These observations are removed from the second model (thereby creating a different dataset which is a subset of the original data) and you cannot meaningfully compare two models that are fit to different datasets. To compare both models you'll have to fit the first model to a dataset without missing data on ps, an, int, ch, boredom. Try:
dat2 <- dat[which(complete.cases(dat[,c('ps', 'an', 'int', 'ch', 'boredom')])),]

mod_zero <- lmer(quality ~ 1 + (1|subject_id), dat2)
mod_one <- lmer(quality ~ ps + an + int + ch + boredom + (1|subject_id),dat2)

anova(mod_zero, mod_one)

This solves the error, but you should ask yourself why there is missing data. Removing missing data could bias your results depending on the missing data mechanism. If you have a lot of missing data that is systematically related to your outcome variable this will bias your model estimates and you'll need to look into ways of reducing this bias (e.g. multiple imputation). Graham has written a lot of books and articles that explain different missing data mechanisms and solutions. Comparing the output of mod_zero on dat and dat2 may give a first indication of possible bias (although a similar output does not ensure the absence of bias).


text:
Q: как обратиться к вложенной функции? function asdf() {
    function dsa() {
        alert(123);
    }
}

как обратиться к функции dsa?

A: Любая функция (включая "стрелочные") создает свой scope (область видимости). Поэтому, ровно как извне функции asdf() нельзя обратиться к переменным, объявленным внутри этой функции, так нельзя и к другим функциям, объявленным внутри этой.
Однако, если внешняя функция возвращает вложенную, то обратиться к ней не составит труда:
function asdf() {
    return function asd() {
    }
}

asdf()();

A: Гулять - так гулять.

function asdf() {
  function dsa() {
    console.log('from dsa: 123');
  }
  console.log('from adsf: old code');
}

var strAsdf = asdf.toString();
var startIndex = strAsdf.indexOf("{");
var strAsdf = strAsdf.substring(0, startIndex + 1) +
  "if (arguments[0] === 'getMeDsa') return dsa;" +
  strAsdf.substring(startIndex + 1);
eval(strAsdf);

asdf('getMeDsa')();
asdf();

A: Как вариант, но подойдёт ли он в вашем случае, не знаю.
function asdf() {
  this.dsa = function() {
    alert(123);
  }
}

 let Asdf = new asdf();
 Asdf.dsa();


text:
Q: Finding top similar strings in PHP? I have an array of 17,000 strings. Many of the strings have similar matches, for example:

User Report XYZ123
Bob Smith
User Report YEI723
User Report
User Report
Number of Hits 27
Frank's Weekly Transaction Report
Transaction Report 123

What is the best way to find the top "similar strings"? For instance, using the example above, I would want to see "User Report" and "Transaction Report" as two of the top "similar strings".

A: Without giving you all the source code to do this, you could go through the array and remove components you consider useless, like any letters with numbers, and so on.
Then you can use array_count_values() and sort that array to see the top ones involved.

A: You could compute the Levenstein distance for each string compared with others and then sort them by that value.
$strings = array('str1', 'str2', 'car', 'dog', 'apple', 'house', 'str3');
$len = count($strings);

$distances = array_fill(0, $len, 0);

for($i=0; $i<$len-1; ++$i)
    for($j=$i+1; $j<$len; ++$j)
    {
        $dist = levenshtein($strings[$i], $strings[$j]);
        $distances[$i] += $dist;
        $distances[$j] += $dist;
    }

// Here $distances indicates how of "similar" is each string
// The lower values are more "similar"

A: I guess you could do a foreach through each of the strings and eliminate the ones that you don't want for that particular search. Then go through the once you have left (possibly with another foreach) and keep shrinking the number of strings that you have an interest in down until there are just a few. Then sort those by something like alphabetical order.

A: If you are able to get all the strings as an array and loop them in a foreach() like this:
$string_array = array('string', 'string1', 'string2', 'does-not-match');
$needle = 'string';

$results = array();
foreach($string_array as $key => $val):
    if (fnmatch($needle, $val):
        $results[] = $val;
    endif;
endforeach;

in the end you should end having the entries that match $needle. As alternative to fnmatch() you could use preg_match() and as pattern /string/i
$string_array = array('string', 'string1', 'string2', 'does-not-match');
$needle = '/string/i';

$results = array();
foreach($string_array as $key => $val):
    if (!empty(preg_match($needle, $val)):
        $results[] = $val;
    endif;
endforeach;

Note there could be issues when using empty() and pass the result of preg_match().:

Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.

No errors should be issued with PHP version 5.3.x < 5.4


text:
Q: How to correlate button between asp .net and KnockoutJS? I am building an ASP .NET web application with KnockoutJS that plays music. I have the following code working to play audio from a JS array of local filepaths. I am having trouble getting ASP .NET and Knockout to "play nice".
Here is a basic example of what I have working:

ko.bindingHandlers.audio = {
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        if (value) {
            element.src = value;
            element.load();
            element.play();
        }
    }
};

//Note: only the last URL is currently active.
Urls = [
    'http://www.noiseaddicts.com/samples/280.mp3',
    'http://www.noiseaddicts.com/samples/289.mp3',
    'http://www.noiseaddicts.com/samples/294.mp3',
    'http://www.w3schools.com/TAGs/horse.ogg',
]

function vm() {
    this.myIndex = ko.observable(3);

    this.URL = ko.computed(function () {
        return Urls[this.myIndex()];
    }, this)

    this.myFunction = function()
    {
        this.myIndex();
    }
};
ko.applyBindings(new vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
    <input type="text" name="name" data-bind="value: myIndex" />
    URL:<text type="text" name="name" data-bind="text: URL" ></text>
</form>

<audio data-bind="audio: URL" controls autoplay></audio>

In my application, I obviously do not want the user to have to type in the number of the song, rather they should scroll down my list and click the play button next to the song they want to play.
There are 2 problems with this:

*

*How do I get the number of the song so it can work with Knockout?

*How do I correlate that number with each button to update myIndex?

This is how I am currently displaying my list of songs:
<script type="text/javascript">
    var Urls = [];
</script>

@if (Model != null)
{
    foreach (MusicStream.Models.SongViewModel song in Model)
    {
        @Html.Partial("~/Views/Shared/Song.cshtml", song);
    }
}

Then in the partial view I display the song's name and a play button (which is the main problem). I also add the url to the JS array.
    <input type="button" value="Play" data-bind="click: myFunction" />

    <script type="text/javascript">
        Urls.push('@Url.Content(Model.FilePath)');
    </script>

If it helps, here is a screenshot of part of the site. I have some other functions on the page, but they aren't related. Please disregard the numbers in parenthesis next to the song title.

I have thought about using Knockout's foreach binding to display my list of songs instead, however it seems like it would be redundant, as I would have a model in C# and JS for each song.
I have been playing with this single issue for awhile now, and have not been able to find a decent way to fix it. I am open to any other techniques that would be better/easier. Also, thanks a ton for your time!

A: You can pass to myFunction the url as a param, see: data-bind="myFunction.bind($data,'@Url.Content(Model.FilePath)')", change to:
Partial:
<input type="button" value="Play" data-bind="click: myFunction.bind($data,'@Url.Content(Model.FilePath)')" />

ViewModel:
function vm() {

    this.URL = ko.observable("");

    this.myFunction = function(url)
    {
        this.URL(url);
    }
};

So see the snippet to an example, how to pass a param to a click binding function:

var viewModel = function(){
  var self = this;
  this.myText = ko.observable();

  this.myFunction= function(text){
      self.myText(text);
  };
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<input type="text" data-bind="value:  myText"/>

<input type="button" value="Play" data-bind="click: myFunction.bind($data,'url')" />


text:
Q: R: Use replace function with multiple index criteria Is there a way to handle multiple conditionals at once using replace?
What I have now is a data.frame and want to keep it a data.frame:
names$first <- replace(names$first, names$first=="kevin", "Kevin")

works fine, but I want to be able to handle multiple criteria by avoiding if_else if possible. Is something like the below possible? The documentation is sparse and has no examples.
names$first <- replace(names$first, c("kevin","susan"), c("Kevin","Susan"))

A: library(stringr)
names = data.frame(first = c("kevin", "susan", "anbreen"))
str_replace_all(names$first, c("kevin" = "Kevin", "susan" = "Susan"))

#[1] "Kevin"   "Susan"   "anbreen"

A: The second argument in replace is an index vector.  What you would need here is something like
kevins <- which(names$first == "kevin")
susans <- which(names$first == "susan")
replace(names(first), c(kevins, susans),
        c(rep("Kevin", length(kevins)), rep("Susan", length(susans))))

But like @epi99 said, there are packages with functions to do this, if you don't mind leaving base R.  I hope this helps!

A: Here are some ways assuming this input:
from <- c("kevin", "susan")
to <- c("Kevin", "Susan")
Names <- data.frame(first = c("kevin", "susan", "joe"), stringsToFactors = FALSE)

1) match This is a base R solution:
first <- Names$first
From <- c(from, first)
To <- c(to, first)
Names$first <- To[match(first, From)]

The above could be written as one line but might not be as clear.
2) gsubfn
library(gsubfn)
Names$first <- gsubfn(".*", as.list(setNames(to, from)), Names$first)

3) Reduce  This one does use replace.  It is also a base R solution.
repl <- function(x, i) replace(x, x == from[i], to[i])
Names$first <- Reduce(repl, init = Names$first, seq_along(from))

4) for A for loop is another base solution and uses replace and is simple:
for(i in seq_along(from)) {
    Names$first <- with(Names, replace(first, first == from[i], to[i]))
}


text:
Q: Upload GML to Geoserver as Layer through REST I have to upload a GML file to my geoserver through REST. I tried to use importer but it doesn't work (even manually). More specifically, the importer module never generate tasks automatically for GML. When I use another REST call to generate tasks, it returns max-stack-limit error. Further, I noticed that GML is not in the supporting list of importer extension.
Here is the code I used to create a import event:
          var uri = 'http://192.168.0.30:8080/geoserver/rest/imports';
          var data = JSON.stringify({"import": {
                 "targetWorkspace": {
                    "workspace": {
                       "name": "wfsresult"
                    }
                 },
                 "targetStore": {
                    "dataStore": {
                       "name": "WFSSourceResult"
                    }
                 },
                 "data": {
                   "type": "file",
                   "file": "/home/zhangj/geoserverDownload/data/wfsresult/u4f3809a0-56a3-11e7-894d-8dc4d5efd317/result.xml.kml"
                 }
              }});
          Request({
            uri: uri,
            method: 'POST',
            auth: auth,
            headers: {
              'content-type': 'application/json'
            },
            body: data
          }, (err, response, body) => {
            if(err) {
              reply(err);
            } else {
              reply(body);
            }
          });
        }

Am I using importer extension correctly?
If importer doesn't fit my situation, what should I use?
I got that wfs transaction may be a good solution. How should I use it?


text:
Q: Implication of Polignac's conjecture on prime distribution in models of PA Polignac's conjecture (PC) is that there exists infinitely many pairs of consecutive prime numbers that are a distance $d$ apart for some natural number $d$.  The twin prime conjecture is the particular instance of this conjecture for $d = 2$.  The fact that this conjecture remains open has some interesting implications on nonstandard models of Peano Arithmetic (PA).  Specifically, it is a standard exercise to show that every model of PA has order type $\mathbb{N} + \mathbb{Z} \cdot A$ for some dense linear order without endpoints.  Thus every nonstandard model has an initial segment of Natural numbers followed by nonstandard numbers all appearing in an unbounded dense linearly ordered collection of what are called integer blocks or $\mathbb{Z}$-blocks.  What I realized (someone else must've realized this too so please mention references if you know of any) is that if Polignac's conjecture turned out to be false, then we'd have the following strong limitation on the number of primes appearing in $\mathbb{Z}$-blocks.

($\mathbb{N} \vDash \lnot PC$) If $M$ is a model of PA and is $\Sigma^0_1$-equivalent to the theory of $\mathbb{N}$, then $M$ can have at most one prime appearing in any $\mathbb{Z}$-block: If not, then for some $d \in \mathbb{N}$, there would be a pair of nonstandard numbers that $M$ would view as two consecutive primes a distance $d$ apart.  Since this occurs in a $\mathbb{Z}$-block, for any true Natural number $n$, the model $M$ thinks that there is a pair of consecutive primes greater than $n$ a distance $d$ apart.  Then by $\Sigma^0_1$-elementarity, $\mathbb{N}$ would think the same thing so $\mathbb{N}$ would have unboundedly many pairs of consecutive primes a distance $d$ apart, making Polignac's conjecture true (in the standard model).

My question concerns the other models of PA:

Can we prove that there is a nonstandard model of PA having a $\mathbb{Z}$-block with at least two primes?  Even better, can we prove that there is a model of PA with unboundedly many $\mathbb{Z}$-blocks having at least two primes?

A: For simplicity, take $d=2$. Then the the existence of a model of PA with at least one non-standard pair of twin primes is equivalent to the assertion
For all (fixed, standard) primes $p$ the sentence $$\phi_p:\forall x>p,\,\,\, x \textrm{ is not prime or } x+2 \textrm{ is not prime }$$
is not provable in PA.
Is it reasonable to spend lots of time hunting for a proof of this before the twin prime conjecture is resolved? My guess is "no" and here is why.
All known constructions of non-standard models of PA depend in some way on an oracle who can determine which sentences are consistent with PA, or who can determine which sets are and are not members of some non-principal ultrafiter. I have no objections to such arguments, but it is well to be clear about the awesome powers of such an oracle: Relative to where we are, this is the point of view of eternity. It would be remarkable indeed if any statement of elementry number theory could be derived from such general constructions, and to my knowledge, none ever has.
There is an analogy here with a paragraph in Hardy and Wright's number theory text. Let $c$ be the constant $.020300500000007\ldots$. The point is that the definition of $c$ depends on foreknowledge of the sequence of primes. Using $c$ we can give a very simple formula for the $n$th prime, which is, as Hardy remarks, completely useless for proving things about primes.
In the same vein, there is a frontspiece to a book, I think by Mahler, that says:
     If you want to make sausage you have to put some pork in the grinder.

It is dangerous to say never, and in spite of Tennenbaum's theorem, there might come a day when some representation of models of PA is discovered that allows one to get information about these models from some source other than the Peano axioms... but as far as I know, that day has not arrived. The closest thing to such a representation theorem I have ever seen is an unpublished theorem of Tennenbaum, proving that every countable model of PA can be embedded in $\mathbb{R}^{\omega}$  modulo the cofinite filter: In other words, you can think of the elements of models of PA as germs at infinity of sequences of real numbers. I once asked Greg Cherlin about the usefulness of this representation. His response was "There is no free lunch."


text:
Q: Shortest Path No route found QGIS 3 I am using shortest path point to point and I have found the following problem:
I am using a road network which includes some roads that have one way and others are bidirectional.  My origin and destination points are not in the network but they are near the network.
If I run the shortest path algorithm without specifying a road direction I get the shortest path between the points, but if I define the one way roads, I do not get a result.
The problem seems to be that the shortest path algorithm first looks for the shortest distance between the points and the road network and then runs the algorithm using that information.  If the shortest distance between the points and the road network lies on a one way road that is not reachable then it gives a not path found error, even if there is a reachable road within the network only a few meters away.
Is there a way to modify the algorithm to search for other points? (Something like, if no route is find, search for the second closest point between the road network and the origin destination points and try again)


text:
Q: In SPSS software, variable view disappears after changing data type from string to numeric After the import of my .xls data into SPSS software, I change String variables to Numeric Continuous and they disappear from viewing.
How to fix that?
Thank you

A: You cannot do that in SPSS, the whole variable will be erased. To get the numeric variable, use the syntax:
recode StringVar (convert) into NumericFVar.
execute.


text:
Q: Cant store images on selected folder - multer and express So I had it all working and for what ever reason after trying to build on it I can no longer get my application working. First and foremost I just want to be able to save my uploads to a folder again.
const saveToFolder = path.join(__dirname + "/../../" + "uploads");

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, saveToFolder);
    },
    filename: (req, file, cb) => {
        const fileName = req.file.originalname + ".jpg";
        cb(null, fileName);
    },
});

const upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (
            file.mimetype == "image/png" ||
            file.mimetype == "image/jpg" ||
            file.mimetype == "image/jpeg"
        ) {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error("Allowed only .png, .jpg, .jpeg"));
        }
    },
});

router.post("/upload", upload.single("file"), (req, res) => {
    console.log(req.file); //Returning undefined
});

My Frontend
submitUpload = (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append("filename", this.state.filename);
        formData.append("file", this.state.file);
        axios({
            method: "post",
            url: "http://localhost:8080/upload",
            headers: {
                "Content-Type": "multipart/form-data",
            },
            data: formData,
        });
    };

My folder structure is
backend
     routes
         uploadImg route (where I handle my post)
frontend
folderToStoreIn

The req.file in my post request forever returns undefined. I've not idea what I've changed to stop it working and I can't understand how too revert it, it all looks fine
Thanks.


text:
Q: eliminate MacBook CapsLock delay On my MacPro there is one issue (and guys from Apple think this is feature...) that annoys me very much: there is a time delay between CapsLock switching. I used to do that fast. If I go to preferences and reassign caps lock to any other button and then back it works OK then, so it is not a hardware problem.
Is there any way to fix that ?

A: I was running the latest firmware on an Apple 2007 Aluminum Wireless Keyboard, and MacBook Pro Keyboard, but the issue still persisted. However, oddly this fixed it:

*

*Open System Preferences

*Click Keyboard

*Click Modifier Keys...

*Select your keyboard from the Select keyboard: list.

*Set the Caps Lock Key: to No Action.

*Press OK.

*Ensure your Caps Lock no longer works on your keyboard.

*Click Modifier Keys... again.

*Set the Caps Lock Key: to Caps Lock.

*Press OK.

Now, the Caps Lock key works instantly for that keyboard. Repeat as-needed for each keyboard you own.

A: If you want a simpler solution than Karabiner, I've written a very small, open source tool to fix exactly that.
https://github.com/gkpln3/CapsLockNoDelay

A: Just as an FYI, I found an alternative solution in another question:

*

*Go to System Preferences -> Accessibility -> Keyboard

*Check Enable Slow Keys

*Click Options

*Drag the Acceptance Delay slider all the way to the left

*Press OK
However, this fix introduces other problems, including:

*

*If you hold down a key to repeat it (such as delete), then the repeat delay is extremely slow

*Some keyboard shortcuts like Crtl+Shift+Tab may no longer work

Tested on macOS 10.14.4 and 10.15.7

A: If you install Karabiner-Elements, it defaults to zeroing out macOS's obnoxious caps lock delay.
The version you need to install depends on your macOS version.
macOS 10.15.6 and above
Download and install Karabiner-Elements 13.3.0 or higher.
macOS 10.11 through 10.15.5
Download and install Karabiner-Elements 11.6.0.
(Note that Karabiner-Elements 12.0.0 - 13.1.0 re-added the Caps Lock delay, and 13.3.0 isn't available on older OS versions.)

This is the only solution I know of that both works on 10.12 and requires nothing more than installing & running an application without any special steps or reconfigurations.

A: *

*Download and install the following software

*

*Karabiner

*Hammerspoon

*Use Karabiner maps CapsLock key to F19.

*Edit init.lua under the path ~/.hammerspoon, paste the code below.

pressedF19 = function()
    hs.hid.capslock.toggle()
end

hs.hotkey.bind({}, 'F19', pressedF19, nil)

Then reload the hammerspoon config for changes to take effect.
See my blog here http://hellohtml5.com/2019/04/25/best-way-to-disable-capslock-delay-on-mac/

A: Not really sure about this, but google found this. This was one of the suggestions, but it does not seem foolproof (or even close). There are more suggestions on the page.

*

*Go to System Preferences > Keyboard & Mouse > Keyboard. Click on Modifier Keys. In the window that opens, for the Caps Lock key, select "No Action"

*Install the "No CapsLock" script. Download at
  http://home2.btconnect.com/Taniwha/ (look near bottom of page)

In addition, if you hold down the key, even for a fraction of a second, it will go on automatically.

A: On Apple's discussion boards other's report that updating your keyboard's firmware can/will eliminate this delay.

Re: Delay problem with caps-lock
Apr 8, 2008 3:52 PM
It appears that the keyboard firmware update released today fixes this
  issue.

Get keyboard firmware(s) from Apple.

A: Originally the answer by Martin Steven worked for me. This was when I used OSX 10.9.
After upgrading to OSX Yosemite (10.10) it stopped working. I found another, essentially the same, solution documented here
http://sleepycow.org/2014/07/removing-the-caps-lock-delay-on-a-macbook/
It uses updated version of the apps (with different names) that work with 10.10.
As requested - quoting the relevant sections from the link

*

*Install Seil and Karabiner.

*Go to System Preferences > Keyboard > Modifier Keys and change "Caps Lock" to "No Action."

*Using Seil, check "Change Caps Lock Key" and change the key code to 110. (Application Key)

*Go to Karabiner, and in the search box, enter "application key to capslock." Under For PC Users > Change PC Application Key, check off "Application Key to CapsLock."

A: I had exactly the same problem,
I could solve it by installing Karabiner-Elements and
making the following modification :

*

*select the Simple Modifications tab

*add a new modification (Add Item)

*and put from key caps_lock to key caps_lock

A: If you don't want to install Karabiner just for that, you can use brew install --cask capslocknodelay, it's nice lightweight and open-source tool GitHub.
Do not forget to enable it in the settings:

*

*System Preferences -> General -> Login Items, add CapsLockNoDelay.app to the list.

*System Preferences -> Security & Privacy -> Privacy -> Accessability -> Enable CapsLockNoDelay.app

*System Preferences -> Security & Privacy -> Input Monitoring -> Enable CapsLockNoDelay.app (if present).

A: This happened on my new MacBook Air, I contacted Apple Support and these were the instructions that were given to me and WORKED:
Go to System Preferences > click Accessibility > click Keyboard > then click Hardware > Select Enable Slow Keys > then click Options > Drag the Acceptance Delay slider to set how long you want your Mac to wait before it responds after the key is pressed.
I hope this helps :)


text:
Q: Grails - transport guarantee confidential So, I have founded a blog showing that in order to configure transport-guarantee confidential in a grails application I have to first install template executing:
grails install-templates

Really? It does not exist a configuration that I can do on grails classes and/or config files to accomplish that? This command install a lot more files than I need...
The blog url:
http://www.intelligrape.com/blog/2012/06/29/how-to-configure-ssl-on-tomcat-server-and-run-grailsjava-application-on-https/


text:
Q: Dynamic h:outputScript name attribute in ui:repeat I'm using com.sun.faces version 2.1.18. I'm displaying a list of questions and for some questions (based on the database ID) I want to insert some dynamic Javascripts.
According to the h:outputScript tag specification the name attribute is of type: javax.el.ValueExpression (must evaluate to java.lang.String).
However, this code is working for me:
<ui:repeat value="#{js.questionScripts[question.id]}" var="script">
  <h:outputScript name="myScript.js" library="js" target="head"/>
</ui:repeat>

But this code isn't:
<ui:repeat value="#{js.questionScripts[question.id]}" var="script">
  <h:outputScript name="#{script}" library="js" target="head"/>
</ui:repeat>

The #{question} comes from a surrounding <ui:repeat> iteration over a list of questions.
I added an output to see if #{script} was not empty, but it contained the correct resource name.
Any ideas on how to solve this or implement an alternative?

A: The <h:outputScript> has to be created during view build time in order to be recognized by JSF resource management. The <ui:repeat> runs during view render time and is therefore too late. You have to use <c:forEach>. I'm not sure how it failed for you, but it works fine for me, provided that #{js} is a request, session or application scoped bean whose questionScripts property is already prepared during its (post)construction and that #{question.id} is available during view build time.
<c:forEach items="#{js.questionScripts[question.id]}" var="script">
    <h:outputScript name="js/#{script}" target="head"/>
</c:forEach>

(note that you've to use items attribute instead of value attribute and also note that I fixed the seemingly improper usage of library attribute).
See also:

*

*JSTL in JSF2 Facelets... makes sense?


text:
Q: variable string has html in it and will not allow whitespace in javascript parameter I am writing a small script to be ran in a dialog when it opens. In the code I have a string type variable with html code, such as string script = . That will not work but if i take out all the white spaces it will work fine. Question is is there a way to pass in a parameter with spaces or any other way to do this? thanks for any examples or suggestions.
Small example of the error, This is a string in c#.
 "
"

A: Some of the character encoding you're doing is a little unnecessary. You need quotes around your JS function, which is why the whitespace is causing it not to work.
string div = "
" +
    "
"

And before you sent it to the client, let .NET do the character encoding for you:
string encoded = HttpUtility.HtmlEncode(div);

Also, you didn't close your opening
 tag; I'm not sure if you were intending to, but I added it anyway.

A: "
"
^^Copy and Paste That

A: JavaScript string literals can not contain a literal newline character.
There are actually 4 characters in the "LineTerminator" class which can not appear in a string literal directly: LF/Line Feed, CR/Carriage Return, LS/Line Separator and PS/Paragraph Separator. More information can be found in section 7.8.4: String Literals and 7.2: Whitespace sections of the EMCAScript 5th Edition specification.
// read the error console, this is a syntax error and is reported by FF as:
//   SyntaxError: unterminated string literal
var bad = "because it
    contained a literal newline"

// this is valid syntax
var good = "because it\n\
    didn't contain one"

Note that in the 2nd case the last '\' (which must be the last character on the line) signifies that the string literal does not terminate but continues on to the next line (no character takes it's place, hence the \n before) to embed the newline into the string.
Happy coding.


text:
Q: Count sorting in vector codes before the line is codes that i get count from each name appear.. then i push the name and count into a new class.. and from the class i try to sort by highest number of count to lowest but having problem..codes after line is sorting part  .. the if part inside for loop was having problem.. any 1 can help me
void zzz(vector<indi>a)
    {

    vector<sortName>s;
        bool duplicate = false;
        for(int i=0; i<a.size();i++)
        {
            int c=0;
             duplicate = false;
                for (int k=i-1;k>0;k--)
               {
                   if (a[i].getname() == a[k].getname())
                   {
                       duplicate=true;
                   }

               }
            for(int j=i;j<a.size();j++)
           {
               if(a[i].getname()==a[j].getname() && duplicate==false)
               {
                   c++;
               }
           }
           if (duplicate == false)
           {
    cout<<a[i].getname() <<":" <<c <<" "<<endl;

          s.push_back(sortName( a[i].getname(),c));
_______________________________________________________________________

           }
        }
        for(int i=0;i<s.size();i++)
        {

                    {
    //                    cout<<"before sort "<<i+1<<". ";
                        s[i].sCountshow();
                        cout<<endl;
                    }
        }
        string tempname;
        int tempcount;
        vector<sortName> temp;
        cout<<"running sort";
        for(int i=0;i<s.size();i++)
        {
            for(int j=i+1;j<s.size();j++)
            {
                if(s[i].getsCount()< s[j].getsCount())
                {
                    temp[0]= s[i];
                    s[i]=s[j];
                    s[j]=temp[0];

                    tempname = s[i].getname();
                    tempcount = s[i].getsCount();
                    s[i] = s[j];
                   s.erase(s[i]);
                   s.insert(s.begin()+j,sortName(tempname,tempcount));
                }
                }

            }
    cout<<"end sort";
     for(int i=0;i<s.size();i++)
        {

                    {
                        cout<<"after sort "<<i+1<<". ";
                        s[i].sCountshow();
                        cout<<endl;
                    }
        }


text:
Q: DB2 Conditional WHERE clause I'm using DB2 v9
I have a stored procedure with paramaters that can potentially be passed in as empty strings. Here somer pseudocode for what I'm trying to do:
WHERE myColumn.name =
     IF param1 = '' THEN
        **disregard this param, all column values are eligible**
     ELSE
        myColumn.name = param1;

Basically just ignore the param if it is an empty string. If not, apply it as a filter in the WHERE clause. Is this possible to do in DB2?

A: SELECT ...
FROM ...
WHERE  param1 = ''
   OR  myColumn.name = param1
   ;

A: The answer provided by wildplasser is correct, but there are some additional considerations that may helpful to include.
First, it might be possible that the stored procedure input parameter contains a NULL instead of ''. Using the COALESCE or NULLIF functions will cover both a NULL and any amount of empty space:
SELECT ... FROM ... WHERE COALESCE( param1, '' ) = '' OR myColumn.name = param1 ;

When that type of search query is compiled into a stored procedure, it generally helps to enable REOPT ALWAYS on the statements inside the procedure. If you don't do this, the SQL statements inside your stored procedure will always use the same access plan, regardless of which input parameters are passed into the stored procedure at runtime. Allowing the optimizer to re-evaluate each statement in the procedure at runtime will provide a much better chance of exploiting the right index when the user searches on a particular column.
CALL SYSPROC.REBIND_ROUTINE_PACKAGE
    ('P','YOURPROCSCHEMA.YOURPROCNAME','REOPT ALWAYS') ;

A: Another Keyword here would be "Dynamic SQL". Build your queries as a string and either EXECUTE IMMEDIATE them (for UPDATE, INSERT or DDL's) or use PREPARE/OPEN/FETCH (for SELECT's).


text:
Q: What does $[M:N]$ mean, where $M,N$ are modules and $N$ is a submodule of $M$. What does $[M:N]$ mean? where $M,N$ are modules and $N$ is a submodule of $M$.
The context is the following equation:
$$\text{disc}(1,\alpha,\alpha^2)=[\mathcal{O}_K:\mathbb{Z}[\alpha]]^2\text{disc}(\mathcal{O}_K)$$ where $\mathbb{Z}[\alpha]$ is the ring of algebraic integers and $\mathbb{Z}[\alpha]$ is a submodule of $\mathbb{Z}[\alpha]$(here $\alpha$ is a algebraic integer).


text:
Q: 'at' or 'of' in a sentence

*

*No one believes him because he is false at heart.

*No one believes him because he is false of heart.

Is the first statement wrong? What are the differences between 1) and 2)?
My book says 2) is the correct usage. But I have never seen anything like it until now.

A: The first ("at heart") is more idiomatic; although the second ("of heart") is not wrong, and would probably be understood the same way.
One might also say

*

*"...because he is false-hearted.

A: Brian Hitchcock is right that both are possible and could be understood the same way.
Here are a couple of real examples:
False at heart:

She said that he was false at heart,
He called her light coquette :
And both exclaimed--"next week we part,
I wish we ne'er had met."
—The New English Drama: With Prefactory Remarks, Biographical Sketches, and Notes, Critical and Explanatory
Volume 19, edited by William Oxberry.

False of heart:

CIX.
O, never say that I was false of heart,
Though absence seem'd my flame to qualify.
As easy might I from myself depart
As from my soul, which in thy breast doth lie.
—Shakespeare's Sonnets, edited, with notes by William J. Rolfe. Litt.D., 1883.
(The Sonnets were first published in 1609.)