Q: A nomenclature issue in Complex Analysis, what is difference between between writing "f(z)" and "f"? As stated in the subject, this is just a curiosity about the nomenclature that is used in some Complex Analysis textbooks (particularly in problem statements).  I would think that writing "f(z)" would be the most general method of indicating f is a function in the complex plane.  Does simply writing "f" mean the same thing as "f(z)" or am I missing out on something serious here?
Thanks!

A: Technically, the function is $f$, not $f(z)$; here, $f(z)$ is the value of the function $f$ at some complex number $z$. So $f$ is the function (which is not a complex number), and $f(z)$ is a value of that function (which is a complex number).
However, writing $f(z)$ rather than $f$ usually (but not always!) causes no confusion. In my own opinion, you should write $f$ to be correct.
Question: Why do many mathematicians write "$f(z)$" rather than simply "$f$" if the latter is more correct?
Here's my opinion. Every time one introduces a function $f$, he/she must mention three items: the domain of $f$; the codomain of $f$; the value of $f$ for each $z$ in its domain. Now, mathematicians usually avoid giving all this info by simply stating $f(z)$ for every $z$ in the domain of $f$, and they assume the reader understands that the domain of $f$ is taken to be "the set of all $z$ for which $f(z)$ makes sense." (They also assume the reader will understand that the codomain is some large set. For complex-valued $f$, it's usually all of $\mathbb{C}$.) So after giving $f(z)$, all three items are known. No harm done.

A: The function $f$ takes $x$ to $f(x)$. When one writes $$f(x)=3x$$ they are not describing the function $3x$ but rather the function that takes an input and outputs three times said input.
It is often easiest to describe a function using notation like $f(x)$, For example, a function that takes an input and squares it can be understood through the expression $$f(x) = x^2$$
while an alternative is less intuitive: $f$ is a function that squares its input.

A: You have two conflicting traditions of writing functions here:

*

*the old-fashioned way, where the letter used for the argument shows what the domain of the function is, e.g. $f(n)$, $g(k)$ are probably functions on the integers, $f(x)$, $g(y)$ probably takes real numbers, and $f(z)$, $g(w) $ complex numbers, $f(A)$ is often a function on sets? (The disadvantages of this notation are best underlined by the fact that I had to use the word "probably" here: any notational convention is bound to be broken by some idiot who thinks he knows better, and $k$ is not always an integer, for example),

*the newer tradition of more formalised function notation, where functions are very definitively separate objects from their values taken on points: $f: A \to B$ is a thing that you give an input from the set $A$ and it returns a unique output from the set $B$. Then the notation $f(z)$ means "the value that $f$ gives you when you feed it $z$".

The point is really that complex analysis is such an old-fashioned subject (there are perfectly useable textbooks on it written in the 1890s and 1920s) that to a certain extent it has remained traditionally immune to the new formalism of notation. Hence in complex analysis $f(z)$ is a function $\mathbb{C} \supseteq D \to \mathbb{C}$ of a complex variable $z$. This is also rather similar to the abstract algebra tradition of using $X$ as an "indeterminant": not a specific value in the original algebraic object, but an extra symbol that we may give a value later if we so choose, but not immediately.
(Personal anecdote: I know a logician who, due to his unusual route into Mathematics, took his first complex analysis course aged sixtysomething and was very surprised that every function was called $f$ and written as $f(z)$, even when considered as a function and not a specific value.)
(Real analysis probably has not experienced the same ossification since it's much more mainstream, has a pile of more recent work to tie directly into it, and was one of the main topics that the more rigorous mathematicians got hold of to spread their ideology: witness the horrors of the entirely symbolic definition of the limit.)

A: To quote my answer this question:

There is a technical difference between $f$ and $f(x)$ that I want to
  elaborate on.
$f$ is a function. $f(x)$ is a function evaluated at an indeterminate
  (this might be the wrong word for it, but my brain is on the fritz)
  point, $x$. Thus the sentence "$f(x)$ is differentiable" is
  technically incorrect because $f(x)$ is the value of $f$ at $x$ and is
  therefore a number and not a function. In contrast, "$f$ is
  differentiable" is correct (of course, its only correct when it is in
  fact true). For another example, "$f$ is given by $x^2+1$" is also
  wrong. $f$ is given by $\{(x,y)\in S:x^2+1=y\}$, or however your
  underlying foundation specifies functions. It is $f(x)$ that is given
  by $x^2+1$.
In practice, this difference rarely is relevant and the vast majority
  of people are content to wave their hands and ignore it. Instead, they
  use $f(x)$ to refer to both the function and the function evaluated at
  the indeterminate point.
Ironically, the main place that people attend to this difference is
  done incorrectly. People write $f\in\mathbb{Z}[x]$ thinking that
  that's preferred to $f(x)$, but $f$ is not an element of
  $\mathbb{Z}[x]$ because that's not a set of functions - it's a ring of
  numbers. It happens to be that these numbers have a particular
  correspondence to functions from $\mathbb{Z}$ to $\mathbb{Z}$ and that
  $\mathbb{Z}[x]$ is isomorphic to an interesting subset of that set of
  functions, but they are distinct structures.

A: As others pointed out, when writing $f(z)$ you basically are referencing "the value that $f$ takes when given an arbitrary value $z$", which can be anything.
My teachers used to say that whenever you use arbitrary terms, you must specify which values they can take, as in the example below :
$f(z) = z+4$ where $z \in \Bbb C$
Meaning "$f$ is a function that returns $z+4$ for any complex number $z$"
Amusingly, you can name either the function and the parameter whatever floats your boat. I knew someone who would draw skulls for functions and fruits for arbitrary params (and that bothered some teachers even though it was totally legit).
Still, to truly answer your question, if you want to stick to definitions, you have to distinguish the name of the function (which in your case is $f$ but could be anything) and the value it takes when given a certain value (what you wrote $f(z)$), and specify its domain ($\Bbb C$ in your case).
You can even have functions that take inputs in a domain and give results in another domain, as $$f : \Bbb R \to \Bbb C$$ $$x \to x + i$$
Read as "a function $f$ that takes a real input $x$ and returns a complex output $x+i$".


Q: VirtualBox - Sharing a folder I'm a Windows 10 user, running macOS High Sierra 10.13 via VirtualBox 5.1.28.
I didn't fully understand how to share a folder.
The part that I did understand and did, is:

*

*Devices → Insert Guest Additions CD image...

*
But then, in macOS, I type in the terminal:
sudo mount -t vboxsf release_builds ~/Downloads/SteamCMD-GUI

And I get the error:
mount: exec /Library/Filesystems/vboxsf.fs/Contents/Resources/mount_vboxsf for /Users/avi12/Downloads/SteamCMD-GUI: No such file or directory

Later, I checked the directory /Library/Filesystems, and found that:

Which means that, there's actually no directory vboxsf.fs, so there would obviously be an error.
The question is then, what part am I missing?

A: There are no guest additions for macOS in VirtualBox. The shared folder feature of VirtualBox won't work here.
You have to configure a share on the host system and access it from inside the guest with one of the common methods:

*

*Finder > Go > Connect to server... cmdK

*Terminal: mount -t smbfs //username:password@server/share .../mountpoint

*Finder window > sidebar > Shared > choose share >

Some network connection between host and guest is required (e.g NAT or bridged adapter). Using the latter requires to set up an IP-address in macOS in the same network as the host's adapter.

To set up a bridged adapter for a guest (which has to be shut down) do the following:

*

*Choose the VM > Settings > Network > Adapter 1 > Check Enable Network Adapter > Attached to > Bridged Adapter > choose a network interface of the host (usually either Ethernet or Wi-Fi)

*Check the IP config of this interface in the host (e.g. IP= 192.168.0.2 Netmask= 255.255.255.0 Gateway=192.168.0.1 DNS=8.8.8.8)

*Use the same config in the guest but choose a different IP (e.g. 192.168.0.111)

*Connect from the guest to the host with cmdK > enter smb://192.168.0.2/Share_name > enter the credentials


Q: How to form str.decode line? With this line
str(hex(int(207))).decode('cp1251',errors='strict')

I get
'str' object has no attribute 'decode'

What is the correct way to format the line?

A: Problem
The decode method you want belongs to Bytes and BytesArray objects. So you need to convert your hex string to Bytes (or BytesArray I guess).
Solution
For this, you can use the fromhex method to convert the hex string. But it may require some formatting beforehand to exclude the '0x' part of the string. You may be better off therefore using Python's format, or f-strings, instead of hex.
Here is an example.
integer = 207
hexstring = f'{integer:x}'
hexbytes = bytes.fromhex(hexstring)
decoded = hexbytes.decode('cp1251',errors='strict')

Of course, you can combine the above into your original one-liner if you wish.


Q: Magento 2: Less Compilation Failing I'm working with a set of Less CSS files I didn't write in Magento 2.  During compilation, I get the following error
Compilation from source:
frontend/Infortis/base/en_US/css/custom.less

Compilation from source:
frontend/Infortis/base/en_US/css/custom.less>
#0 /path/to/magento/framework/View/Asset/PreProcessor/AlternativeSource.php(155): Magento\Framework\Css\PreProcessor\Adapter\Less\Processor->processContent(Object(Magento\Framework\View\Asset\File))

I know I can start debugging from line 155 in AlternativeSource.php -- but does anyone know what this cryptic error means?

A: I think this may happen because the generated CSS content is empty.
See: https://github.com/magento/magento2/blob/f748e57d04f65cb0b6f3d22cfc00602e6772e51d/lib/internal/Magento/Framework/Css/PreProcessor/Adapter/Less/Processor.php#L92.


Q: Android LruCache between two activities I read about using LruCache from developer.android.com, and I create a blurred Bitmap from one activity and put it into cache, now that I want to access the cached image from another activity but it returned null. Any examples or links on how to properly use cache will be greatly appreciated, thanks!

A: The LruCache is being instantiated in one class. It won't be accessible from another class. You could try the approach mentioned in this answer
https://stackoverflow.com/a/14325075/2931650


Q: How do I use audispd to send messages forwareded from a remote system to local syslog Using RHEL6, I currently have audispd setup to send logs to a remote server. The remote server successfully receives the messages, and writes them to the remote audit log. My problem is, I can't seem to get the forwarded messages(local ones work) to be processed by audispd and to be written to rsyslog.
This doesn't work.
box1 auditd ===> box1 audispd ===> box2 auditd XXX> box2 audispd XXX> box2 rsyslog
This does.
box2 auditd ===> box2 audispd ===> box2 rsyslog
I know generally how to configure audispd to send local logs to rsyslog, but the forwarded logs are not going to rsyslog. The X's above show where the traffic is not reaching its destination.
I'm not looking to use imfile or other workarounds unless it is not possible to send forwarded messages through audispd on box2. I know I can send to rsyslog on box1, but it is my intention not to.


Q: Geotiff Mollweide and geotools I am new to GIS and I want to read population data from a GeoTiff Grid using the java geotools library.
The following throws a runtime error
GridCoverage2D image  = new GeoTiffReader(f);

gives
Error message: GeoTiffMetadata2CRSAdapter::createCoordinateSystem:Only
Geographic & Projected Systems are supported.

Is there a way to have geotools to use Mollweide ?
Or can I convert the tiff file ?
Below is the gdalinfo.
Driver: GTiff/GeoTIFF
Files: GHS_POP_GPW42015_GLOBE_R2015A_54009_1k_v1_0.tif
       GHS_POP_GPW42015_GLOBE_R2015A_54009_1k_v1_0.tif.ovr
       GHS_POP_GPW42015_GLOBE_R2015A_54009_1k_v1_0.tif.aux.xml
Size is 35497, 15236
Coordinate System is:
PROJCS["World_Mollweide",
    GEOGCS["GCS_WGS_1984",
        DATUM["D_WGS_1984",
            SPHEROID["WGS_1984",6378137.0,298.257223563]],
        PRIMEM["Greenwich",0.0],
        UNIT["Degree",0.017453292519943295]],
    PROJECTION["Mollweide"],
    PARAMETER["False_Easting",0.0],
    PARAMETER["False_Northing",0.0],
    PARAMETER["Central_Meridian",0.0],
    UNIT["Meter",1.0]]
Origin = (-17619594.547443531453609,8751029.461868489161134)
Pixel Size = (1000.000000000000000,-1000.000000000000000)
Metadata:
  AREA_OR_POINT=Area
Image Structure Metadata:
  COMPRESSION=LZW
  INTERLEAVE=BAND
Corner Coordinates:
Upper Left  (-17619594.547, 8751029.462) (  5d15'16.97"W, 83d38'22.73"N)
Lower Left  (-17619594.547,-6484970.538) (107d 3'58.73"E, 55d59' 2.97"S)
Upper Right (17877405.453, 8751029.462) ( 15d52' 0.05"E, 83d38'22.73"N)
Lower Right (17877405.453,-6484970.538) (103d21'55.35"W, 55d59' 2.97"S)
Center      (  128905.453, 1133029.462) (  1d17'47.25"E,  9d10'43.07"N)

SOLUTION from @IanTurton:
I created a epsg.properties file with the line indicated by Ian.
And added the following code:
   URL epsg = getClass().getClassLoader().getResource("epsg.properties");
          if (epsg != null) {
           Hints hints =
            new Hints(Hints.CRS_AUTHORITY_FACTORY, PropertyAuthorityFactory.class);
           ReferencingFactoryContainer referencingFactoryContainer =
            ReferencingFactoryContainer.instance(hints);
           PropertyAuthorityFactory factory;
            factory = new PropertyAuthorityFactory(
                            referencingFactoryContainer,
                            Citations.fromName("EPSG"),
                            epsg);
            ReferencingFactoryFinder.addAuthorityFactory(factory);
            ReferencingFactoryFinder.scanForPlugins();
}
          else throw new IOException("properties not found");

A: The ability to use Mollweide has been in GeoTools and GeoServer for sometime
but you have to add the definition to the local projections file as it is not a standard EPSG projection.
You need to add
54009=PROJCS[“World_Mollweide”, GEOGCS[“WGS_1984″,DATUM[“WGS_1984″,SPHEROID[“WGS_1984″,6378137.0,298.257223563]], PRIMEM[“Greenwich”,0.0],UNIT[“Degree”,0.0174532925199433]],PROJECTION[“Mollweide”], PARAMETER[“Central_Meridian”,0.0],UNIT[“Meter”,1.0]] 54012=PROJCS[“World_Eckert_IV”,  GEOGCS[“WGS_1984″,DATUM[“WGS_1984″,SPHEROID[“WGS_1984″,6378137.0,298.257223563]], PRIMEM[“Greenwich”,0.0],UNIT[“Degree”,0.0174532925199433]],PROJECTION[“Eckert_IV”], PARAMETER[“Central_Meridian”,0.0],UNIT[“Meter”,1.0]]

to your epgs.properties file. You'll need to include gt-epsg-wkt module, there are instructions in the referencing FAQ.


Q: Can't bind to a property I've got the following markup.
<TextBox x:Name="Address"
         Text="{x:Static local:MainWindow.Boundie.SomeProp}"
</TextBox>

In the code behind I have a static property like so.
static Something Boundie { get; set; }

public class Something { public String SomeProp { get; set; } }

The problem is that it nags that "type expected" when I hover over Boundie and "static member expected" when I hover over SomeProp. When I leave out the latter, it only complains that the expected type is String but it only sees Something.
How do I bind to a static member's non-static field?
Why I want to do that? Because I want to reuse the domain object model and those classes are not equipped with static members.

A: SomeProp is instance property so you cannot use x:Static to access that. You can bind to it using combination of static Source and Path
<TextBox ...
         Text="{Binding
           Source={x:Static local:MainWindow.Boundie},
           Path=SomeProp}"/>

A: <object property="{x:Static prefix:typeName.staticMemberName}" .../>

http://msdn.microsoft.com/en-us/library/ms742135.aspx


Q: access 2016 System resource exceeded I am try to migrate from access 2003 to 2016 When I am importing my objects everything is fine. Only,on the process of importing 3 tables, I am getting this error.

System resource exceeded

They are big tables too.
There is no hotfix for access 2016, Total table quantity around 100 tables
If you help me I really appreciate

A: Found solution here:
https://answers.microsoft.com/en-us/msoffice/forum/all/ms-access-2016-system-resource-exceeded/df80f64a-f233-467e-89df-f05a8d58bc77
In short:
 task manager/processes tab, find msaccess, right click and select set affinity.... option.  I had 6 CPUs ticked (0 to 5).  I un-ticked them all and just ticked the 0 CPU.

A: Not sure if this will help you, but I've managed to resolve this error by wrapping fields referenced in the WHERE clause with Nz e.g.
instead of
WHERE ReportDate = Date

use
WHERE Nz(ReportDate,ReportDate) = Date

It's strange but it seems to work for me, I've found the issue is often related to indexed fields, so I always add it to those fields first

A: Since currently there is no hot fix for 2016 version you have to merge either to 2010 or 2013. Then you can try merging to 2016.
Please check this link:
https://social.technet.microsoft.com/Forums/en-US/aedecca8-aa7d-417f-9f03-6e63e36f0c5d/access-2016-system-resources-exceeded?forum=Office2016setupdeploy&prof=required


Q: load RetainFragment in a Fragment Hello Android Developer,
i follow the Display Images Guide from Android Developers and want to load my initialized cache from a RetainFragment if i rotate my device. A do this in my ListFragments onActivityCreated() method but the fragment is every time new created and not reused.
I do something like this:
RetainFragment
class RetainFragment extends Fragment {
private static final String TAG = "RetainFragment";
public LruCache mRetainedCache;

public RetainFragment() {}

public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
    RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
    if (fragment == null) {
        fragment = new RetainFragment();
    }
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

}
And this: ListFragment
@Override
public void onActivityCreated( Bundle savedInstanceState )
{
    super.onActivityCreated( savedInstanceState );

    RetainFragment mRetainFragment = RetainFragment.findOrCreateRetainFragment(getFragmentManager());
    LruCache mMemoryCache = RetainFragment.mRetainedCache;
    if (mMemoryCache == null)
    {
        mMemoryCache = new LruCache(cacheSize);
        mRetainFragment.mRetainedCache = mMemoryCache;
    }
    else
    {
        mMemoryCache = mRetainFragment.mRetainedCache;
    }
    ...
}

A: It looks to me like they forgot to actually attach that RetainFragment somehow to the Activity so FragmentManager has a chance to find it. Fragments that are not attached don't survive configuration changes.
Not sure if but it should work with the addition below
public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
    RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
    if (fragment == null) {
        fragment = new RetainFragment();
        // add this line
        fm.beginTransaction().add(fragment, TAG).commit();
    }
    return fragment;
}


Q: Drawing a physics body's path? I've been working on a first-person shooter game with Bullet and OpenGL, and now have it to the point of being able to fire bullets through the scene. I'm now looking to draw the path these bullets take, from starting position to their ending position, with the entire path staying drawn until the next bullet is fired (so that the screen isn't cluttered).
I'm basically just looking for something like a red line that extends to the bullet's new position each frame, or something like that. So, by the time the bullet has gone from the gun to its final stopping place, the red line will show the exact path it took, what it bounced off of, etc.
I've tried looking for examples but I can't find anything useful. I've seen mention of leaving a trail behind an object using an accumulation buffer, but that's not really what I want.
How can this be done? Does everyone know of any examples or tutorials for this?

A: just make vbo of points
and then
...

glVertexAttribPointer(.., 1, GL_FLOAT, GL_FALSE, 0, (void*)0);

glDrawArrays(GL_POINTS,0,.. );

Use math you have to assign each.
But it's not so easy. I think it can be done with deploy of second pair of shaders /vao. OpenGL multiple draw calls with unique shaders gives blank screen


Q: ggplot: using geom_smooth to plot variance I am making a  time series plot with ggplot.  I have the mean and the variance of the 5 variables of interest. I can plot the variance with error bars, but when I try to do it with geom_smooth()/stat_smooth() it doesn't work well.
   ggplot(data = df4, aes(x = times, y = value, colour = variable)) + geom_line()+
        geom_errorbar(aes(ymin = value-var, ymax = value+var))+
        geom_errorbarh(aes(xmin = value-var, xmax = value+var))+ geom_smooth()

Output figure


Q: How to make a relationship beetween radiobuttons? Please, help with this situation: how can I make relations (using jquery) between payment and delivery types? For example, if user choose "Pre Order" in payment - in delivery automatically checked "Pre Order, delivery not available". And if user choose "PayPal" he is given a choice between "Mail Service" and "AIR MAIL", but "Pre Order, delivery not available" is readonly. I appreciate your help.
Payment type:
<input type="radio" name="payment" value="10" class="payment-item" id="pay-type-10" onclick="shEvOrd('payment',this)">Pre Order
<input type="radio" name="payment" value="11" class="payment-item" id="pay-type-11" onclick="shEvOrd('payment',this)">PayPal

Delivery type:
<input type="radio" name="delivery" value="7" class="delivery-item" id="del-type-7" onclick="shEvOrd('delivery',this,1)">Pre Order, delivery not available
<input type="radio" name="delivery" value="6" class="delivery-item" id="del-type-6" onclick="shEvOrd('delivery',this,1)">Mail Service
<input type="radio" name="delivery" value="5" class="delivery-item" id="del-type-5" onclick="shEvOrd('delivery',this,1)">AIR MAIL

<input type="button" value="Place order" id="order-button" onclick="shopCheckOut();this.order.reset">

A: You can try this
// attach a click event to the payment radio group
$(".payment-item").click(function(){

    var payment = $("input:radio[name='payment']:checked").val(), // check the current value
        isPaypal = payment !== "10", // a simple check to see what was selected
        delivery = $("#del-type-7"); // get the radio element with the pre-order option

    return delivery.prop({
        // Disabled if `isPaypal` is true
        disabled: isPaypal,
        // Checked if `isPaypal` is true
        checked: !isPaypal
    });
});

Have a look at the demo http://jsfiddle.net/jasonnathan/3s3Nn/2/

A: jsBin demo
All you need:
var $delType7 = $("#del-type-7");       // Cache your elements
$("[name='payment']").click(function(){
    var PPal = $("[name='payment'][value='10']").is(':checked'); // Boolean
    $delType7.prop({checked:!PPal, disabled:PPal}); // boolean to toggle states
});

Remove onclick from HTML
http://api.jquery.com/checked-selector/
http://api.jquery.com/prop/


Q: WordPress regex not working as expected I need to put a string like user-profile/id=3 into regex form. I tried 'user-profile/id=\d+$'  and also 'user-profile/([a-z][.][0-9]+)/?$', but none of them are working. What is the correct way?

A: Since your string is always in the format as above, you do not need a regex. Use a mere explode:
explode("/", $s)[1]

See this demo.
Another  non-regex approach: use strstr to get the substring after and including /, and then get the substring from the 1 char:
substr(strstr($s, "/"),1);

See another PHP demo

A: Your problem is that you aren't escaping the / character with a backslash.
Another problem you could face immediately after solving that one, is that you are using the $ character, which means end of line. If there are more characters afterwards, even just a single space, then it won't match.
If you try:
user-profile\/(id=\d+)

You'll probably find that it matches just fine. The brackets I added in will capture id=3 in capture group #1.

A: If you just want to extract id=3 I recommend to use preg_replace. Like:
$str = 'user-profile/id=3';
$after_preg = preg_replace('/user-profile\//', '', $str);
echo $after_preg;

If you want to get just a number it can be as follows:
$str = 'user-profile/id=3';
$after_preg = preg_replace('/user-profile\/id=/', '', $str);
echo $after_preg;

More about it you can read in PHP Manual: preg_replace
If you want to check if you string is like user-profile/id=3 you can use regex:
user-profile\/id=\d*


Q: Flutter: can't find class "FlutterFragment" I have a Flutter app create by flutter create command.
I have the MainActivity (which extends from FlutterActivity) and also a native activity that I opens it via MethodChannel.
Now I need to call another FlutterActivity embedded with a FlutterFragment but the class FlutterFragment simply doesn't exists.
My page stack would be like that:

*

*MainActivity(FlutterActivity) -> NativeActivity (with native code and layout) -> AnotherFlutterActivity.

I am following this tutorial: https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps
Ayone know why this is happening?
[√] Flutter (Channel stable, v1.2.1, on Microsoft Windows [versÃ£o 10.0.17763.379], locale pt-BR)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[√] IntelliJ IDEA Community Edition (version 2019.1)
[√] VS Code (version 1.30.1)
[√] Connected device (1 available)

A: This is probably because you haven't imported FlutterFragment in your activity, please add this line in your import statements.
import io.flutter.embedding.android.FlutterFragment;

Also, make sure to extend your activity from FlutterFragmentActivity. You will have to import it, add this line at the top of your file along with the other import statements.
Like so:
...
import io.flutter.app.FlutterFragmentActivity;
...

Hope this helps :)


Q: Notepad ++ Insert New Line Before 'else if' I'm trying to insert a new line before every instance of the phrase 'else if'. I know how to do this for a single word using
Find: else
Replace: \r

But I can't figure out how to search for a multi word string in the Find.
Apologies if these is really obvious; I've had a good hunt around regular expressions guides for Notepad ++ but I haven't been able to get anywhere.

A: Find: else if
Replace: \r\nelse if

Search Mode: Extended

A: Have a try with:
Find what: (\belse if\b)
Replace with: \n$1


Q: Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback unable to get the data on postman Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
"There was an unexpected error (type=Not Found, status=404) .
I executed multiple students detail on spring boot and then tried to run it on localhost:8080 but getting the error as written above.
used controller and mapping already still unable to resolve


Q: vb.net DateTimePicker remove time 12:00:00 AM im having a problem when viewing date on my listview.
on my SQL its okay that on my column "2016-28-11" that is fine
but when i view it on my listview in vb.net it said that "2016-28-11 12:00:00 am"
on my datetimepicker
Value: 11/28/2016
custom format: yyyy-MM-dd
format: custom
when i save the date it adds that time. can anyone help me?

A: When you add the date in your listview just use something like that:
 Dim NewItem As New ListViewItem
 NewItem.Text = "My Item"
 NewItem.SubItems.Add(mydate.tostring("yyyy-MM-dd"))
 ListView1.Items.Add(NewItem)

Just keep in mind mydate.tostring("yyyy-MM-dd") where mydate is a datetime.
Considerate your comments, here is the code:
.SubItems.Add(ds.Tables("studnum").Rows(i).Item(4).ToString)
Dim MyDate As DateTime = CDate(ds.Tables("studnum").Rows(i).Item(5).ToString)
.SubItems.Add(MyDate.ToString("yyyy-MM-dd"))


Q: How do I change tab url I'm currently editing an affiliate plugin. I have added the affiliate plugin as a tab in 'My account' as well as using the plugin's shortcode to display the content there. Although when I click on the dropdown and select 'Today' for example, the page redirects to an URL without 'affiliate-area' in it, therefore the filter doesn't work. How can I edit this so the filter works?
Thanks.
Current webpage output on load:

webpage output when 'Today' is selected from dropdown and 'Filter' button is clicked:

Code:
<?php
/**
 * Graphs
 *
 * This class handles building pretty report graphs
 *
 * @package     AffiliateWP
 * @copyright   Copyright (c) 2012, Pippin Williamson
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       1.0
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Affiliate_WP_Graph Class
 *
 * @since 1.0
 */
class Affiliate_WP_Graph {

    /*

    Simple example:

    data format for each point: array( location on x, location on y )

    $data = array(

        'Label' => array(
            array( 1, 5 ),
            array( 3, 8 ),
            array( 10, 2 )
        ),

        'Second Label' => array(
            array( 1, 7 ),
            array( 4, 5 ),
            array( 12, 8 )
        )
    );

    $graph = new Affiliate_WP_Graph( $data );
    $graph->display();

    */

    /**
     * Data to graph
     *
     * @var array
     * @since 1.0
     */
    public $data;

    /**
     * Unique ID for the graph
     *
     * @var string
     * @since 1.0
     */
    public $id = '';

    /**
     * Graph options
     *
     * @var array
     * @since 1.0
     */
    public $options = array();

    /**
     * Get things started
     *
     * @since 1.0
     */
    public function __construct( $_data = array() ) {

        $this->data = $_data;

        // Generate unique ID
        $this->id   = md5( rand() );

        // Setup default options;
        $this->options = array(
            'y_mode'          => null,
            'x_mode'          => null,
            'y_decimals'      => 0,
            'x_decimals'      => 0,
            'y_position'      => 'right',
            'time_format'     => '%d/%b',
            'ticksize_unit'   => 'day',
            'ticksize_num'    => 1,
            'multiple_y_axes' => false,
            'bgcolor'         => '#f9f9f9',
            'bordercolor'     => '#ccc',
            'borderwidth'     => 2,
            'bars'            => false,
            'lines'           => true,
            'points'          => true,
            'currency'        => true,
            'show_controls'   => true,
        );

    }

    /**
     * Set an option
     *
     * @param $key The option key to set
     * @param $value The value to assign to the key
     * @since 1.0
     */
    public function set( $key, $value ) {
        if( 'data' == $key ) {

            $this->data = $_data;

        } else {

            $this->options[ $key ] = $value;

        }
    }

    /**
     * Get an option
     *
     * @param $key The option key to get
     * @since 1.0
     */
    public function get( $key ) {
        return isset( $this->options[ $key ] ) ? $this->options[ $key ] : false;
    }

    /**
     * Get graph data
     *
     * @since 1.0
     */
    public function get_data() {
        return apply_filters( 'affwp_get_graph_data', $this->data, $this );
    }

    /**
     * Load the graphing library script
     *
     * @since 1.0
     */
    public function load_scripts() {
        // Use minified libraries if SCRIPT_DEBUG is turned off
        $suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
        wp_enqueue_script( 'jquery-flot', AFFILIATEWP_PLUGIN_URL . 'assets/js/jquery.flot' . $suffix . '.js' );

        if( $this->load_resize_script() ) {
            wp_enqueue_script( 'jquery-flot-resize', AFFILIATEWP_PLUGIN_URL . 'assets/js/jquery.flot.resize' . $suffix . '.js' );
        }
    }

    /**
     * Determines if the resize script should be loaded
     *
     * @since 1.1
     */
    public function load_resize_script() {

        $ret = true;

        // The DMS theme is known to cause some issues with the resize script
        if( defined( 'DMS_CORE' ) ) {
            $ret = false;
        }

        return apply_filters( 'affwp_load_flot_resize', $ret );
    }

    /**
     * Build the graph and return it as a string
     *
     * @var array
     * @since 1.0
     * @return string
     */
    public function build_graph() {
        $this->load_scripts();

        ob_start();

        if ( function_exists( 'wp_add_inline_script' ) ) {
            wp_add_inline_script( 'jquery-flot', $this->graph_js() );
        } else {
            // Back-compat for < WP 4.5.0.
            wp_scripts()->add_data( 'jquery-flot', 'after', array(
                wp_scripts()->get_data( 'jquery-flot', 'after' ),
                $this->graph_js()
            ) );
        }

        if ( false !== $this->get( 'show_controls' ) ) {
            echo $this->graph_controls();
        }
        ?><div id="affwp-graph-<?php echo $this->id; ?>" class="affwp-graph" style="height: 300px; width:100%;">
<?php
        return ob_get_clean();
    }

    /**
     * Retrieves the Graph initialization JS for output inline.
     *
     * @access public
     * @since  1.9.5
     *
     * @return string Graph JS output.
     */
    public function graph_js() {
        $yaxis_count = 1;

        ob_start();
        ?>
        var affwp_vars;
        jQuery( document ).ready( function($) {
            $.plot(
                $("#affwp-graph-<?php echo $this->id; ?>"),
                [
                    <?php foreach( $this->get_data() as $label => $data ) : ?>
                    {
                        label: "<?php echo esc_attr( $label ); ?>",
                        id: "<?php echo sanitize_key( $label ); ?>",
                        // data format is: [ point on x, value on y ]
                        data: [<?php foreach( $data as $point ) { echo '[' . implode( ',', $point ) . '],'; } ?>],
                        points: {
                            show: <?php echo $this->options['points'] ? 'true' : 'false'; ?>,
                        },
                        bars: {
                            show: <?php echo $this->options['bars'] ? 'true' : 'false'; ?>,
                            barWidth: 2,
                            align: 'center'
                        },
                        lines: {
                            show: <?php echo $this->options['lines'] ? 'true' : 'false'; ?>
                        },
                        <?php if( $this->options[ 'multiple_y_axes' ] ) : ?>
                        yaxis: <?php echo $yaxis_count; ?>
                        <?php endif; ?>
                    },
                    <?php $yaxis_count++; endforeach; ?>
                ],
                {
                    // Options
                    grid: {
                        show: true,
                        aboveData: false,
                        backgroundColor: "<?php echo $this->options[ 'bgcolor' ]; ?>",
                        borderColor: "<?php echo $this->options[ 'bordercolor' ]; ?>",
                        borderWidth: <?php echo absint( $this->options[ 'borderwidth' ] ); ?>,
                        clickable: false,
                        hoverable: true
                    },
                    xaxis: {
                        mode: "<?php echo $this->options['x_mode']; ?>",
                        timeFormat: "<?php echo $this->options['x_mode'] == 'time' ? $this->options['time_format'] : ''; ?>",
                        tickSize: "<?php echo $this->options['x_mode'] == 'time' ? '' : 1; ?>",
                        <?php if( $this->options['x_mode'] != 'time' ) : ?>
                        tickDecimals: <?php echo $this->options['x_decimals']; ?>
                        <?php endif; ?>
                    },
                    yaxis: {
                        position: 'right',
                        min: 0,
                        mode: "<?php echo $this->options['y_mode']; ?>",
                        timeFormat: "<?php echo $this->options['y_mode'] == 'time' ? $this->options['time_format'] : ''; ?>",
                        <?php if( $this->options['y_mode'] != 'time' ) : ?>
                        tickDecimals: <?php echo $this->options['y_decimals']; ?>
                        <?php endif; ?>
                    }
                }

            );

            function affwp_flot_tooltip(x, y, contents) {
                $('
' + contents + '
').css( {
                    position: 'absolute',
                    display: 'none',
                    top: y + 5,
                    left: x + 5,
                    border: '1px solid #fdd',
                    padding: '2px',
                    'background-color': '#fee',
                    opacity: 0.80
                }).appendTo("body").fadeIn(200);
            }

            var previousPoint = null;
            $("#affwp-graph-<?php echo $this->id; ?>").bind("plothover", function (event, pos, item) {
                $("#x").text(pos.x.toFixed(2));
                $("#y").text(pos.y.toFixed(2));
                if (item) {
                    if (previousPoint != item.dataIndex) {
                        previousPoint = item.dataIndex;
                        $("#affwp-flot-tooltip").remove();
                        var x = item.datapoint[0].toFixed(2),
                            y = item.datapoint[1].toFixed(2);

                        <?php if( $this->get( 'currency' ) ) : ?>
                        if( affwp_vars.currency_pos == 'before' ) {
                            affwp_flot_tooltip( item.pageX, item.pageY, item.series.label + ' ' + affwp_vars.currency_sign + y );
                        } else {
                            affwp_flot_tooltip( item.pageX, item.pageY, item.series.label + ' ' + y + affwp_vars.currency_sign );
                        }
                        <?php else : ?>
                        affwp_flot_tooltip( item.pageX, item.pageY, item.series.label + ' ' + y );
                        <?php endif; ?>
                    }
                } else {
                    $("#affwp-flot-tooltip").remove();
                    previousPoint = null;
                }
            });

            $( '#affwp-graphs-date-options' ).change( function() {
                var $this = $(this);
                if( $this.val() == 'other' ) {
                    $( '#affwp-date-range-options' ).css('display', 'inline-block');
                } else {
                    $( '#affwp-date-range-options' ).hide();
                }
            });

        });
        <?php
        return ob_get_clean();
    }

    /**
     * Output the final graph
     *
     * @since 1.0
     */
    public function display() {
        /**
         * Fires just prior to the graph output.
         *
         * @param stdClass $graph The graph object.
         */
        do_action( 'affwp_before_graph', $this );

        echo $this->build_graph();

        /**
         * Fires immediately after the graph output.
         *
         * @param stdClass $graph The graph object.
         */
        do_action( 'affwp_after_graph', $this );
    }

    /**
     * Show report graph date filters
     *
     * @since 1.0
     * @return void
    */
    function graph_controls() {
        $date_options = apply_filters( 'affwp_report_date_options', array(
            'today'         => __( 'Today', 'affiliate-wp' ),
            'yesterday'     => __( 'Yesterday', 'affiliate-wp' ),
            'this_week'     => __( 'This Week', 'affiliate-wp' ),
            'last_week'     => __( 'Last Week', 'affiliate-wp' ),
            'this_month'    => __( 'This Month', 'affiliate-wp' ),
            'last_month'    => __( 'Last Month', 'affiliate-wp' ),
            'this_quarter'  => __( 'This Quarter', 'affiliate-wp' ),
            'last_quarter'  => __( 'Last Quarter', 'affiliate-wp' ),
            'this_year'     => __( 'This Year', 'affiliate-wp' ),
            'last_year'     => __( 'Last Year', 'affiliate-wp' ),
            'other'         => __( 'Custom', 'affiliate-wp' )
        ) );

        $dates = affwp_get_report_dates();

        $display = $dates['range'] == 'other' ? 'style="display:inline-block;"' : 'style="display:none;"';

        $current_time = current_time( 'timestamp' );

        ?>
        <form id="affwp-graphs-filter" method="get">

                <?php if( is_admin() ) : ?>
                    <?php $tab = isset( $_GET['tab'] ) ? $_GET['tab'] : 'referral'; ?>
                    <?php $page = isset( $_GET['page'] ) ? $_GET['page'] : 'affiliate-wp'; ?>
                    <input type="hidden" name="page" value="<?php echo esc_attr( $page ); ?>"/>
                <?php else: ?>
                    <?php $tab = isset( $_GET['tab'] ) ? $_GET['tab'] : 'graphs'; ?>
                    <input type="hidden" name="page_id" value="<?php echo esc_attr( get_the_ID() ); ?>"/>
                <?php endif; ?>

                <input type="hidden" name="tab" value="<?php echo esc_attr( $tab ); ?>"/>

                <?php if( isset( $_GET['affiliate_id'] ) ) : ?>
                <input type="hidden" name="affiliate_id" value="<?php echo absint( $_GET['affiliate_id'] ); ?>"/>
                <input type="hidden" name="action" value="view_affiliate"/>
                <?php endif; ?>

                <select id="affwp-graphs-date-options" name="range">
                <?php
                    foreach ( $date_options as $key => $option ) {
                        echo '<option value="' . esc_attr( $key ) . '" ' . selected( $key, $dates['range'] ) . '>' . esc_html( $option ) . '</option>';
                    }
                ?>
                </select>

                <div id="affwp-date-range-options" <?php echo $display; ?>>

                    <?php
                    $from = empty( $_REQUEST['filter_from'] ) ? '' : $_REQUEST['filter_from'];
                    $to   = empty( $_REQUEST['filter_to'] )   ? '' : $_REQUEST['filter_to'];
                    ?>

                        <?php _ex( 'From', 'date filter', 'affiliate-wp' ); ?>
                        <input type="text" class="affwp-datepicker" autocomplete="off" name="filter_from" placeholder="<?php esc_attr_e( 'From - mm/dd/yyyy', 'affiliate-wp' ); ?>" aria-label="<?php esc_attr_e( 'From - mm/dd/yyyy', 'affiliate-wp' ); ?>" value="<?php echo esc_attr( $from ); ?>" />
                        <?php _ex( 'To', 'date filter', 'affiliate-wp' ); ?>
                        <input type="text" class="affwp-datepicker" autocomplete="off" name="filter_to" placeholder="<?php esc_attr_e( 'To - mm/dd/yyyy', 'affiliate-wp' ); ?>" aria-label="<?php esc_attr_e( 'To - mm/dd/yyyy', 'affiliate-wp' ); ?>" value="<?php echo esc_attr( $to ); ?>" />

                <input type="submit" class="button" value="<?php _e( 'Filter', 'affiliate-wp' ); ?>"/>

        </form>
        <?php
    }

}

/**
 * Sets up the dates used to filter graph data
 *
 * Date sent via $_GET is read first and then modified (if needed) to match the
 * selected date-range (if any)
 *
 * @since 1.0
 * @return array
*/
function affwp_get_report_dates() {
    $dates = array();

    $current_time = current_time( 'timestamp' );

    $dates['date_from']  = ! empty( $_REQUEST['filter_from'] ) ? $_REQUEST['filter_from'] : date( 'j/n/Y', $current_time );
    $dates['date_to']    = ! empty( $_REQUEST['filter_to'] )   ? $_REQUEST['filter_to']   : date( 'j/n/Y', $current_time );

    $variable_from_time  = ! empty( $_REQUEST['filter_from'] ) ? strtotime( $dates['date_from'] ) : $current_time;
    $variable_to_time    = ! empty( $_REQUEST['filter_to'] )   ? strtotime( $dates['date_to'] )   : $current_time;

    $dates['range']      = isset( $_GET['range'] )      ? $_GET['range']      : 'this_month';
    $dates['year']       = isset( $_GET['year_start'] ) ? $_GET['year_start'] : date( 'Y', $variable_from_time );
    $dates['year_end']   = isset( $_GET['year_end'] )   ? $_GET['year_end']   : date( 'Y', $variable_to_time );
    $dates['m_start']    = isset( $_GET['m_start'] )    ? $_GET['m_start']    : date( 'n', $variable_from_time );
    $dates['m_end']      = isset( $_GET['m_end'] )      ? $_GET['m_end']      : date( 'n', $variable_to_time );
    $dates['day']        = isset( $_GET['day'] )        ? $_GET['day']        : date( 'd', $variable_from_time );
    $dates['day_end']    = isset( $_GET['day_end'] )    ? $_GET['day_end']    : date( 'd', $variable_to_time );

    // Modify dates based on predefined ranges
    switch ( $dates['range'] ) :

        case 'this_month' :
            $dates['day']       = 1;
            $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, $dates['m_start'], date( 'Y', $current_time ) );
            $dates['m_start']   = date( 'n', $current_time );
            $dates['m_end']     = date( 'n', $current_time );
            $dates['year']      = date( 'Y', $current_time );
        break;

        case 'last_month' :
            if( date( 'n' ) == 1 ) {
                $dates['day']     = 1;
                $dates['day_end'] = cal_days_in_month( CAL_GREGORIAN, 12, date( 'Y', $current_time ) );
                $dates['m_start'] = 12;
                $dates['m_end']   = 12;
                $dates['year']    = date( 'Y', $current_time ) - 1;
                $dates['year_end']= date( 'Y', $current_time ) - 1;
            } else {
                $dates['day']     = 1;
                $dates['day_end'] = cal_days_in_month( CAL_GREGORIAN, date( 'n' ) - 1, date( 'Y', $current_time ) );
                $dates['m_start'] = date( 'n' ) - 1;
                $dates['m_end']   = date( 'n' ) - 1;
                $dates['year_end']= $dates['year'];
            }
        break;

        case 'today' :
            $dates['day']       = date( 'd', $current_time );
            $dates['day_end']   = date( 'd', $current_time );
            $dates['m_start']   = date( 'n', $current_time );
            $dates['m_end']     = date( 'n', $current_time );
            $dates['year']      = date( 'Y', $current_time );
        break;

        case 'yesterday' :
            $month              = date( 'n', $current_time ) == 1 && date( 'd', $current_time ) == 1 ? 12 : date( 'n', $current_time );
            $days_in_month      = cal_days_in_month( CAL_GREGORIAN, $month, date( 'Y', $current_time ) );
            $yesterday          = date( 'd', $current_time ) == 1 ? $days_in_month : date( 'd', $current_time ) - 1;
            $dates['day']       = $yesterday;
            $dates['day_end']   = $yesterday;
            $dates['m_start']   = $month;
            $dates['m_end']     = $month;
            $dates['year']      = $month == 1 && date( 'd', $current_time ) == 1 ? date( 'Y', $current_time ) - 1 : date( 'Y', $current_time );
        break;

        case 'this_week' :
            $dates['day']       = date( 'd', $current_time - ( date( 'w', $current_time ) - 1 ) *60*60*24 ) - 1;
            $dates['day']      += get_option( 'start_of_week' );
            $dates['day_end']   = $dates['day'] + 6;
            $dates['m_start']   = date( 'n', $current_time );
            $dates['m_end']     = date( 'n', $current_time );
            $dates['year']      = date( 'Y', $current_time );
        break;

        case 'last_week' :
            $dates['day']       = date( 'd', $current_time - ( date( 'w' ) - 1 ) *60*60*24 ) - 8;
            $dates['day']      += get_option( 'start_of_week' );
            $dates['day_end']   = $dates['day'] + 6;
            $dates['year']      = date( 'Y', $current_time );

            if( date( 'j', $current_time ) <= 7 ) {
                $dates['m_start']   = date( 'n', $current_time ) - 1;
                $dates['m_end']     = date( 'n', $current_time ) - 1;
                if( $dates['m_start'] <= 1 ) {
                    $dates['year'] = date( 'Y', $current_time ) - 1;
                    $dates['year_end'] = date( 'Y', $current_time ) - 1;
                }
            } else {
                $dates['m_start']   = date( 'n', $current_time );
                $dates['m_end']     = date( 'n', $current_time );
            }
        break;

        case 'this_quarter' :
            $month_now = date( 'n', $current_time );
            $dates['day'] = 1;

            if ( $month_now <= 3 ) {

                $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, 4, date( 'Y', $current_time ) );
                $dates['m_start']   = 1;
                $dates['m_end']     = 4;
                $dates['year']      = date( 'Y', $current_time );

            } else if ( $month_now <= 6 ) {

                $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, 7, date( 'Y', $current_time ) );
                $dates['m_start']   = 4;
                $dates['m_end']     = 7;
                $dates['year']      = date( 'Y', $current_time );

            } else if ( $month_now <= 9 ) {

                $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, 10, date( 'Y', $current_time ) );
                $dates['m_start']   = 7;
                $dates['m_end']     = 10;
                $dates['year']      = date( 'Y', $current_time );

            } else {

                $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, 1, date( 'Y', $current_time ) + 1 );
                $dates['m_start']   = 10;
                $dates['m_end']     = 1;
                $dates['year']      = date( 'Y', $current_time );
                $dates['year_end']  = date( 'Y', $current_time ) + 1;

            }
        break;

        case 'last_quarter' :
            $month_now = date( 'n' );
            $dates['day'] = 1;

            if ( $month_now <= 3 ) {

                $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, 9, date( 'Y', $current_time ) - 1 );
                $dates['m_start']   = 10;
                $dates['m_end']     = 12;
                $dates['year']      = date( 'Y', $current_time ) - 1; // Previous year

            } else if ( $month_now <= 6 ) {

                $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, 3, date( 'Y', $current_time ) );
                $dates['m_start']   = 1;
                $dates['m_end']     = 3;
                $dates['year']      = date( 'Y', $current_time );

            } else if ( $month_now <= 9 ) {

                $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, 6, date( 'Y', $current_time ) );
                $dates['m_start']   = 4;
                $dates['m_end']     = 6;
                $dates['year']      = date( 'Y', $current_time );

            } else {

                $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, 9, date( 'Y', $current_time ) );
                $dates['m_start']   = 7;
                $dates['m_end']     = 9;
                $dates['year']      = date( 'Y', $current_time );

            }
        break;

        case 'this_year' :
            $dates['day']       = 1;
            $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, 12, date( 'Y', $current_time ) );
            $dates['m_start']   = 1;
            $dates['m_end']     = 12;
            $dates['year']      = date( 'Y', $current_time );
            $dates['year_end']  = date( 'Y', $current_time );
        break;

        case 'last_year' :
            $dates['day']       = 1;
            $dates['day_end']   = cal_days_in_month( CAL_GREGORIAN, 12, date( 'Y', $current_time ) - 1 );
            $dates['m_start']   = 1;
            $dates['m_end']     = 12;
            $dates['year']      = date( 'Y', $current_time ) - 1;
            $dates['year_end']  = date( 'Y', $current_time ) - 1;
        break;

    endswitch;

    return apply_filters( 'affwp_report_dates', $dates );
}

A: A link to the affiliate area from the WooCommerce account page is being added in AffiliateWP 2.1.


Q: How can I find out which data record goes into which cluster in R using kohonen and means I have clustered my data with an SOM and kmeans
install.packages("kohonen")
library(kohonen)
set.seed(7)

som_grid <- somgrid(xdim = 8, ydim=8, topo="hexagonal")

som_model <- som(umfrage_veraendert_kurz,
             grid=som_grid,
             rlen=500,
             alpha=c(0.05,0.01),
             keep.data = TRUE )

I get from my som_model the "codes" and clustered it with kmeans
mydata <- som_model$codes

clusterzentren <- kmeans(mydata, center=3)
head(clusterzentren)

I have now 3 clusters but I don't know which data record goes to which cluster? How can I find it out?
Thanks for any help

A: The return value of kmeans is a S3 object which contains not only the centers, but also the cluster assignment.
See the R manual of kmeans for details.


Q: How to keep aliases in multiple shell sessions? I want to set up some alias and would like to keep them so I don't have to reset them every time I have a new Terminal open. How can I do that? Would it require modifying hidden files?

EDIT: I'm using Mac, I found a bashrc under /etc, is it the one?

A: Yup – you'll need to put it in ~/.bash_profile:
alias ls='ls --color=auto'

A: It depends on your shell/system e.g., for bash on Ubuntu check out ~/.bashrc, ~/.bash_profile files.


Q: Make TextField in libGDX java I've got problem with making TextField in my libGDX project. So I just take some compleate example of initialize Label from web. And it's work well.
     public ItemCreateScreen()
{
     Label.LabelStyle Label1Style = new Label.LabelStyle();
    BitmapFont myFont = new BitmapFont();
    myFont.scale(2);
    Label1Style.font = myFont;
    Label1Style.fontColor = Color.RED;

    Label Label1 = new Label("Title (BitmapFont)",Label1Style);
    Label1.setSize(Gdx.graphics.getWidth(),row_height);
    Label1.setPosition(0,Gdx.graphics.getHeight()-row_height*2);
    Label1.setText("Hello folks");
    mLabels.add(Label1);
}

@Override
public void drawn(SpriteBatch fBatch)
{
    mLabels.get(0).draw(fBatch,255);
}

When i just replace textually "Label" with "TextField", and feel great because compilation isnt show any error.
      public ItemCreateScreen()
{
    TextField.TextFieldStyle TextField1Style = new
    TextField.TextFieldStyle();
    BitmapFont myFont = new BitmapFont();
    myFont.scale(2);
    TextField1Style.font = myFont;
    TextField1Style.fontColor = Color.RED;

    TextField TextField1 = new TextField("Title (BitmapFont)",TextField1Style);
    TextField1.setSize(Gdx.graphics.getWidth(),row_height);
    TextField1.setPosition(0,Gdx.graphics.getHeight()-row_height*2);
    TextField1.setText("Hello folks");
    mTextFields.add(TextField1);
}

@Override
public void drawn(SpriteBatch fBatch)
{
    mTextFields.get(0).draw(fBatch,255);
}

But after build i dont see any TextField like it was before with Label.
What i have done wrong?


Q: Promise Chaining / Cascading to RxJS angular 1 to angular 2 I'm currently trying to convert some good old $http Promises into rxJs observables in angular2.
A very simple example of something I used to do frequently in angular 1:
// Some Factory in Angular 1
var somethings = [];
var service = {
    all: all
};
return service;

function all() {
    return $http
        .get('api/somethings')
        .then(function(response) {
            somethings = parseSomethings(response.data);
            return somethings;
        });
}

// Some Controller in Angular 1
var vm = this;
vm.somethings = [];
vm.loading = true;

loadThings();

function loadThings() {
    SomeFactory
        .all()
        .then(function(somethings) {
            vm.somethings = somethings;
        })
        .finally(function() {
            vm.loading = false;
        })
}

Now I can achieve something similar with angular2 using RxJs Observable and Subject. But I am unsure on how to return 'completion hooks'  down to the caller. (E.g.: The loading in the angular1 controller)
What I tried with for angular2 is something similar:
// Some Service in Angular 2
export class SomeService {
    private _somethings$: Subject<Something[]>;
    private dataStore: {
        somethings: Something[]
    };

    constructor(private http: Http) {}

    get _somethings$() : Observable<Something[]> {
        return this._somethings$.asObservable();
    }

    loadAll() {
        this.http
            .get(`api/somethings`)
            .map(response => response.json())
            .subscribe(
                response => {
                    this.dataStore.somethings = parseSomethings(response.data);
                    this._somethings$.next(this.dataStore.somethings);
                }
            );
    }
}

//Some Component in Angular 2
export class SomeComponent() {

    constructor(private someService: SomeService) {}

    ngOnInit() {
        this.someService.loadAll();
        this.somethings = this.someService.somethings$;
    }
}

Note
I used a Subject / Observable here so that when I create / update / remove 'something' I can call .next to notify the subscribers.
E.g.:
create(something: Something) : Observable<Something>{
    return this.http.post(`api/somethings`, JSON.stringify(something))
        .map(response => response.json())
        .do(
            something => {
                this.dataStore.somethings.push(something);
                this._somethings$.next(this.dataStore.somethings); //Notify the subscribers
            }
        );
}

Note
Here I used .do in the method and when calling the method in a 'form component' I subscribe just to get completion handler:
this.someService.create(something).subscribe(
(ok) => ...
(error) => ...
() => stop loading indicator
)

Questions

*

*How can we pass down a completion-hook to callers (e.g. angular 1 controller) in angular 2 with RxJs

*What alternative paths do exist to achieve similar behaviour ?

A: Your last code example is fine. Just use map() instead of subscribe() and subscribe at call site.
You can use
return http.post(...).toPromise(val => ...))

or
return http.post(...).map(...).toPromise(val => ...))

to get the same behavior as in Angular where you can chain subsequent calls with .then(...)


Q: Angular: add class to span selector I have the below code, I want to add a class to a span selector, but I have this error

Cannot read property 'classList' of null

<th *ngFor="let column of columns;"
    <ng-container *ngIf="column?.sortable">

    </ng-container>

if (this.columns) {
   this.columns.forEach(column => {
       if (column.sortable) {
           const parent: HTMLElement = document.getElementById("sort-" + column.field);

           this.renderer.setElementClass(parent, "sorting_asc", true);
       }
   })
}

A: I think you have overly complicated your code, You are using angular and I believe its not a good practice to access DOM elements using document.getElementById().
For your code to work, you will need to ensure that the view has loaded before you can access the DOM elements. You need to move your code to the AfterViewInit life cycle hook.
Below is how I would refactor the code
<th *ngFor="let column of columns;"
    <ng-container *ngIf="column?.sortable">

     </ng-container>

We simply bind to [class.sorting_asc]="column?.sortable" and let angular apply the classes for us


Q: I am trying to apply constraints on some random packets (I could apply to fixed packets) that I have to send to DUT The following code has two classes - packet and packet_1; packet  class has properties length and mode, packet class has the constraints that are required for length and mode. In packet_1 class I want to create 30 such packets and want to apply a constraint of length=6 for 10 random packets, I could do it for one particular(not random) packet, please let me know if this is the correct way and how to do it for 10 random packets ?
Following code generated 30 packets with 4th packet having length=6 and  complying with the other constraints, but how can do the same thing for 1 random packet (not a fixed 4th packet) or 10 random packets out of 30 .
 class packet;
 rand bit[1:0] mode;
 rand int length;
 int num;
 constraint mod_len {mode==0 -> length inside {[1:5]};
                  mode==1 -> length inside {[6:10]};
                  mode==2 -> length inside {[11:15]};
                  mode==3 -> length inside {[16:20]};};
 endclass

 class packet_1;
  packet p1;
  task pack();
  p1=new;
  p1.num=0;

  repeat(30)
  begin
  p1.num++;
  if(p1.num==4)
    p1.randomize with {(p1.length==6);} ;
  else
  p1.randomize ;
  $display("packet is %p",p1);
  end
  endtask
 endclass

  module a;
  packet_1 p2;
  initial
  begin
  p2=new();
  p2.pack();
  end
  endmodule

A: If you want exactly specific number of packets, then we can use a queue/array that stores random indices of constrained value to be stored.
class packet_1;
   packet p1;
   int NUM_CONSTRAINED_PKTS=10; // Number of pkts to be constrained
   int NUM_TOTAL_PKTS=30; // total number of pkts to be generated
   rand int q[$];
   constraint c1{
     q.size == NUM_CONSTRAINED_PKTS; // random indices = total constrained pkts generated
     foreach(q[i]){q[i]>=0; q[i]<NUM_TOTAL_PKTS;} // indices from 0-total_pkts
       unique {q}; // unique indices
   };
  task pack();
    p1=new;
    p1.num=0;
    this.randomize(); // randomize indices in q
    for(int i=0;i<NUM_TOTAL_PKTS;i++) begin
      if(i inside {q}) begin // check if index matches
        p1.randomize with {(p1.length==6);} ;
        p1.num++; // debug purpose
      end
      else
        p1.randomize ;
      $display("packet is %p",p1);
    end
    if(p1.num != NUM_CONSTRAINED_PKTS) $error("Error: p1.num=%0d",p1.num); // 10 pkts with constrained value
    else $display("Pass!!");
  endtask
endclass

Another method is to use dist operator on length variable with some glue logic to generate a weighted distribution in the output.


Q: JNI - Async task crashing I'm trying to do the following :

*

*Run Java app on Android

*Call native C++ code from that Java app

*Create and run a native thread from that natice code

*return immediatly while the thread keeps running

*Call a java method from native code once the thread is finished
Here is my code :
#include <jni.h>
#include <pthread.h>
#include <unistd.h> /* sleep() */
#include <stdio.h>

#ifdef __cplusplus
extern "C"
{
#endif

JNIEXPORT jstring JNICALL Java_xxx_asynctasktest_MainActivity_runAsyncTask( JNIEnv * env, jobject that, jstring oDummyStr );

#ifdef __cplusplus
}
#endif

JavaVM *  g_jvm;
jobject   g_obj;
jmethodID g_mid;

void * threadProc( void * pArg )
{
    JNIEnv * env = 0;
    int res = g_jvm->AttachCurrentThread( & env, NULL );

    sleep( 3 );

    jobject oStr = (jobject)pArg;
    env->CallObjectMethod( g_obj, g_mid, oStr );

    env->DeleteGlobalRef( oStr );
    env->DeleteGlobalRef( g_obj );

    g_jvm->DetachCurrentThread();

    return 0;
}

JNIEXPORT jstring JNICALL Java_xxx_asynctasktest_MainActivity_runAsyncTask( JNIEnv * env, jobject that, jstring oDummyStr )
{
    env->GetJavaVM( & g_jvm );
    g_obj = env->NewGlobalRef( that );
    g_mid = env->GetMethodID( env->GetObjectClass( that ), "onTaskFinished", "(Ljava/lang/String;)Ljava/lang/String;" );

    if( g_mid == NULL )
    {
        fprintf( stderr, "No such method" );
    }
    else
    {
        pthread_t thread = 0;
        pthread_create( & thread, NULL, threadProc, (void *)env->NewGlobalRef( oDummyStr ) );
    }

    return env->NewStringUTF( "lolol" );
}

My problem is that when i call env->CallObjectMethod( g_obj, g_mid, oStr );  eclipse tries to open Handler.class in the class file editor and says not found and the thread doesn't call the Java method.
What am I doing wrong ? Thank you.
EDIT : Forgot to mention that my Java callback creates a dialog as follows :
    AlertDialog.Builder dlgAlert  = new AlertDialog.Builder( this );
    dlgAlert.setMessage( msgBoxText );
    dlgAlert.setTitle( "" );
    dlgAlert.setPositiveButton( "OK", null );
    dlgAlert.setCancelable( true );
    dlgAlert.create().show();

And i'm having a runtime exception somewhere in "Handler" at line 121, source file not available.
EDIT : I'm actually reaching the Java callback, but it crashes when i start creating my dialog.


Q: Error "Cannot read contents from file.." when changing themes from admin panel Error:

Cannot read contents from file "C:/wamp64/www/magento2/" Warning!file_get_contents(C:/wamp64/www/magento2/): failed to open stream: No such file or directory

A: I had to change the theme in Website scope not Global.
Source: https://github.com/magento/magento2/issues/5666#issuecomment-233236951

A: Try to clean & flush cache, remove generated files, and regenerate static content:
$ php bin/magento cache:clean
$ php bin/magento cache:flush
$ rm -rf var/cache/* var/generation/* var/page_cache/* var/view_preprocessed/*
$ php bin/magento setup:static-content:deploy

Report back if it does not fix the error.

A: I have found a workaround for this issue. Please copy the folder
\vendor\magento\module-email\view\frontend\email

to
\vendor\magento\module-email\view\adminhtml\email\.


Q: Redisson client injects weird characters at the beginning of strings I'm using Redisson client to publish String messages on a topic, but for some reasons, the published messages always contain some weird characters at the beginning:
eg: when I publish the string "{"event":"notification"}"
at the redis level I end up with this:
"\x04>\x18{"event":"notification"}"
1) "pmessage"
2) "*"
3) "active_project_users:1"
4) "\x04>\x18{\"event\":\"notification\"}"

Any idea how I can make those weird chars go away?
My java code looks like this:
 private void publish(String channel, String message) {
        RTopic topic = redissonClient.getTopic(channel);
        topic.publish("{\"event\":\"notification\"}");
    }

I'm using redis:3.2 &  radisson-spring-boot-starter 3.16.1
Thanks

A: It seems I have to set the encoding for this to work properly:
RTopic topic = redissonClient.getTopic(channel, StringCodec.INSTANCE);


Q: WPF - error: [xxx] "does not contain a definition for [zzz] and no extension method [zzz] could be found I get an error while compiling:
'SimulatorUi.MainWindow' does not contain a definition for 'UserCtrlSimulator' and no extension method 'UserCtrlSimulator' accepting a first argument of type 'SimulatorUi.MainWindow' could be found (are you missing a using directive or an assembly reference?)
I got this error while compiling a user control and its owning window in the same project.
Why ?

A: The problem is the naming of the userControl in its owning Window. I named as:
Name="UserCtrlSimulator"

instead of:
x:Name="UserCtrlSimulator"

You can find the bug and a more useful error message by removing the reference of that badly named object (remove any reference to the object named without the "x:").
I can't tell the exact reason why it is like this ??? But my solution works fine.
Hope it can help anybody because I lost a lots of time with this weird bug.


Q: Google Sheet - limit certain users from organization from editing/viewing? I have the following issue.
I have a Google Sheet that is shared with everyone within my organization(300 people) and they have to have edit rights.
But, certain users from that organization should not be able to edit or even access the file, even tho it's okay if they can just view it.
I'm currently battling this by using a script that checks the users mail(Session.getEffectiveUser().getEmail()) and if they match the address in the array that contains all the addresses it fires an alert modal telling the user they are not eligible.
However, this works but if the users simply closes the alert he/she can continue editing the sheet. Which is not desirable. :)
I've searched but i failed to find a working solution or at least the idea to prevent those few users from the organization to edit this Sheet.
Appreciate any input, thanks!


Q: core Plot:Decrease distance between bar in bar graph ios i am plotting 2 data set on bar graph and i want them to be like histogram ,so can anyone guide me to the solution asap.
i have 2 datasets(google and Apple)in 1 datasets.I am not getting any spaces between bars of 1 dataset but i am getting too much spacing between 2 datasets.
here is my code,
    -(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
    return [[[CPDStockPriceStore sharedInstance] datesInWeek] count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    if ((fieldEnum == CPTBarPlotFieldBarTip) && (index < [[[CPDStockPriceStore sharedInstance] datesInWeek] count]))
    {
        if ([plot.identifier isEqual:CPDTickerSymbolAAPL])
        {
            NSLog(@"apple index:%@",[[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolAAPL] objectAtIndex:index]);
           return [[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolAAPL] objectAtIndex:index];
        }
        else if ([plot.identifier isEqual:CPDTickerSymbolGOOG])
        {
            NSLog(@"google index:%@",[[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolGOOG] objectAtIndex:index]);
            return [[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolGOOG] objectAtIndex:index];
        }
    }
    return [NSDecimalNumber numberWithUnsignedInteger:index];

-(void)viewDidLoad
{
    [super viewDidLoad];
    [self initPlot];
}

#pragma mark - Chart behavior
-(void)initPlot
{
    self.hostView.allowPinchScaling = YES;
    [self configureGraph];
    [self configurePlots];
    [self configureAxes];
    graphData=[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolAAPL];
    NSLog(@"google:%@",graphData);

}

-(void)configureGraph {
    // 1 - Create the graph
    CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];

    graph.plotAreaFrame.masksToBorder = NO;
    self.hostView.hostedGraph = graph;
    // 2 - Configure the graph
    [graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];
    graph.paddingBottom = 30.0f;
    graph.paddingLeft  = 30.0f;
    graph.paddingTop    = -1.0f;
    graph.paddingRight  = -5.0f;
    CGFloat xMin = 0.0f;
    CGFloat xMax = [[[CPDStockPriceStore sharedInstance] datesInWeek] count];
    CGFloat yMin = 0.0f;
    CGFloat yMax = 800.0f;  // should determine dynamically based on max price
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xMin) length:CPTDecimalFromFloat(xMax)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(yMin) length:CPTDecimalFromFloat(yMax)];

}

-(void)configurePlots
{
    // 1 - Set up the three plots
    self.aaplPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor colorWithComponentRed:105.0f/255.0f green:252.0f/255.0f blue:144.0f/255.0f alpha:1.0] horizontalBars:NO];
    self.aaplPlot.identifier = CPDTickerSymbolAAPL;

    self.googPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor colorWithComponentRed:103.0f/255.0f green:103.0f/255.0f blue:103.0f/255.0f alpha:1.0] horizontalBars:NO];
    self.googPlot.identifier = CPDTickerSymbolGOOG;

    // 2 - Set up line style
    CPTMutableLineStyle *barLineStyle = [[CPTMutableLineStyle alloc] init];
    barLineStyle.lineColor = [CPTColor lightGrayColor];
    barLineStyle.lineWidth = 0.5;

    // 3 - Add plots to graph
    CPTGraph *graph = self.hostView.hostedGraph;
    CGFloat barX = CPDBarInitialX;
    NSArray *plots =[NSArray arrayWithObjects:self.aaplPlot, self.googPlot, nil];
    for (CPTBarPlot *plot in plots)
    {
        plot.dataSource = self;
        plot.delegate = self;
        plot.barWidth = CPTDecimalFromDouble(CPDBarWidth);
        plot.barOffset = CPTDecimalFromDouble(barX);
        plot.lineStyle = barLineStyle;
        [graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];
        barX += CPDBarWidth;
    }

}

-(void)configureAxes
{
    // 1 - Configure styles
    CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
    axisTitleStyle.color = [CPTColor whiteColor];
    axisTitleStyle.fontName = @"Helvetica-Bold";
    axisTitleStyle.fontSize = 12.0f;
    CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
    axisLineStyle.lineWidth = 2.0f;
    axisLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:1];
    // 2 - Get the graph's axis set
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;
    // 3 - Configure the x-axis
    axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
    axisSet.xAxis.title = @"Days of Week (Mon - Fri)";
    axisSet.xAxis.titleTextStyle = axisTitleStyle;
    axisSet.xAxis.titleOffset = 10.0f;
    axisSet.xAxis.axisLineStyle = axisLineStyle;
    // 4 - Configure the y-axis
    axisSet.yAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
    axisSet.yAxis.title = @"Price";
    axisSet.yAxis.titleTextStyle = axisTitleStyle;
    axisSet.yAxis.titleOffset = 5.0f;
    axisSet.yAxis.axisLineStyle = axisLineStyle;

}

-(void)hideAnnotation:(CPTGraph *)graph
{
    if ((graph.plotAreaFrame.plotArea) && (self.priceAnnotation)) {
        [graph.plotAreaFrame.plotArea removeAnnotation:self.priceAnnotation];
        self.priceAnnotation = nil;
    }

}

A: With CPDBarWidth = 0.15, two bars take up only 30% of the space between successive bar locations. Increase the barWidth to reduce the space between neighboring bars.


Q: NameError: name 'redis' is not defined - PySpark - Redis I am using the addPyFile method in pyspark to load the redis.zip file.
I am able to load the file using
sc.addPyFile("/home/path/to/redis.zip")

But while running the code using ./pyspark, it is showing the error:

NameError: name 'redis' is not defined

The zip(redis.zip) contains .py files(client.py, connection.py,exceptions.py, lock.py,utils.py and others).
Python version is - 3.5 and spark is 2.7

A: If you pack py files into zip and add it using sc.addPyFile you should import modules using import client, import connector, etc.


Q: Lifestyle of NLog wrapper class I have five different logger and a wrapper class for them :
internal class CommonNLogResolver : ICommonLogger
{
    private readonly NLog.Logger commonLog;
    private readonly NLog.Logger errorLog;
    private readonly NLog.Logger dataBaseLog;
    private readonly NLog.Logger logExceptionLogger;
    private readonly NLog.Logger clientLogger;

    public CommonNLoggerResolver()
    {
        commonLog = NLog.LogManager.GetLogger(Constants.CommonLog);
        errorLog = NLog.LogManager.GetLogger(Constants.ErrorLog);
        dataBaseLog = NLog.LogManager.GetLogger(Constants.DBLog);
        logExceptionLogger = NLog.LogManager.GetLogger(Constants.LogExceptionLog);
        clientLogger = NLog.LogManager.GetLogger(Constants.ReportLog);
    }
}

I look at the LogFactory.cs in NLog and since it has a cache for logger I don't know what lifestyle is appropriate for my wrapper class.
so my question is should I register this class singleton , transient or scope?
also I'm using SimpleInjector for Dependency Injection.

A: NLog is thread-safe, so you can safely reuse your logger. You can make it Singleton.


Q: Least involved proof for continuos functions $\Rightarrow$ uniform continuous functions on $[a,b]$ I have been looking at this proof in my textbook and seem to always get lost in its logic, its roughly 3 pages long. The proof is:

If f is continuous on a closed interval [a,b], then f is uniformly continuous on [a,b].

Do any of you know of a nice, clean and quick proof for this? Asking my professor has only resulted in more confusion, and google helps little to none.
I greatly appreciate your help in advance!

A: Suppose for contradiction that $f$ is continuous but not uniformly continuous on $[a,b]$. Then there exists $\varepsilon > 0$ such that for every $n \in \mathbb{N}$ there exist $x_n, y_n \in [a,b]$ with $|x_n - y_n| < \frac{1}{n}$ and $|f(x_n) - f(y_n)| \ge \varepsilon$. By the Bolzano-Weierstrass theorem, the sequence $(x_n)$ has a convergent subsequence $(x_{n_k})$; say $x_{n_k} \to x \in [a,b]$. Now you have
$$
|y_{n_k} - x| \le |y_{n_k} - x_{n_k}| + |x_{n_k} - x| \le \frac{1}{n_k} + |x_{n_k} - x| \to 0
$$
and so $y_{n_k} \to x$ as well.
Since $f$ is continuous at $x$ and since $x_{n_k}, y_{n_k} \to x$, we have $f(x_{n_k}) \to f(x)$ and $f(y_{n_k}) \to f(x)$. In particular, there exists $k$ such that $|f({x_{n_k}}) - f(x)| < \varepsilon/2$ and $|f(y_{n_k}) - f(x)| < \varepsilon/2$. So the triangle inequality forces $|f(x_{n_k}) - f(y_{n_k})| < \varepsilon$, which contradicts the choice of the sequences $x_n$ and $y_n$.


Q: Eclipse added jar to referenced libraries but still getting ClassNotFoundException Hi I'm following this tutorial using eclipse. I've included the derby.jar and derbyclient.jar files and I can clearly see them appearing under referenced libraries. Oddly, I'm still geting java.lang.ClassNotFoundException: org.apache.derby.jdbc.ClientDriver even though the jar files are clearly there. I tried looking online but nothing were useful.
My steps of adding jar to referenced libraries: Right click project > properties > Java build path > Modulepath > Add External JARs. I've also tried adding it to Classpath instead of Modulepath and importing the package but either approaches doesn't seem to work at all.


Q: ESLint throwing unpredicted errors with Hardhat I recently began a project which uses hardhat. I ran npx hardhat ., and went with the advanced TS project.
Everything works fine, from the types to the solidity compiling, but ESLint always complains...
This is the kind of error I keep seeing:

As you can see the types are there, but ESLint continues to throw errors. This luckily doesn't stop the app to run.
Here is my config file:
module.exports = {
  env: {
    browser: false,
    es2021: true,
    mocha: true,
    node: true
  },
  plugins: ['@typescript-eslint'],
  extends: ['standard', 'plugin:node/recommended'],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 12
  },
  rules: {
    'node/no-unsupported-features/es-syntax': [
      'error',
      { ignores: ['modules'] }
    ]
  }
}

A: I've spent a lot of time on this issue, and the best method for me was to remove everything.
1 - Create a .ptettierrc.json file the root of your project.
2 - Run yarn remove eslint-plugin-promise eslint-plugin-node eslint-plugin-import eslint-config-standard eslint-config-prettier
3 - Change your ESLint config to the one below:
module.exports = {
  env: {
    browser: false,
    es2021: true,
    mocha: true,
    node: true
  },
  plugins: ['@typescript-eslint'],
  extends: ['plugin:prettier/recommended'],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 12
  },
  rules: {
    'node/no-unsupported-features/es-syntax': [
      'error',
      { ignores: ['modules'] }
    ]
  }
}

Keep in mind this is for a fresh config, if you've already changed your config, just remove any mentions of the package we removed on step 2.


Q: What Datatype is created? What data type does "two_days_in_a_row" create in Python? Does it create a list or a tuple, or any other datatype
In my Advanced Data Science with Python on Coursera Course 1, Week 4, Distributions lecture, prof said that two_days_in_a_row = 0 will create a list. I am still figuring why will be the case, why a list will be created. Help me know the answer. Thanks in advance!!!
two_days_in_a_row = 0
#creates a list

A: You have assigned a integer value to that variable.
Using type() will tell you what data type you have.
I.E: type(two_days_in_a_row) --> returns int

A: Don't confuse, Check below data types in python
two_days_in_a_row = 0
type(two_days_in_a_row): int

two_days_in_a_row = []
type(two_days_in_a_row): list

two_days_in_a_row = None
type(two_days_in_a_row): NoneType

two_days_in_a_row = ""
type(two_days_in_a_row): str

two_days_in_a_row = {}
type(two_days_in_a_row): dict

two_days_in_a_row = ()
type(two_days_in_a_row): tuple

two_days_in_a_row = 0.0
type(two_days_in_a_row): float

two_days_in_a_row = 2+3j
type(two_days_in_a_row): complex

two_days_in_a_row = True
type(two_days_in_a_row): bool


Q: Combine forEach callback parameter with function parameter I am trying to combine a forEach callback parameter (HTMLAnchorElement/HTMLTableCellElement objects) with a function parameter (string).
What I am doing is getting the href of an a tag in one function call, and then textContent of a td tag in another function call, using the same function.
Here is my code:
// example usage of function
await scraper.scraper(args, 'a[href]', 'href') // get href

await scraper.scraper(args, 'table tr td', 'textContent') // get textContent

// scraper function
const scraper = async (urls, regex, property) => {
  const promises = []
  const links = []

  urls.forEach(async url => {
    promises.push(fetchUrls(url))
  })

  const promise = await Promise.all(promises)
  promise.forEach(html => {
    const arr = Array.from(new JSDOM(html).window.document.querySelectorAll(regex))
    arr.forEach(tag => {
      links.push(tag.href) // how about textContent?
    })
  })

  return links
}

Is there a way of some how combining the callback parameter tag from the forEach with the function parameter property?
The code below works. But what if I want to do further function calls to other properties? I don't want to add an if statement every time I make another function call, that kind of defeats the purpose of my function to be reusable.
property === 'textContent' ? links.push(tag.textContent) : links.push(tag.href)
Any attempt in trying to combine the two seems to go wrong. Is it not possible?

A: Use the property value you pass in as computed key of your el object (tag in your code), in order to pass the property value for the element inside the forEach dynamically, depending on the property you passed in
arr.forEach(el => {
  links.push(el[property]);
})


Q: Deleting Cloudwatch logs using boto3 I am trying to delete Cloudwatch logs irrespective of the Log group.
Is there any method available with boto3 using which I can search for a pattern(keyword) in the Log group name?

A: You'll need to call describe_log_groups() and do the filtering within your code.
The only filter available is the ability to specify a logGroupNamePrefix.


Q: I want to assign 1 day after checkin date for check out date in bootstrap datepicker I have the HTML as follows

  <input type="hidden" data-date-format="MM/DD/YYYY" name="dateArrival"   id="dateArrival">

  <input type="hidden" data-date-format="MM/DD/YYYY" name="dateDeparture" id="dateDeparture">

and following is the JS file content for the above
jQuery("#booking-tab-contents .input-daterange").datepicker({
    format: "yyyy-mm-dd",
    autoclose: true,
    startDate: new Date(),
    show: true,
    inputs: jQuery('.booking-date-fields-container')
 });

$('#dp3').datepicker().on('click', function (ev) {
    $('#dateArrival').val( $('#dp3').datepicker('getFormattedDate'));
});

$('#dp4').datepicker().on('click', function (ev) {
    $('#dateDeparture').val( $('#dp4').datepicker('getFormattedDate'));
});

I want to make my date-picker in such a way that, when I select arrival date or check in date, the checkout date must be a day after the check-in date


Q: Java util Timer - Thread addition Timer timer = new Timer();

// scheduling the task at interval
timer.schedule(tasknew,100, 100);

If this is added as part of a web-application at the startup, how is the task getting kicked off at the scheduled time? Is a new daemon thread process being created, solely for triggering this task?
I just want to understand if we are creating any additional thread that is responsible for this task threads?

A:
I just wanted to understand if we are creating any additional threads that is responsible for this task threads?

Yes - from the documentation:

Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.


Q: How to disallow multiple parallel user sessions per login in ZF2? I'm currently facing the situation, that the ZendFramework2 ZFCuser-Module does not have any options to prevent a user from logging in from two devices at the same time.
We recently had a case, that two people were "account-sharing" and accidentally deleted each others data. Since I did not build the application to account for this kind of resource conflicts, I need to prevent this behaviour now.
Is there any module or easy possibility out there to prevent account-sharing in Zend Framework 2 with ZFCUser?
The docs and SO and all sorts of ZF2 blogs somehow appear to never have come across this type of problem...
Thanks in advance!

A: I was able to achieve the functionality of limiting the number of sessions for the same user.
However, my solution (code below) doesn't provide any data-protected layer in order to restrict CRUD operation performed from another session.
I think you can achieve this if you restrict operation based on user_id and session_id
DB

id
user_id
client_id

00m5nqcvpk9bhqv7rbllq5hsi4
198
14

34ssnqcvpk9xxqv7rbll4354fdf
123
42

id will be session_id (PHP SID)

Method
/**
     *
     * @param int $userId
     * @param int $clientId
     * @return type
     */
    public function validateActiveSession($userId, $clientId) {
        if (empty($userId)) {
            $userId = $this->getResourceManager()->getIdentity()->getId();
        }

        if (empty($clientId)) {
            $clientId = $this->getResourceManager()->getIdentity()->getClientId();
        }

        $sessionManager = $this->getServiceLocator()->get('Zend\Session\SessionManager');
        $id = $sessionManager->getId();

        $userModel = $this->getResourceManager()->getuserModel();

        $sIdUserExist = $userModel->getUserActiveSession('', '', $id);
        if (empty($sIdUserExist)) {
            $userModel->addUserSessionBySidAndUserClientId($id, $userId, $clientId);
        }
    }

Repository
public function addUserSessionBySidAndUserClientId($sessionId, $userId, $clientId)
    {
        $em = $this->_em->getConnection();
        $sql = "INSERT INTO `user_session`(`id`, `user_id`, `client_id`) VALUES (:id,:user_id,:client_id)";
        $params = array('id' => $sessionId, 'user_id' => $userId, 'client_id' => $clientId);
        $stmt = $em->prepare($sql);
        return $stmt->execute($params);
    }

public function getActiveUserSession($userId, $clientId, $sessionId)
    {
        $rsm = new ResultSetMapping();
        $rsm->addScalarResult('id', 'id');
        $rsm->addScalarResult('user_id', 'user_id');

        $userIdClause = $clientIdClause = $andClause = $sessionIdClause = '';

        if (!empty($userId)) {
            $userIdClause = 'user_id = :user_id';
        }

        if (!empty($clientId)) {
            $clientIdClause = ' and client_id = :client_id';
        }

        if (!empty($userId) && !empty($sessionId)) {
            $andClause = ' and ';
        }

        if (!empty($sessionId)) {
            $sessionIdClause = 'id = :id';
        }

        $query = $this->_em->createNativeQuery('SELECT id,user_id FROM user_session WHERE ' . $userIdClause . $clientIdClause . $andClause . $sessionIdClause, $rsm);

        if (!empty($userId)) {
            $query->setParameter('user_id', $userId);
        }

        if (!empty($clientId)) {
            $query->setParameter('client_id', $clientId);
        }
        if (!empty($sessionId)) {
            $query->setParameter('id', $sessionId);
        }

        return $query->getResult();
    }

once user logged-in check for active sessions
$sameActiveUser = count($userModel->getActiveUserSession($userId, $clientId, ''));

if ($sameActiveUser == 2) { //already 2 active session than restrict 3rd
   return "session already present";
} else {
   $this->validateActiveSession($userId, $clientId);
}


Q: How do I remove access to selected users from Microsoft Teams? Removing Teams licenses doesn't work In Office 365/Azure we have a set of special high privileged accounts used only for management purposes. Then normal accounts used for "office" work.
The privileged accounts are set as "unlicensed" - all app access removed. Yet, when I access Teams with any of the users, I can use it normally. Also, whenever someone performs a user search/autocomplete in Teams the privileged accounts show up. This is an issue because, for example, my name shows up 3 times causing confusion and mistakes.
What do I need to do to totally remove the users from Teams?


Q: Using floats for counters - Any problems? The code I'm looking at uses a golang float64 as a counter, does this pose a problem with loss of accuracy at some point? Specifically, are all integers represented in the range covered by float64? If not, where do I start running into problems? When do I run out of contiguous integers?
In case you're wondering, the reason for using a float64 as a counter is because it's part of a []float64 that holds many metrics that are not integers.

A: The golang specification says, "float64 is the set of all IEEE-754 64-bit floating-point numbers." which is commonly known as double precision numbers,
http://en.wikipedia.org/wiki/Double-precision_floating-point_format
You can read all of its glory details if interested, but to answer your question, quote,
"...next range, from 253 to 254, everything is multiplied by 2..."
So if you want to use it as counters, i.e. positive integers, you won't have problem until 253=9,007,199,254,740,992.

A: Yes, float64 has 52 bits to store your counter. You should be accurate until 253.
(Side note: the entire JavaScript language uses only Floating Point.)


Q: Encontrar y tildar checkbox de un nodo en un treeview Tengo un treeview con toda la estructura de directorios y archivos de la PC donde se está ejecutando la aplicación. Al iniciar, obtengo una lista de strings con varias rutas, para las cuales necesito encontrar el nodo del treeview correspondiente a cada una de ellas y marcar su checkbox.
El problema es que al iniciar la aplicación, sólo aparecen en el treeview las unidades (discos fijos y extraibles) y a medida que voy expandiendo cada nodo se va completando con sus subdirectorios (esto lo plantee así para no recargar el inicio de la aplicación). Entonces lo que no encuentro forma de hacer es, primero ir expandiendo los nodos hasta llegar al último nivel de cada ruta (puede ser archivo o directorio), y segundo, marcar su checkbox.
El código que tengo es el siguiente:
Al iniciar la aplicación:
foreach (DriveInfo unidad in DriveInfo.GetDrives())
{
    if (unidad.DriveType != DriveType.Fixed && unidad.DriveType !=
        DriveType.Removable)
    {
        continue;
    }

    TreeNode raiz = new TreeNode(unidad.Name);
    raiz.ToolTipText = "Unidad";
    raiz.Tag = unidad.Name;
    raiz.ImageIndex = 0;

    raiz.Nodes.Add(new TreeNode());
    tvArbol.Nodes.Add(raiz);
}

Al expandir un nodo:
DirectoryInfo directorioPadre = new DirectoryInfo(path);
DirectoryInfo[] subDirectorios = directorioPadre.GetDirectories();

foreach (DirectoryInfo subDirectorio in subDirectorios)
{
    TreeNode directorioHijo = new TreeNode(subDirectorio.Name);
    directorioHijo.Tag = subDirectorio.FullName;
    directorioHijo.ImageIndex = 1;

    directorioHijo.Nodes.Add(new TreeNode());
    directorioHijo.Checked = nodo.Checked;
    nodo.Nodes.Add(directorioHijo);
}

List<FileInfo> archivos = new List<FileInfo>();
archivos.AddRange(directorioPadre.GetFiles());

foreach (FileInfo archivo in archivos)
{
    TreeNode archivoHijo = new TreeNode(archivo.Name);
    archivoHijo.ImageIndex = 2;

    archivoHijo.Tag = archivo;
    archivoHijo.Checked = nodo.Checked;
    nodo.Nodes.Add(archivoHijo);
}

A: Dices que tienes una List<string> con las rutas de varios archivos. Entonces entiendo que tienes que ir marcando como Checked las rutas que coincidan a medida que vas expandiendolas.
Aqui tienes un método que comprueba si hay que añadir el Checked a un nodo. Seguro que puede optimizarse y yo probablemente lo convertiría en un método de extensión, pero para que te hagas una idea (paths es la lista de las rutas, cambialo por la tuya).Utiliza el Level del nodo para saber hasta que parte del path hay que comparar:
private bool isChecked(TreeNode node)
{
    bool check= false;
    foreach (string pathcomparar in paths)
    {
        string[] splittedPath = pathcomparar.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
        string[] splittedTreePath = node.FullPath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
        if (String.Join("\\", splittedPath.Take(node.Level + 1)) == String.Join("\\", splittedTreePath.Take(node.Level + 1)))
        {
            check = true;
        }
    }
    return check;
}

Con este método, no tienes mas que modificar tu código de la siguiente manera.
Al iniciar la aplicación:
foreach (DriveInfo unidad in DriveInfo.GetDrives())
{
    if (unidad.DriveType != DriveType.Fixed && unidad.DriveType !=
        DriveType.Removable)
    {
        continue;
    }

    TreeNode raiz = new TreeNode(unidad.Name);
    raiz.ToolTipText = "Unidad";
    raiz.Tag = unidad.Name;
    raiz.ImageIndex = 0;

    raiz.Nodes.Add(new TreeNode());
    tvArbol.Nodes.Add(raiz);
    raiz.Checked = isChecked(raiz);
}

Al expandir nodos (entiendo que usas el evento AfterExpand):
DirectoryInfo directorioPadre = new DirectoryInfo(path);
DirectoryInfo[] subDirectorios = directorioPadre.GetDirectories();

foreach (DirectoryInfo subDirectorio in subDirectorios)
{
    TreeNode directorioHijo = new TreeNode(subDirectorio.Name);
    directorioHijo.Tag = subDirectorio.FullName;
    directorioHijo.ImageIndex = 1;

    directorioHijo.Nodes.Add(new TreeNode());
    //directorioHijo.Checked = nodo.Checked;
    nodo.Nodes.Add(directorioHijo);

    directorioHijo.Checked = isChecked(directorioHijo);
}

List<FileInfo> archivos = new List<FileInfo>();
archivos.AddRange(directorioPadre.GetFiles());

foreach (FileInfo archivo in archivos)
{
    TreeNode archivoHijo = new TreeNode(archivo.Name);
    archivoHijo.ImageIndex = 2;

    archivoHijo.Tag = archivo;
    nodo.Nodes.Add(archivoHijo);

    archivoHijo.Checked = isChecked(archivoHijo);
}

Si tienes alguna duda o problema, comentamelo.


Q: Removing From ElasticSearch by type last 7 day I have different logs in elasticsearch 2.2 separate by 'type'. How can delete all data, only one of type, older one week? thanks
Example of logs:

{
  "_index": "logstash-2016.02.23",
  "_type": "dns_ns",
  "_id": "AVMOj--RqgDl5Axva2Nt",
  "_score": 1,
  "_source": {
    "@version": "1",
    "@timestamp": "2016-02-23T14:37:07.029Z",
    "type": "dns_ns",
    "host": "11.11.11.11",
    "clientip": "22.22.22.22",
    "queryname": "api.bing.com",
    "zonetype": "Public_zones",
    "querytype": "A",
    "querytype2": "+ED",
    "dnsip": "33.33.33.33"
  },
  "fields": {
    "@timestamp": [
      1456238227029
    ]
  }
}

A: See here or here on how to delete by query. In Elasticsearch 2.*, you might find the Delete by Query plugin useful.

A: Deleting "types" is no longer directly supported in ES 2.x  A better plan is to have rolling indexes, that way deleting indexes older than 7 days becomes very easy.
Take the example of logstash, it creates an index for every day.  You can then create an alias for logstash so that it queries all indexes.  And then when it comes time to delete old data you can simply remove the entire index with:
DELETE logstash-2015-12-16


Q: How do I re-layout and re-paint a field when a Manager calls setPositionChild(Field)? My class extends Manager and calls setPositionChild(Field f) to change f's position. After calling setPositionChild() method, how do I apply the position(i.e. re-layout and re-paint) so I can see the changes?
I tried to call invalidate(), which did not work.

A: invalidate() just forces a repaint, it doesn't redo the whole layout, as you noticed.
You can force a relayout by going up to the parent Screen object, and calling invalidateLayout().  Forcing the layout will almost certainly call setPositionChild() on the field you are trying to move, so you will want to make sure the new field position is preserved by the manager layout code. This may mean you need to write a custom manager.


Q: Inno Setup Remove version number from "Setup has detected that ... is currently running" I've added the line AppMutex={#MyAppName} to my InnoSetup script, and #MyAppName does NOT include the version number. However, when my Setup.exe runs, it says "Your App v1.01 is already running" (or whatever) with the version number, which I don't want. Is there a way to have the message NOT show the version number?
Reason: Say I'm running v1.00 of my app, and I launch "MyApp_101_Setup.exe" (made with Inno Setup). The message shown is "Your App v1.01 is already running" which is NOT true, I'm trying to install v1.01 while v1.00 is running. This can cause confusion for my users.
Any tips? Thanks! :)

A: You are wrong.
The message is:
SetupAppRunningError=Setup has detected that %1 is currently running.%n%nPlease close all instances of it now, then click OK to continue, or Cancel to exit.

Where the %1 is replaced by value of the AppName directive:
ExpandedAppName := ExpandConst(SetupHeader.AppName);

...

{ Check if app is running }
while CheckForMutexes(ExpandedAppMutex) do
  if LoggedMsgBox(FmtSetupMessage1(msgSetupAppRunningError, ExpandedAppName),
     SetupMessages[msgSetupAppTitle], mbError, MB_OKCANCEL, True, IDCANCEL) <> IDOK then
    Abort;

So the version is included in the message, only if you have included the version in the AppName directive. What is wrong, the directive value may not include the version, as the documentation says:

Do not include the version number, as that is defined by the AppVersion and/or AppVerName directives.


Q: How do I use `Explain` with a `find_by_sql` query? User.find_by_sql("...my statement here...").explain
results in an error undefined method explain for array... which makes perfect sense to me...
I'm not using rails. I'm using sinatra although that should not matter since the commands come from the activerecord gem which I am using...
Any suggestions?

A: Error is pretty self-explanatory.
You can only run explain on ActiveRecord::Relation objects. But find_by_sql gives you an Array instead, on which explain cannot be called.
You have two ways to work around this:

*

*Convert your query with ActiveRecord methods (which return
Relation)

*Use explain inside your find_by_sql string.