text:
Q: Passing command line arguments to JUnit in Eclipse All,
I am currently using JUnit 4 for writing test cases. I am fairly new to JUnit and finding it difficult to test my main class which takes arguments. I have specified the arguments to my JUnit test class by:
1 > Right click JUnit test class
2 > Goto Run As -> Run Configurations
3 > Select the Arguments tab and specify a value (I have entered an invalid argument i.e. the main class expects the command line argument to be converted to an int and I am passing a String value that cannot be converted to int)
However, the main class that I am testing, if the command line argument cannot be converted to a int, than I throw IllegalArgumentException. However, the JUnit does not show the testMain() method as Error or Failure. I don't think my setup is right for the JUnit class. Can anyone please guide me where I am going wrong

A: To test your class main method simply write something like:
@Test(expected = IllegalArgumentException.class)
public void testMainWithBadCommandLine()
{
     YourClass.main(new String[] { "NaN" });
}

A: Change the main() method to something like this:
public static void main(String[] args)
{
  MyClass myclass = new MyClass(args);
  myclass.go();
}

Move the code that was in main() to the new method go().  Now, your test method can do this:
public void myClassTest()
{
  String[] args = new String[]{"one", "two"}; //for example
  MyClass classUnderTest = new MyClass(testArgs);
  classUnderTest.go();
}

A: Firstly the arguments should be in the program arguments section. Normally the launching point of the application that's the main method doesn't need to be tested if you design the app to be testable.

*

*Refactor the class

public static class ArgumentValidator
    {
        public static boolean nullOrEmpty(String [] args)
        {
             if(args == null || args.length == 0)
             {
                 throw new IllegalArgumentException(msg);
             }
             //other methods like numeric validations
        }
     }

*You can now easily test the nullOrEmpty method using junit like

@Test(expected = IllegalArgumentException.class)

    public void testBadArgs()
    {
         ArgumentValidator.nullOrEmpty(null);
    }

I think this is a better approach


text:
Q: Google Spreadsheet - To execute a custom function only in the expanded row group I have a form where my team fills in daily sales activity data.
I have to fetch the data of each member and display it another sheet.
Though I can do it with query, I have written a custom function that takes 3 arguments and search in the form responses and returns an array of data. Daily(name,week,day) is my function.
Every time the formula is called, the search happens on the entire form response data.
Now the issue is the formula is used 13*365(13 people ad 365 days) times in the sheet.
I am unable to stop the function from executing again and again. I have grouped the rows month wise, also created named ranges. either of the ways, can I execute the formula only in this expanded rows/named ranges using Apps script???? Attached the sheet

A: I wrote the code, like i would go from row 1 to max and check every row. If  it is not hidden, you can execute your code, else its skipped.
Its working for me. Depends on your code you have to adaped it.
function HiddenRowSkipper() {
  var devTest = SpreadsheetApp.getActive().getSheetByName("DevTest");

  var maxRow = devTest.getMaxRows();

  for(var i = 1; i < maxRow; i++){
    if(devTest.isRowHiddenByUser(i) == false){
      //Execute your code on the Row "i"
    }
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use Selenium to test for print window in Chrome I'm trying to verify that clicking a print button opens the print dialog. The button calls javaScript that calls window.print().
I get an exception, but the print view opens.  I am unable to select the print view. I can inspect the with the dev tools and it is showing HTML.

The HTTP request to the remote WebDriver server for URL
  .../session/888062777289e469e06bab59a6ea6c29/element/0.4957923940382898-7/click
  timed out after 60 seconds.

driver.FindElement(By.Id("print-preview")); does not find the window.
The dev tools say the address is chrome://print/, but it looks like an overlay.
Is there a way to interact with the print dialog? I'm only going to run the test on Chrome.
I'm also open to using MS Coded UI and am going to start looking into that.


text:
Q: $\lim\ \frac{1}{\sqrt{n}}\sum_{k=0}^n\sqrt{C_n^kp^k(1-p)^{n-k}}$ Let $p\in (0,1)$ and define the sequence :
$$a_n=\frac{1}{\sqrt{n}}\sum_{k=0}^n\sqrt{C_n^kp^k(1-p)^{n-k}}$$ where $C_n^k=\frac{n!}{k!(n-k)!}$.
How can I calculate $\lim a_n$ ? Any help would be appreciated !
Thank you in advance !

A: A full solution based on my comment, but cleaner:
Let $n$ be large enough, and let $X$ be a random variable with law $B(n,p)$.
We have $\sqrt{n}a_n=\sum_{k=0}^n{\sqrt{P(X=k)}}$.
By AM-QM and then variance estimate, $$\sum_{0\leq k\leq n,|k-np| \geq n^{3/4}}{\sqrt{P(X=k)}}\leq \sqrt{n}P(|X-np| \geq n^{3/4}) \leq \sqrt{n}np(1-p)n^{-3/2} \leq 1.$$
Thus, $a_n \leq n^{-1/2}+n^{-1/2}\sum_{np-n^{3/4} \leq k \leq np+n^{3/4}}{\sqrt{P(X=k)}}$.
By AM-QM, the sum in the RHS is at most $\sqrt{1+2n^{3/4}}\sqrt{P(|X-np| \leq n^{3/4})} \leq 2n^{3/8} \cdot 1$.
It follows $a_n \leq 3n^{-1/8}$ hence $a_n \rightarrow 0$.


text:
Q: Converting from The vector field corresponds to image coordinates. x,y,z grid into vector field specified per voxel I have a 501x501x83 single matrix which contains the vector field of each point. . This vector field is corresponds to  image coordinates. x,y,z grid for the vector field in image coordinates. I want to convert them back into vector field  specified per voxel, rather than using  physical coordinates. While the positive direction is along how voxel indices increase, the values in DVF are in the unit of voxels
How can I do it.
Yours sincerely


text:
Q: Xamarin Android Click Button in ListView And Get Item Position I want to make a click button on OnCreateView "Fragment"
the first class is HomeScreenAdapter : BaseAdapter
is a simple Adapter retrun a view

HomeScreenAdapter

public class HomeScreenAdapter : BaseAdapter<Quotes>
{
    List<Quotes> items;
    Activity context;
    public HomeScreenAdapter(Activity context, List<Quotes> items)
        : base()
    {
        this.context = context;
        this.items = items;
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override Quotes this[int position]
    {
        get { return items[position]; }
    }
    public override int Count
    {
        get { return items.Count; }
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var item = items[position];
        View view = convertView;
        if (view == null) // no view to re-use, create new
            view = context.LayoutInflater.Inflate(Resource.Layout.Quotes, null);
        view.FindViewById<TextView>(Resource.Id.Quotes).Text = item.s_Quotes;
        view.FindViewById<TextView>(Resource.Id.From).Text = item.s_From;
        view.FindViewById<TextView>(Resource.Id.Category).Text = item.Category;

        return view;
    }
}

Fragment

class CrimeFragments : Fragment
{
    ListView Lv;
    List<Quotes> tableItems = new List<Quotes>();
    static Quotes quotes;
    ClipboardManager Cbm;
    ClipData Cd;
    ImageView imageView;
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

        View rootView = inflater.Inflate(Resource.Layout.crimelayout, container, false);
        Lv = rootView.FindViewById<ListView>(Resource.Id.crimeListView);
        Lv.VerticalScrollBarEnabled = false;
        Lv.Adapter = new HomeScreenAdapter(this.Activity, tableItems);
        Lv.ItemClick += Lv_ItemClick;
        return rootView;
    }

    private void Lv_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
    {
        var t = tableItems[e.Position];
        string cpy = t.s_Quotes + " - " + t.s_From;
        Cbm = (ClipboardManager)Context.GetSystemService(Context.ClipboardService);
        Cd = ClipData.NewPlainText("text", cpy);
        Cbm.PrimaryClip = Cd;
        Toast.MakeText(this.Activity, "Text Copied", ToastLength.Short).Show();
    }
}

I Want to make this button click not Lv.ItemClick

I want make thies buttons independent from Listview
Any One Can Help Me Please ?

A: Hi Developers I found a solution this worked for me :

*

*If You've a Adapter class change the GetView Function to this :
    public override View GetView(int position, View convertView, ViewGroup parent)
{
    var item = items[position];
    View view = convertView;
    if (view == null)
    {
        // no view to re-use, create new
        view = context.LayoutInflater.Inflate(Resource.Layout.Quotes, null);
    }
    view.FindViewById<TextView>(Resource.Id.Quotes).Text = item.s_Quotes;
    view.FindViewById<TextView>(Resource.Id.From).Text = item.s_From;
    view.FindViewById<TextView>(Resource.Id.Category).Text = item.Category;
    Button btnCopy = view.FindViewById<Button>(Resource.Id.btnCopy);

    btnCopy.Click += delegate
    {
        Toast.MakeText(this.context, items[position].s_From, ToastLength.Short).Show();
    };
    return view;
}


text:
Q: java:  expected with ArrayList I have a class named Storage.  Storage contains an arraylist of special objects called Products.  Each product contains information such as name, price, etc.  My code is as follows:
class Storage{

 Product sprite = new Product("sprite",1.25,30);
 Product pepsi = new Product("pepsi",1.85,45);
 Product orange = new Product("orange",2.25,36);
 Product hershey = new Product("hershey",1.50,33);
 Product brownie = new Product("brownie",2.30,41);
 Product apple = new Product("apple",2.00,15);
 Product crackers = new Product("peanut",3.90,68);
 Product trailmix = new Product("trailmix",1.90,45);
 Product icecream = new Product("icecream",1.65,28);
 Product doughnut = new Product("doughnut",2.75,18);
 Product banana = new Product("banana",1.25,32);
 Product coffee = new Product("coffee",1.30,40);
 Product chips = new Product("chips",1.70,35);

 ArrayList<Product> arl = new ArrayList<Product>();

 //add initial elements to arraylist
 arl.add(sprite);
 arl.add(pepsi);
 arl.add(orange);
 arl.add(hershey);
 arl.add(brownie);
 arl.add(apple);
 arl.add(peanut);
 arl.add(trailmix);
 arl.add(icecream);
 arl.add(doughnut);
 arl.add(banana);
 arl.add(coffee);
 arl.add(chips);
}

Whenever I compile, I get an error message on lines 141-153 stating <identifier> expected.
I know it's an elementary problem, but I can't seem to figure this out.  Any help is much appreciated.

A: You can't call methods like that just in the class body. You have to put methods calls in other methods, or in a constructor.
You want this:
class Storage{

    Product sprite = new Product("sprite",1.25,30);
    Product pepsi = new Product("pepsi",1.85,45);
    Product orange = new Product("orange",2.25,36);
    Product hershey = new Product("hershey",1.50,33);
    Product brownie = new Product("brownie",2.30,41);
    Product apple = new Product("apple",2.00,15);
    Product crackers = new Product("peanut",3.90,68);
    Product trailmix = new Product("trailmix",1.90,45);
    Product icecream = new Product("icecream",1.65,28);
    Product doughnut = new Product("doughnut",2.75,18);
    Product banana = new Product("banana",1.25,32);
    Product coffee = new Product("coffee",1.30,40);
    Product chips = new Product("chips",1.70,35);

    ArrayList<Product> arl = new ArrayList<Product>();

    //constructor
    protected Storage(){
        //add initial elements to arraylist
        arl.add(sprite);
        arl.add(pepsi);
        arl.add(orange);
        arl.add(hershey);
        arl.add(brownie);
        arl.add(apple);
        arl.add(peanut);
        arl.add(trailmix);
        arl.add(icecream);
        arl.add(doughnut);
        arl.add(banana);
        arl.add(coffee);
        arl.add(chips);
    }
}

A: The problem is that your initialization code is out of place. You can:

*

*Put it in a constructor or other method

*Put it in instance initializer

*Put it as field initializer

The last option is the simplest and cleanest solution; it would look something like this:
List<Product> arl = new ArrayList<Product>(
  Arrays.asList(
    sprite, pepsi, orange, hershey, brownnie, apple, peanut,
    trailmix, icecream, doughnut, banana, coffee, chips
  )
);

Note also that I switched the type of arl to its interface List<Product>. You should try to work with interfaces rather than concrete implementations whenever possible.

A: Your class is missing some methods. Use a constructor or a main method (public static void main(String[] args){...}) to fill your ArrayList.


text:
Q: build.gradle.kts failed : Unresolved reference python,pip, jni,install I'm new to android development and working on a Mobile solution, where Python Script has to be executed from android, from the documentation came to know chaquopy plugin should be used to execute Python Script in Android.
The expectation of requirement is to bundle all the dependencies/jars/plugins and python code in Android Library(AAR), and this AAR should be encapsulated in a way without doing any changes to main app should work (since I'm not the owner of the main app, no changes will be allowed)
However, for testing AAR I have a received cloned version of Main App.
Below is the AAR build.gradle.kts file code.
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
    id("com.android.library")
    kotlin("android")
    id("gradle-pega-android-module" )
    id("com.chaquo.python") version "13.0.0"
}

group = "com.***.***"
version = "0.1-SNAPSHOT"

android {
    compileSdk = 33

    defaultConfig {
        minSdk = 23
        targetSdk = 33

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
        python {
                pip {
                install("six")
                install("pandas")

            }
        }
        ndk {
            abiFilters("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
        }

        sourceSets.main {
            jni.srcDirs = listOf()
            jniLibs.srcDir("src/main/libs")
        }
        sourceSets {
            named("main") {
                // let gradle pack the shared library into apk
                jniLibs.srcDirs = listOf("../distribution/gperf/lib","../distribution/conda-android-python/lib")
            }
        }
    }
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        jvmTarget = "11"
    }
}

dependencies {
    implementation("androidx.appcompat:appcompat:1.4.1")
    androidTestImplementation("androidx.test:runner:1.4.0")
    androidTestImplementation("androidx.test.espresso:espresso-core:3.5.0-alpha06")
    testImplementation("junit:junit:4.12")
    implementation("com.google.mlkit:image-labeling:17.0.7")
    implementation("com.google.android.gms:play-services-mlkit-text-recognition:18.0.2")
    implementation("com.google.android.gms:play-services-mlkit-image-labeling:16.0.8")
    implementation("com.chaquo.python:gradle:13.0.0")
}

While doing the build getting below errors.
Unresolved reference: python
Unresolved reference: pip
Unresolved reference: install
Unresolved reference: install
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline operator fun <T : Any, C : NamedDomainObjectContainer<TypeVariable(T)>> TypeVariable(C).invoke(configuration: Action<NamedDomainObjectContainerScope<TypeVariable(T)>>): TypeVariable(C) defined in org.gradle.kotlin.dsl
public operator fun <T> Closure<TypeVariable(T)>.invoke(): TypeVariable(T) defined in org.gradle.kotlin.dsl
public operator fun <T> Closure<TypeVariable(T)>.invoke(x: Any?): TypeVariable(T) defined in org.gradle.kotlin.dsl
public operator fun <T> Closure<TypeVariable(T)>.invoke(vararg xs: Any?): TypeVariable(T) defined in org.gradle.kotlin.dsl
public operator fun <V> Callable<TypeVariable(V)>.invoke(): TypeVariable(V) defined in org.gradle.kotlin.dsl
public operator fun <T, R> DeepRecursiveFunction<TypeVariable(T), TypeVariable(R)>.invoke(value: TypeVariable(T)): TypeVariable(R) defined in kotlin
public operator fun <T> Action<in TypeVariable(T)>.invoke(target: TypeVariable(T)): Unit defined in org.gradle.kotlin.dsl
public operator fun <T> NamedDomainObjectProvider<TypeVariable(T)>.invoke(action: TypeVariable(T).() -> Unit): Unit defined in org.gradle.kotlin.dsl
public operator fun ArtifactHandler.invoke(configuration: ArtifactHandlerScope.() -> Unit): Unit defined in org.gradle.kotlin.dsl
public operator fun DependencyConstraintHandler.invoke(configuration: DependencyConstraintHandlerScope.() -> Unit): Unit defined in org.gradle.kotlin.dsl
public inline operator fun <T> ExtraPropertiesExtension.invoke(initialValueProvider: () -> TypeVariable(T)): InitialValueExtraPropertyDelegateProvider<TypeVariable(T)> defined in org.gradle.kotlin.dsl
public operator fun <T> ExtraPropertiesExtension.invoke(initialValue: TypeVariable(T)): InitialValueExtraPropertyDelegateProvider<TypeVariable(T)> defined in org.gradle.kotlin.dsl
public operator fun <T> Spec<TypeVariable(T)>.invoke(arg: TypeVariable(T)): Boolean defined in org.gradle.kotlin.dsl
public inline operator fun TaskContainer.invoke(configuration: TaskContainerScope.() -> Unit): TaskContainer defined in org.gradle.kotlin.dsl
Expression 'main' cannot be invoked as a function. The function 'invoke()' is not found
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val NamedDomainObjectContainer<KotlinSourceSet>.main: NamedDomainObjectProvider<KotlinSourceSet> defined in org.gradle.kotlin.dsl
Unresolved reference: jni
Variable expected
Not enough information to infer type variable T
Unresolved reference: jniLibs
Function invocation 'srcDirs(...)' expected
Variable expected
Calls to BasePlugin.getExtension() are deprecated and will be removed in AGP 8.0
Script compilation errors:

Any inputs or alternate approaches without doing any changes to main app will be great helpful.


text:
Q: Could somebody rewrite this sentence in a simple language? "A knight had only to swop his armorial surcoat and shield for those of another to be safely taken for that person." (Hanley, Catherine., War and Combat (1150-1270): The Evidence from Old French Literature, p33)

A:
A knight only had to put on someone else's cloths to be identified as that person.

I wonder where the exact problems are in your sentence. Maybe you can elaborate a bit more on the specific problems you face - or why you want it "simplified"?
Safely simply indicates that the knight does not risk to be found out.
We are talking about a time when people did not carry (photo) identification, and the only way - short from personally knowing the person - to identify someone was to ask their name.
For a knight, or for nobility, once heraldry became common, you could identify them by their (coat of) arms. This could be displayed on a seal, on a banner, or on their coat - the armorial surcoat. This coat or cape displayed the coat of arms or much simpler, the personal heraldic colours or shield of the wearer - or that of their lord.
So if a knight would put on a different knight's coat, he would become that other knight for all intents and purposes.
As an example, the Knights Templar wore a long white coat with a red cross on it. This was not just because it looked nice, it identified them as a Knight Templar. All someone had to do to be identified as one of them was simply take that coat and put it on. Of course, the actual owner of the said coat would very likely object to that.


text:
Q: Laravel 5.5 wildcard sudomain not working on live server I'm making a laravel app and part of it is users been able to create a page which I want to have as subdomain. On my localhost this works fine. But immediately I uploaded to a live server, I got this
This site can't be reached
sub.domain.com's server IP address could not be found.
I've set up a wildcard subdomain and yet nothing seems to be working...


text:
Q: Is there a Bitcoin calculator /price tracker widget to add to Gnome? Is there a way to add something like an online Bitcoin to USD calculator to the Gnome desktop? I don't think the Software store has anything like that.

A: There is a gnome-shell-extension available for Gnome Shell that does this.

First, install gnome-tweak-tool, gnome-shell-extensions, and the gnome-shell-integration "native hosts" package chrome-gnome-shell by running the following commands in a terminal:
sudo apt update
sudo apt upgrade
sudo apt install gnome-tweak-tool gnome-shell-extensions chrome-gnome-shell

Reboot before you proceed.

Next, go to the bitcoin-markets official-gnome-shell-extension homepage and install the bitcoin-markets extension.
Finally, open the application "gnome-tweak-tool" (it might be listed as "tweaks") and click on the "extensions" tab on the left and make sure that the extension is enabled here (there should be a toggle switch for each extension listed).

Please post any errors or problems you encounter. Thanks!


text:
Q: Does View.setVisibility(View.VISIBLE) forces the view to redraw even if it's already visible? I'm trying to figure out the optimization for my custom view. I'm wondering if the calling to View.setVisibility(View.VISIBLE) forces the Android framework to update the view visibility (<- forcing the view to redraw) even if the view is already visible.

A: No, it doesn't.
Take a look at setVisibility():
public void setVisibility(int visibility) {
    setFlags(visibility, VISIBILITY_MASK);
    if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
}

It simply calls setFlags(), which immediately returns if nothing has changed:
....
int changed = mViewFlags ^ old;
if (changed == 0) {
    return;
}

Even if it(somehow) got past there, it then checks for the individual flags changing, and only updates if one of them is different than it was.

A: Looking in View#setVisibility:
public void setVisibility(int visibility) {
    setFlags(visibility, VISIBILITY_MASK);
    if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
}

setFlags(...) method begins with:
int old = mViewFlags;
mViewFlags = (mViewFlags & ~mask) | (flags & mask);

int changed = mViewFlags ^ old;
if (changed == 0) {
    return;
}

So I am pretty sure this method doesn't do anything. Otherwise, it would do a lot of things, besides triggering layout and redraw.
Background#setVisible is similar:
public boolean setVisible(boolean visible, boolean restart) {
    boolean changed = mVisible != visible;
    if (changed) {
        mVisible = visible;
        invalidateSelf();
    }
    return changed;
}

the if will be false so this will not do anything.
However, View#setVisible() is overwritten by: ImageView, MediaRouteButton, ProgressBar, SurfaceView and ViewStub. You would need to check each implementation if it does anything else extra - you're maybe using one of these subclasses.
Same applies for Drawable: there are 8 classes that overwrite Drawable#setVisible(boolean, boolean):

*

*ClipDrawable

*DrawableContainer

*AnimationDrawable - extends from DrawableContainer

*InsetDrawable

*LayerDrawable

*RotateDrawble

*ScaleDrawable

*SlideDrawable

Depending on your combination, you may find that you're actually doing something extra, so you need to investigate what kind of View you're using and its background drawable what kind of drawable is it.

A: setVisibility() sets view flags by calling setFlags inside.. and if we go into sdk  View.setFlags() we can see that this method nothing to do if flags state isn't changed.  Code from sdk View.setFlags() method: int changed = mViewFlags ^ old;
        if (changed == 0) {
            return;
        }

A: I'm not 100% but I don't believe so
from grepcode of the View class, this is from the setFlags(int flags, int mask) method which is called from setVisibility(int visibility)
int changed = mViewFlags ^ old;
if (changed == 0) {
    return;
}

after this in the same method are calls to requestLayout()and invalidate()
so going by that I'd say no it doesn't


text:
Q: Run Kubernetes in a docker container in GitLab runner? I need to be able to execute some Python code that would:

*

*Run a docker container in GitLab runner.

*Install Kubernetes (Minikube?) in that container.

*Run a pod in that Kubernetes.

I was having troubles finding the way to run Kubernetes in a container. It shouldn't be anything advanced, just for test purposes.

A: Use Kind instead of Minikube. These articles may help you.

*

*https://adamrushuk.github.io/running-kind-in-gitlab-ci-on-kubernetes/

*https://gist.github.com/trondhindenes/0307fbe9cda1164115353b4632a31ea9


text:
Q: custom facebook fan page I want a facebook fan page with something like this:

*

*With new design/theme, matching to my new website (orange/black)

*Custom Logo/contents display

*30 boxes short description, on mouse hover, get some highlight for box and on click of specific box, opens a new pop-up

*pop-up should contain more detailed description and a link to specific page on my website

I think above things are achievable using FBML but any good ref/guide would be appreciated to help me quickly develop such a thing.

A: FBML is being deprecated by Facebook. You can create an iframe application instead. In an iframe you can basiclly do anything you like. As for themeing the page, you can't touch the facebook design. You can only control the contents of the iframe itself. You can however upload an image for the "profile picture".
Here is a guide for iframe apps for your reference:
http://www.hyperarts.com/blog/adding-iframe-application-to-facebook-fan-page/

A: Here is the reference site where you find the full demonstration of custom FB fan page.
You can achieve that using fb api.

http://www.kimwoodbridge.com/how-to-create-a-custom-facebook-fan-page/
http://blog.theunical.com/facebook-integration/simple-steps-to-publish-on-facebook-fan-page-using-php/
http://www.webdigi.co.uk/blog/2010/creating-a-custom-facebook-page/


text:
Q: Populating firebase recycler view with multiple order by I have the address,quantity and medname fields. I need to extract the names of the stores in that address having the given medname and value should be greater than the given quantity.

FirebaseRecyclerOptions<model> options =
            new FirebaseRecyclerOptions.Builder<model>()
                    .setQuery(FirebaseDatabase.getInstance().getReference(address).orderByChild(medname).equalTo(medname), model.class)
                    .build();


text:
Q: Evaluate the integral $I=\int\limits_{-\infty}^{\infty} \frac{\sin^{2}u}{u^{2}}du$ To evaluate this integral I have got to use Parseval's Theorem and the fourier transform of
$$s(x)=\begin{cases}
0  & x\leq -a \\
1 & -a<x<a \\
0 & x \geq a.\end{cases}$$
This works out to be
$$\tilde{s}(k)=\frac{e^{ika}}{ik}-\frac{e^{-ika}}{ik}$$
I have then changed this into sin and cos and got to the stage of
$$|\tilde{s}(k)|^{2}=\left|\frac{-4\sin^{2}(ka)}{-k^{2}}\right|$$
but this is as far as I have got and I can't figure out what to do from here.

A: The FT of $f(x) = \sin{x}/x$ is
$$\hat{f}(k) = \begin{cases} \\\pi & |k| < 1 \\ 0 & |k| > 1 \end{cases}$$
Parseval's theorem then implies that
$$\int_{-\infty}^{+\infty} dx \frac{\sin^2{x}}{x^2} = \frac{1}{2 \pi} \int_{-1}^1 dk \: \pi^2 = \pi $$

A: Take $a=1$ in your function $s(x)$. The Fourier transform of $s$ is $$\frac{1}{\sqrt{2\pi}}\int_{-1}^1 e^{-iwx}\,dx=\sqrt{\frac{2}{\pi}}\frac{\sin w}{w} $$ Then Parseval (also called Plancherel) relation says $$\int_{-\infty}^{\infty}\frac{2}{\pi}\frac{\sin^2w}{w^2}\,dw = \int_{-1}^1 1^2\,dx=2.$$


text:
Q: Mongoose / mongoDB drop unique index constraint I created a unique index using Mongoose sometime ago in my database.
Model.index({name: 1, location: 1}, {unique: true});

Now due to some coding changes, I would like to drop the uniqueness on the index. Is there a way to just drop the uniqueness on the index?
The only thing I can come up with is to just do
Model.dropIndex({name: 1, location: 1});
Model.index({name: 1, location: 1});

Is this correct? Or is there less a confusing way to write the code..

A: Yes as stated in the docs:

To modify an existing index, you need to drop and recreate the index
  with the exception of m TTL indexes.

So your code is correct for the time being. Maybe in the future they add the possibility to change it in place.

A: Yes that is correct way of dropping. You can either do it from mongo client.
or from node server like this
Model( { {name: 1, location: 1} }, function(err){
     if(err){
         res.send("error");
    }
    else{
        res.send("success");
    }
});

A: If you use a UI tool like RoboMongo, you can drop it from its UI


text:
Q: How would I get it to fade to another view when rotated? I know how to get the view to fade in, but how do I see when they've rotated the screen left or right?

A: You can re-load views, change views, basically do anything you want in the shouldAutoRotate method of your UIViewController:
(BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation

You can manipulate anything you like here.  I have a UIWebView that loads a page optimized for portrait or landscape depending on what orientation this method tells me is coming.
As for the fade, you can use UIViewAnimations
[UIView beginAnimations:nil context:NULL];
play with the alpha (1 is full display; 0 is total fade)
[UIView commitAnimations];

Good Luck!

A: Changes in the view hierarchy on interface rotation are best made in the willAnimateRotationToInterfaceOrientation:duration: method. The view controller will call this method from inside the animation block it creates for the rotation animation.


text:
Q: Summation of sgn function I seen the equation $\sum_\sigma(\operatorname{sgn} \sigma)^2=k!$, where $\sigma\in S_k$ ($S_k$ is the symmetric group). How can I prove this equation?

A: $\text{sgn}\sigma \in \{1,-1\}$, then $(\text{sgn}\sigma)^2 = 1$ for all $\sigma \in S_k$.
Hence:
$$
\sum_{\sigma}(\text{sgn}\sigma)^2 = \sum_{\sigma} 1 = k!
$$


text:
Q: How do I rotate a shape in CSS3 but not rotate the text inside the shape? Just getting started out in CSS3 and had a beginner question (first question on stackoverflow!). I've created four little shapes that rotate and change color when you hover over them. Inside each shape is a text box with a phrase like "About" or "Contact." How do I make it so that when I hover, the text box does not rotate but the shape around it does? I imagine I'll have to counter-rotate my span the same degrees as the shape rotates, but I'm having trouble doing this. I know the spacing is funny on the shapes, but I'm just setting this up as an exercise for myself. I'll address all the cosmetic things once I've figured out the rotation problem.
.burst-12 {
width: 80px;
height: 80px;
text-align: center;
position: absolute;
left:50px;
opacity: .8;
top:100px;
border-radius: 17px;
-moz-border-radius: 17px;
-webkit-border-radius: 15 16 17 18px;
}

.burst-12:before, .burst-12:after {
content: "";
position: absolute;
top: 0;
left: 0;
height: 80px;
width: 80px;
background: inherit;
}

.burst-12:before {
-webkit-transform: rotate(30deg);
   -moz-transform: rotate(30deg);
    -ms-transform: rotate(30deg);
     -o-transform: rotate(30deg);
border-radius: 18px;
-moz-border-radius: 18px;
-webkit-border-radius: 18 19 17 16px;
}

.burst-12:after {
-webkit-transform: rotate(60deg);
   -moz-transform: rotate(60deg);
    -ms-transform: rotate(60deg);
     -o-transform: rotate(60deg);
border-radius: 19px;
-moz-border-radius: 19px;
-webkit-border-radius: 19 10 11 16px;
}

.x1{
  background: #f64260;
}

.x2{
background: #f8605b;
left:123px;
-webkit-transform: rotate(15deg);
   -moz-transform: rotate(15deg);
    -ms-transform: rotate(15deg);
     -o-transform: rotate(15deg);
}

.x1:hover{
background-color:#94dbdd;
-webkit-transform: rotate(300deg);
   -moz-transform: rotate(300deg);
    -ms-transform: rotate(300deg);
     -o-transform: rotate(300deg);
}

.x2:hover{
background-color:#4c6278;
-webkit-transform: rotate(360deg);
   -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
     -o-transform: rotate(360deg);
}

.x3 {
background-color: sandybrown;
left:190px;
-webkit-transform: rotate(10deg);
   -moz-transform: rotate(10deg);
    -ms-transform: rotate(10deg);
     -o-transform: rotate(10deg);
}

.x3:hover{
background-color:cornflowerblue;
-webkit-transform: rotate(360deg);
   -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
     -o-transform: rotate(360deg);
}

.x4{
background-color: #f1ce4b;
left:260px;
-webkit-transform: rotate(10deg);
   -moz-transform: rotate(10deg);
    -ms-transform: rotate(10deg);
     -o-transform: rotate(10deg);
}

.x4:hover{
background-color:#305578;
-webkit-transform: rotate(360deg);
   -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
     -o-transform: rotate(360deg);
}

.burst-12 span{
 display:block;
 position:absolute;
 z-index:2;
}

p:first-letter{
text-transform: uppercase;
}

p {
color: white;
font-family: "Adobe Caslon Pro", "Hoefler Text", Georgia, Garamond, Times,     serif;
letter-spacing:0.1em;
text-align:center;
margin: 30px auto;
text-transform: lowercase;
line-height: 145%;
font-size: 14pt;
font-variant: small-caps;
border-style:solid;
border-width: 1px;
padding: 4px;
}

Here's my jfiddle: https://jsfiddle.net/mthrasher33/bdh8sybj/
Thanks!

A: You are correct, you can count-rotate the text:
.x1:hover span{
    -webkit-transform: rotate(-300deg);
       -moz-transform: rotate(-300deg);
        -ms-transform: rotate(-300deg);
         -o-transform: rotate(-300deg);
}

This is what that would look like: https://jsfiddle.net/bdh8sybj/1/
And if you want to keep the text in the same position, you can use CSS3 translate:
.x1:hover span{
    -webkit-transform: rotate(-300deg) translateY(-8px) translateX(-8px);
       -moz-transform: rotate(-300deg) translateY(-8px) translateX(-8px);
        -ms-transform: rotate(-300deg) translateY(-8px) translateX(-8px);
         -o-transform: rotate(-300deg) translateY(-8px) translateX(-8px);
}

https://jsfiddle.net/bdh8sybj/2/


text:
Q: Eliminating a color with OpenCV I'm trying to eliminate blue color using the following code with OpenCV:
import cv2
import numpy as np

img=cv2.imread('//home/ze/Downloads/blue.jpg ')

lower = np.array([0,0,204], np.uint8)
upper = np.array([204,255,255], np.uint8)
mask = cv2.inRange(img, lower, upper)

res = cv2.bitwise_and(img, img, mask= mask)

cv2.imshow('Result', res)

k=cv2.waitkey(5) & 0xFF

if k==27:
    cv2.destroyAllWindows()

but I'm getting this error:

OpenCV Error: Sizes of input arguments do not match (The lower bounary is neither an array of the same size and same type as src, nor a scalar) in inRange

A: The problem is most likely related to loading the specified image-path. Generally, I plaster my code with these kinds of checks when accessing file-system:
img = cv2.imread('/path/that/might/change')
if img is None:
    print("Error loading img")
    sys.exit(-1)

I think generally it's a good idea to do these assertions when loading data from external resources, whether over the internet or file-system. Your code runs without a problem when specifying the correct path to an image, other than changing cv2.waitKey(5) to cv2.waitKey(), or your image will only flash open briefly.


text:
Q: networkx in python reading from csv file I have a data in csv file and that has following datas in it:
    Origin  Destiny  Hours
0     Alat     Baku   1.08
1     Baku     Alat   1.13
2     Alat  Shirvan   0.83
3  Shirvan     Alat   0.80
4  Imishli  Shirvan   1.42
Index(['Origin', 'Destiny', 'Hours'], dtype='object')

Now when i do
G = networkx.from_pandas_edgelist(data, source='Origin', target='Destiny', edge_attr=True)

there happens a problem or a misunderstanding for me: Because both G.edges["Baku","Alat"] and G.edges["Alat","Baku"] gives the same result which is {'Hours': 1.13}. Why is it like this,as it should give 1.08 and 1.13 for reversed order.

A: You should use Directed graphs by using parameter create_using=networkx.DiGraph()
G = networkx.from_pandas_edgelist(
    data, source='Origin', target='Destiny', edge_attr=True,
create_using=networkx.DiGraph())


text:
Q: Wire up AngularJS controller to express controller I'm getting started with node/express/Angular by using the MEAN stack at mean.io.
I don't understand how the Angular controller calls the express controller to fetch data.
What I have is public/js/controllers/index.js:
angular.module('mean.system').controller('IndexController', ['$scope', 'Global', 'Tabs',
    function ($scope, Global, Tabs) {
        $scope.global = Global;
        Tabs.query(function(tabs) {
            $scope.tabs = tabs;
        });
}]);

But I'm confused what exactly 'Tabs' is. I know that somehow, magically, eventually this method is called - I think this is the Express controller?
app/controllers/tabs.js:
exports.all = function(req, res) {
    Tab.find().sort('artist').select("-content").populate('user').exec(function(err, tabs) {
    if (err) {
        res.render('error', {
            status: 500
        });
    } else {
        res.jsonp(tabs);
    }
});
};

But I don't understand how it gets called. What I want to do is call a different method in app/controllers/tabs.js instead - namely, this:
exports.newest = function(req, res) {
    Tab.find().sort('-created').limit(10).select("-content").exec(function(err, tabs) {
    ...

But I don't understand how to "wire up" the AngularJS controller with the express controller.
i.e. what do I have to do so that I can do something like this in my controller:
angular.module('mean.system').controller('IndexController', ['$scope', 'Global', 'Tabs',
    function ($scope, Global, Tabs) {
        $scope.global = Global;
        Tabs.newest(function(tabs) { // this won't work
            $scope.tabs = tabs;
        });
}]);

A: In MEAN, The Articles service is an angular service that returns a $resource object you can usually find in the public/js/services folder.
$resource is a wrapper around $http AJAX service that comes with angularjs, it enables you to connect with RESTful endpoints if your REST service is built in a specific manner.
The connection to the the node.js controller happens using the routes.js object found in the config folder that binds routes to specific module methods.
further reading:
http://docs.angularjs.org/api/ngResource.$resource
http://expressjs.com/api.html#app.VERB


text:
Q: Why my json logs have text-payload in the output, and not json-payload? I am running Fluentd in GKE to get my containers' logs in Stackdriver using my customized Fluentd configuration file.
Some logs which are json objects in the container log files at /var/log/containers/, are having text-payload at Stackdriver.
I want them to show up as json-payload.
When I use the built in Fluentd agent of Stackdriver (i.e. not using my customized Fluentd config file), those logs have json-payload.
What in my config file could cause this problem?
Here is my config file:
<source>
  type tail
  format json
  time_key time
  path /var/log/containers/*.log
  pos_file /var/log/gcp-containers.log.pos
  time_format %Y-%m-%dT%H:%M:%S.%N%Z
  tag reform.*
  read_from_head true
</source>

 <filter reform.**>
  type parser
  format /^(?<time>\d{2}[^\s]*) : \[[^\]]*\] \[[^\]]*\] \[[^\]]*\] \[[^\]]*\] (?<severity>[^ ]*) (.*)/
  reserve_data true
  suppress_parse_error_log true
  key_name log
</filter>

<filter reform.**>
  type parser
  format /^(?<severity>\w)(?<time>\d{4} [^\s]*)\s+(?<pid>\d+)\s+(?<source>[^      \]]+)\] (?<log>.*)/
  reserve_data true
  suppress_parse_error_log true
  key_name log
</filter>
<filter reform.**>
  @type concat
  key log
  n_lines 1
</filter>

<filter reform.**>
  @type record_transformer
  enable_ruby true
  <record>
  log ${record["log"].gsub(/[0-9]{4} *[0-9]{4} *[0-9]{4} *[0-9]{4}/,"xxxx xxxx xxxx xxxx")}
  </record>
</filter>

<match reform.**>
  type record_reformer
  enable_ruby true
  tag raw.kubernetes.${tag_suffix[4].split('-')[0..-2].join('-')}
</match>
 # Detect exceptions in the log output and forward them as one log entry.
<match raw.kubernetes.**>
  @type copy

  <store>
    @type prometheus

    <metric>
      type counter
      name logging_line_count
      desc Total number of lines generated by application containers
    </metric>
  </store>
  <store>
    @type detect_exceptions

    remove_tag_prefix raw
    message log
    stream stream
    multiline_flush_interval 5
    max_bytes 500000
    max_lines 1000
  </store>
</match>

<source>
  type tail
  format /^(?<time>[^ ]* [^ ,]*)[^\[]*\[[^\]]*\]\[(?<severity>[^ \]]*) *\] (?<message>.*)$/
  time_format %Y-%m-%d %H:%M:%S
  path /var/log/salt/minion
  pos_file /var/log/gcp-salt.pos
  tag salt
</source>

# Example:
# Dec 21 23:17:22 gke-foo-1-1-4b5cbd14-node-4eoj startupscript: Finished running startup script /var/run/google.startup.script
<source>
  type tail
  format syslog
  path /var/log/startupscript.log
  pos_file /var/log/gcp-startupscript.log.pos
  tag startupscript
</source>
 # Examples:
# time="2016-02-04T06:51:03.053580605Z" level=info msg="GET /containers/json"
# time="2016-02-04T07:53:57.505612354Z" level=error msg="HTTP Error" err="No such image: -f" statusCode=404
<source>
  type tail
  format /^time="(?<time>[^)]*)" level=(?<severity>[^ ]*) msg="(?<message>[^"]*)"( err="(?<error>[^"]*)")?( statusCode=($<status_code>\d+))?/
  path /var/log/docker.log
  pos_file /var/log/gcp-docker.log.pos
  tag docker
</source>

# Example:
# 2016/02/04 06:52:38 filePurge: successfully removed file /var/etcd/data/member/wal/00000000000006d0-00000000010a23d1.wal
<source>
  type tail
  # Not parsing this, because it doesn't have anything particularly useful to
  # parse out of it (like severities).
  format none
  path /var/log/etcd.log
  pos_file /var/log/gcp-etcd.log.pos
  tag etcd
</source>

# Example:
# I0204 07:32:30.020537    3368 server.go:1048] POST /stats/container/: (13.972191ms) 200 [[Go-http-client/1.1] 10.244.1.3:40537]
<source>
  type tail
  format multiline
  multiline_flush_interval 5s
  format_firstline /^\w\d{4}/
  format1 /^(?<severity>\w)(?<time>\d{4} [^\s]*)\s+(?<pid>\d+)\s+(?<source>[^ \]]+)\] (?<message>.*)/
  time_format %m%d %H:%M:%S.%N
  path /var/log/kubelet.log
  pos_file /var/log/gcp-kubelet.log.pos
  tag kubelet
</source>
# Example:
# I1118 21:26:53.975789       6 proxier.go:1096] Port "nodePort for kube-system/default-http-backend:http" (:31429/tcp) was open before and is still needed
<source>
  type tail
  format multiline
  multiline_flush_interval 5s
  format_firstline /^\w\d{4}/
  format1 /^(?<severity>\w)(?<time>\d{4} [^\s]*)\s+(?<pid>\d+)\s+(?<source>[^ \]]+)\] (?<message>.*)/
  time_format %m%d %H:%M:%S.%N
  path /var/log/kube-proxy.log
  pos_file /var/log/gcp-kube-proxy.log.pos
  tag kube-proxy
</source>

# Example:
# I0204 07:00:19.604280       5 handlers.go:131] GET /api/v1/nodes: (1.624207ms) 200 [[kube-controller-manager/v1.1.3 (linux/amd64) kubernetes/6a81b50] 127.0.0.1:38266]
<source>
  type tail
  format multiline
  multiline_flush_interval 5s
  format_firstline /^\w\d{4}/
  format1 /^(?<severity>\w)(?<time>\d{4} [^\s]*)\s+(?<pid>\d+)\s+(?<source>[^ \]]+)\] (?<message>.*)/
  time_format %m%d %H:%M:%S.%N
  path /var/log/kube-apiserver.log
  pos_file /var/log/gcp-kube-apiserver.log.pos
  tag kube-apiserver
</source>

# Example:
# 2017-02-09T00:15:57.992775796Z AUDIT: id="90c73c7c-97d6-4b65-9461-f94606ff825f" ip="104.132.1.72" method="GET" user="kubecfg" as="<self>" asgroups="<lookup>" namespace="default" uri="/api/v1/namespaces/default/pods"
# 2017-02-09T00:15:57.993528822Z AUDIT: id="90c73c7c-97d6-4b65-9461-f94606ff825f" response="200"
<source>
  type tail
  format multiline
  multiline_flush_interval 5s
  format_firstline /^\S+\s+AUDIT:/
  # Fields must be explicitly captured by name to be parsed into the record.
  # Fields may not always be present, and order may change, so this just looks
  # for a list of key="\"quoted\" value" pairs separated by spaces.
  # Unknown fields are ignored.
  # Note: We can't separate query/response lines as format1/format2 because
  #       they don't always come one after the other for a given query.
  # TODO: Maybe add a JSON output mode to audit log so we can get rid of this?
  format1 /^(?<time>\S+) AUDIT:(?: (?:id="(?<id>(?:[^"\\]|\\.)*)"|ip="(?<ip>(?:[^"\\]|\\.)*)"|method="(?<method>(?:[^"\\]|\\.)*)"|user="(?<user>(?:[^"\\]|\\.)*)"|groups="(?<groups>(?:[^"\\]|\\.)*)"|as="(?<as>(?:[^"\\]|\\.)*)"|asgroups="(?<asgroups>(?:[^"\\]|\\.)*)"|namespace="(?<namespace>(?:[^"\\]|\\.)*)"|uri="(?<uri>(?:[^"\\]|\\.)*)"|response="(?<response>(?:[^"\\]|\\.)*)"|\w+="(?:[^"\\]|\\.)*"))*/
  time_format %FT%T.%L%Z
  path /var/log/kube-apiserver-audit.log
  pos_file /var/log/gcp-kube-apiserver-audit.log.pos
  tag kube-apiserver-audit
</source>

# Example:
# I0204 06:55:31.872680       5 servicecontroller.go:277] LB already exists and doesn't need update for service kube-system/kube-ui
<source>
  type tail
  format multiline
  multiline_flush_interval 5s
  format_firstline /^\w\d{4}/
  format1 /^(?<severity>\w)(?<time>\d{4} [^\s]*)\s+(?<pid>\d+)\s+(?<source>[^ \]]+)\] (?<message>.*)/
  time_format %m%d %H:%M:%S.%N
  path /var/log/kube-controller-manager.log
  pos_file /var/log/gcp-kube-controller-manager.log.pos
  tag kube-controller-manager
</source>
<source>
  type tail
  format multiline
  multiline_flush_interval 5s
  format_firstline /^\w\d{4}/
  format1 /^(?<severity>\w)(?<time>\d{4} [^\s]*)\s+(?<pid>\d+)\s+(?<source>[^ \]]+)\] (?<message>.*)/
  time_format %m%d %H:%M:%S.%N
  path /var/log/kube-scheduler.log
  pos_file /var/log/gcp-kube-scheduler.log.pos
  tag kube-scheduler
</source>

# Example:
# I1104 10:36:20.242766       5 rescheduler.go:73] Running Rescheduler
<source>
  type tail
  format multiline
  multiline_flush_interval 5s
  format_firstline /^\w\d{4}/
  format1 /^(?<severity>\w)(?<time>\d{4} [^\s]*)\s+(?<pid>\d+)\s+(?<source>[^ \]]+)\] (?<message>.*)/
  time_format %m%d %H:%M:%S.%N
  path /var/log/rescheduler.log
  pos_file /var/log/gcp-rescheduler.log.pos
  tag rescheduler
</source>

# Example:
# I0603 15:31:05.793605       6 cluster_manager.go:230] Reading config from path /etc/gce.conf
<source>
  type tail
  format multiline
  multiline_flush_interval 5s
  format_firstline /^\w\d{4}/
  format1 /^(?<severity>\w)(?<time>\d{4} [^\s]*)\s+(?<pid>\d+)\s+(?<source>[^ \]]+)\] (?<message>.*)/
  time_format %m%d %H:%M:%S.%N
  path /var/log/glbc.log
  pos_file /var/log/gcp-glbc.log.pos
  tag glbc
</source>

<source>
  type tail
  format multiline
  multiline_flush_interval 5s
  format_firstline /^\w\d{4}/
  format1 /^(?<severity>\w)(?<time>\d{4} [^\s]*)\s+(?<pid>\d+)\s+(?<source>[^ \]]+)\] (?<message>.*)/
  time_format %m%d %H:%M:%S.%N
  path /var/log/cluster-autoscaler.log
  pos_file /var/log/gcp-cluster-autoscaler.log.pos
  tag cluster-autoscaler
</source>

# Logs from systemd-journal for interesting services.
<source>
  type systemd
  filters [{ "_SYSTEMD_UNIT": "docker.service" }]
  pos_file /var/log/gcp-journald-docker.pos
  read_from_head true
  tag docker
</source>

<source>
  type systemd
  filters [{ "_SYSTEMD_UNIT": "kubelet.service" }]
  pos_file /var/log/gcp-journald-kubelet.pos
  read_from_head true
  tag kubelet
</source>

monitoring.conf: |-

# Prometheus monitoring
<source>
  @type prometheus
  port 80
</source>
<source>
  @type prometheus_monitor
</source>
# This source is used to acquire approximate process start timestamp,
# which purpose is explained before the corresponding output plugin.
<source>
  @type exec
  command /bin/sh -c 'date +%s'
  tag process_start
  time_format %Y-%m-%d %H:%M:%S
  keys process_start_timestamp
</source>

# This filter is used to convert process start timestamp to integer
# value for correct ingestion in the prometheus output plugin.
<filter process_start>
  @type record_transformer
  enable_ruby true
  auto_typecast true
  <record>
    process_start_timestamp ${record["process_start_timestamp"].to_i}
  </record>
</filter>
  output.conf: |-
# This match is placed before the all-matching output to provide metric
# exporter with a process start timestamp for correct exporting of
# cumulative metrics to Stackdriver.
<match process_start>
  @type prometheus
  <metric>
    type gauge
    name process_start_time_seconds
    desc Timestamp of the process start in seconds
    key process_start_timestamp
  </metric>
</match>
<match kubernetes.**>
  @type copy

  <store>
    @type google_cloud

    # Set the buffer type to file to improve the reliability and reduce the memory consumption
    buffer_type file
    buffer_path /var/log/fluentd-buffers/kubernetes.containers.buffer
    # Set queue_full action to block because we want to pause gracefully
    # in case of the off-the-limits load instead of throwing an exception
    buffer_queue_full_action block
    # Set the chunk limit conservatively to avoid exceeding the GCL limit
    # of 10MiB per write request.
    buffer_chunk_limit 2M
    # Cap the combined memory usage of this buffer and the one below to
    # 2MiB/chunk * (6 + 2) chunks = 16 MiB
    buffer_queue_limit 6
    # Never wait more than 5 seconds before flushing logs in the non-error case.
    flush_interval 5s
    # Never wait longer than 30 seconds between retries.
    max_retry_wait 30
    # Disable the limit on the number of retries (retry forever).
    disable_retry_limit
    # Use multiple threads for processing.
    num_threads 2
  </store>
  <store>
    @type prometheus

    <metric>
      type counter
      name logging_entry_count
      desc Total number of log entries generated by either an application container or a system component
      <labels>
        component container
      </labels>
    </metric>
  </store>
</match>

<match **>
  @type copy

  <store>
    @type google_cloud

    detect_subservice false
    buffer_type file
    buffer_path /var/log/fluentd-buffers/kubernetes.system.buffer
    buffer_queue_full_action block
    buffer_chunk_limit 2M
    buffer_queue_limit 2
    flush_interval 5s
    max_retry_wait 30
    disable_retry_limit
    num_threads 2
  </store>
  <store>
    @type prometheus

    <metric>
      type counter
      name logging_entry_count
      desc Total number of log entries generated by either an application         container or a system component
      <labels>
        component system
      </labels>
    </metric>
  </store>
</match>

A: There was an opened issue (48139) a couple of months ago related to fluentd-gcp parsing json payload as text to Stackdriver.  It should have been fixed after the 1.6.7 release.


text:
Q: jQuery mobile CSS and data-attribute issues I'm using jQuery Mobile in a project and i'm not sure about how to handle some data-attributes CSS overrides.
For example, when i use data-attributes like data-role="page" to create page transitions, it overrides some of my CSS rules, applying its own. I'm not quite familiar with data-attributes yet...
I could use (a lot of) !important declarations but we know it might led to problems and clutter etc and therefore it should be avoided.
Any suggestions on how to deal with that?


text:
Q: Loading multiple Flot pie charts from external js file as needed Using Flot to create a whole bunch of pie charts across a site.
I'm finding that if a chart is defined, but on a given page the div it's assigned to isn't there or doesn't have the height/width set, that chart and all those defined thereafter do not display.
The issue is that some charts are needed in some pages and not in others. I'd like to define the charts all in one place and place them in their appropriate views as needed, but with Flot Pie it seems that as soon as the script comes up with no place to put a given chart, the script thereafter simply blows up and no chart is loaded after that point. This even happens if those subsequent charts are on another page/view.
Here's a fiddle illustrating the issue. If you remove the commented div in the HTML, the rest of the charts will then load when run. But comment out any of these divs, console will throw the error:
Uncaught Error: Invalid dimensions for plot, width = null, height = null
...and the charts will thereafter fail to load. Since there's nowhere to put the chart, I understand the error. But shouldn't it simply be ignored and the rest of the script executed?
This issue has been asked about before on SO, but didn't draw so much as a comment until I came along with the same issue. I'd have to agree with Richard that this seems like this would be a common problem if it's inherent in the implementation. Is there no way around this?
HTML:

Performance

Critical Thinking

Affective Domain

Attitudes

JQuery:
$(document).ready(function () {
    var dataSetDistrictLMCore = [
    {label: "95% - 100%", data: 56, color: "#006837" },
    { label: "80% - 94%", data: 10, color: "#18859d" },
    { label: "70% - 79%", data: 9, color: "#ef9521" },
    { label: "Below 70%", data: 25, color: "#c62037" }
];
  var dataSetCreative = [
    {label: "Mastered", data: 26, color: "#007700" },
    { label: "Not Mastered", data: 14, color: "#cc0000" },
    { label: "Not Attempted", data: 60, color: "#ACAAA5" }
];
    var dataSetCritical = [
    {label: "Mastered", data: 24, color: "#007700" },
    { label: "Not Mastered", data: 49, color: "#cc0000" },
    { label: "Not Attempted", data: 27, color: "#ACAAA5" }
];
    var dataSetAffective = [
    {label: "Best Answer", data: 33.3, color: "#007700" },
    { label: "Other Answer", data: 33.3, color: "#cc0000" },
    { label: "No Answer", data: 33.3, color: "#ACAAA5" }
];
    var dataSetAttitudes = [
    {label: "Best Answer", data: 43.3, color: "#007700" },
    { label: "Other Answer", data: 13.3, color: "#cc0000" },
    { label: "No Answer", data: 43.3, color: "#ACAAA5" }
];

    var options2 = {
        series: {
            pie: {
                show: true,
                innerRadius: 0.5,
                label: {
                    show: true
                },
                offset: {
                    left: 0,
                    top: -24
                }
            }
        }
    };

$(window).load(function () {
        $.plot($("#flot-placeholder-DistrictLMCore"), dataSetDistrictLMCore, options2);
        $("#flot-placeholder-DistrictLMCore").showMemo();
        $.plot($("#flot-placeholder-creative"), dataSetCreative, options2);
        $("#flot-placeholder-creative").showMemo();
        $.plot($("#flot-placeholder-critical"), dataSetCritical, options2);
        $("#flot-placeholder-critical").showMemo();
        $.plot($("#flot-placeholder-affective"), dataSetAffective, options2);
        $("#flot-placeholder-affective").showMemo();
        $.plot($("#flot-placeholder-attitudes"), dataSetAttitudes, options2);
        $("#flot-placeholder-affective").showMemo();/**/
    });

    $.fn.showMemo = function () {
        $(this).bind("plothover", function (event, pos, item) {
            if (!item) { return; }
            console.log(item.series.data)
            var html = [];
            var percent = parseFloat(item.series.percent).toFixed(2);

            html.push("
",
          "",
          item.series.label,
          " : ",
          $.formatNumber(item.series.data[0][1], { format: "#,###", locale: "us" }),
          " (", percent, "%)",
          "",
          "
");
            $("#flot-memo").html(html.join(''));
        });
    };

    });

EDIT: I should mention that the issue persists even if I were to try to load different charts from a different docready or even a different js file.

A: You try to draw a chart inside a non-existing div element, so you get an error and execution of your JavaScript holds. The best way to handle this is to only draw the charts you want on this specific page.
Another way to get this working would be to catch the exceptions for each chart, so that the following charts will be drawn regardless of errors with the previous charts. This works for all kinds of problems, not only the "container not found" one. See this fiddle:
function drawChart(container, data) {
    try {
        $.plot($("#" + container), data, options2);
        $("#" + container).showMemo();
    } catch (ex) {
        console.log(ex);
    }
}

$(window).load(function () {
    drawChart("flot-placeholder-DistrictLMCore", dataSetDistrictLMCore);
    drawChart("flot-placeholder-creative", dataSetCreative);
    drawChart("flot-placeholder-critical", dataSetCritical);
    drawChart("flot-placeholder-affective", dataSetAffective);
    drawChart("flot-placeholder-attitudes", dataSetAttitudes);
});


text:
Q: Hibernate not inserting into joined table because id is null I have a many to many relationship between a User and a Trip entity with two foreign keys. I am trying to add a Trip to the User and even though there is a such an ID in my Users table, I receive the following exception:
Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "UserTrip" violates foreign key constraint "user_id"
  Detail: Key (user_id)=(1) is not present in table "User".

User side of the many to many relationship:
@ManyToMany
@JoinTable(name = "\"UserTrip\"", schema = "\"TransportSystem\"", joinColumns = {
                @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "trip_id") })
private List<Trip> trips = new ArrayList<>();

Trip side of the many to many relationship:
@ManyToMany(mappedBy = "trips")
private List<User> users = new ArrayList<>();

DAO function to add a trip:
public void addTrip(int id, Trip trip) {
        executeInsideTransaction(entityManager -> {
            User user = entityManager.find(User.class, id);
            user.getTrips().add(trip);
            });
}

My little helper function to handle transactions within the same dao:
private void executeInsideTransaction(Consumer<EntityManager> action) {
        EntityTransaction tx = entityManager.getTransaction();
        try {
            tx.begin();
            action.accept(entityManager);
            tx.commit();
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
        }
}

This is where I call to add the trip (don't think any more context is needed, if you wish, I can provide more.)
UserService userService = new UserService();
User user = userService.getById(1);
userService.addTrip(1, newTrip);

Things to note:

*

*The entity is "User" but the table it is mapped to is called "Users" since in PostgreSQL the User is a reserved keyword.

*I tried MERGE and REMOVE cascades and a lazy fetch type on the User side

*I tried to pass the whole User object to the addTrip function and then use entityManager.merge() but then as read here on stackoverflow I decided to use entityManager.find() to load the user by id from the database directly and then add a role and commit the transaction. Unfortunately, both cases yield the same result (this exception).

*Needless to say, there is a user_id = 1 in the database.

I would appreciate your input. I know there are many threads regarding this particular exception but honestly I seem unable to resolve it.

A: This has been resolved, to anyone wondering:
The problem comes from the fact that User is a reserved keyword in PostgreSQL. I tried multiple times to avoid problems with it, I created a Users table and mapped my User entity to Users table. So far there were no problems with it.
But once a joined table is involved, things get complicated. In my case, I had a UserTrip joined table with a many to many relationship and Hibernate is looking for a user_id from User. I found no way to explicitly tell hibernate to take Users rather than User, that's why I decided to name my table UsersTrip and everything has been resolved.
Lesson learned - avoid using words similiar to keywords where possible.


text:
Q: Getting this error System.ArgumentException: Host can't be null I'm trying to connect to Postgresql from my project, and I get this error over and over again.
I tried all the Youtube solutions with no improvement.


text:
Q: How to use ASP.NET to get data from MSSQL for JQuery Autocomplete widget I downloaded jquery-ui to use autocomplete widget and I want to get items from an MSSQL database. But I couldn't figure out how to use it in ASP.NET with sql. Codes are basically like below.
        var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "C",
            "C++",
            "Clojure",
            "COBOL",
            "ColdFusion",
            "Erlang",
            "Fortran",
            "Groovy",
            "Haskell",
            "Java",
            "JavaScript",
            "Lisp",
            "Perl",
            "PHP",
            "Python",
            "Ruby",
            "Scala",
            "Scheme"
        ];
        $("#autocomplete").autocomplete({
            source: availableTags
        });

 <div>
        <input id="autocomplete" title="type "a"">
    </div>

EDIT: Just find out how to do it. Just copied the jquery to the server side with below code:
StringBuilder strScript = new StringBuilder();
        strScript.Append("var availableTags = ['java','javascript'];");
        strScript.Append("$('#autocomplete').autocomplete({");
        strScript.Append("source: availableTags});");
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Script",
        strScript.ToString(), true);

A: First you need to write back-end side of code to get data from SQL. Then you will call this function with JQuery and you need to set this values into autocomplete source.
So your autocomplete code should look like this.
$("#YourAutoCompleteInputId").autocomplete({
    autoFocus: true,
    delay: 0,
    scrollIntoView: false,
    source: function (request, response) {
        $.get("/YourControllerName/YourControllerMethod/", { searchTerm: request.term }, function (data) {
            response($.map(data, function (item) {
                return {
                    label: item.Name
                    val: item.Id
                }
            }));
        }).fail(function () {
            alert("error");
        });
    },
    select: function (event, ui) {
        // whatever you return from your back-end code. you can reach here
        // you can reach it by using ui.item.label => it's your label and ui.item.val => is your value.
        // do something when user select one the result from autocomplete list.
    },
    open: function () {
        // do something when user open autocomplete list
    },
    close: function () {
        // do something when user close autocomplete list
    }
});

And your method should be like this.
public async Task<JsonResult> GetApplicantNamesForAutoComplete(string searchTerm)
{
    var list = yourData.Where(x => x.yourTableColumnName.Contains(searchTerm))
        .Select(x => new { x.Id, Name = (x.FirstName + " " + x.LastName)});
    return Json(await list.ToListAsync(), JsonRequestBehavior.AllowGet);
}


text:
Q: Set date format and then convert it in Date from String- Java I am doing this to set a date format and then convert it into date datatype but it is not giving expected results.
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
 DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
 String cur_date=dateFormat.format(new Date());
 myDb.setDOB(formatter.parse(cur_date));

Scenario is: I want  current date to be converted in yyyy/mm/dd and then pass it in setDOB(Date date).
EDIT:Result added Result is Tue Jan 01 00:08:00 IST 2013
GUYS! I am not using 'mm',here I just mistakenly wrote mm in DateFormat it is also MM
EDIT AGAIN First I just used setDOB(new Date() ); but got formatting issue,
then I used SimpleDateFormat.format to set yyyy/MM/dd but it returns String so used
DateFormat.parse to convert it back into date type.

A: You're not using the same format. Case matters! "MM" is for months, "mm" is for minutes.

A: The issue is you MM in the format.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat formatter = new SimpleDateFormat("yyyy/mm/dd");

*

*MM is month

*mm is minute

Refer here for the detailed formats. So it should have been,
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");

A: +1 mael for spotting the format issue first, however...
Date is a container for the number of milliseconds since the epoch (Jan-1970-01-01 GMT), it does not care about the format of the values.
For example, the following...
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date now = new Date();
String cur_date = dateFormat.format(now);

try {
    System.out.println("Now = " + now);
    System.out.println("cur_date = " + cur_date);
    System.out.println("dateFormat.parse(cur_date) = " + dateFormat.parse(cur_date));
} catch (ParseException exp) {
    exp.printStackTrace();
}

Outputs...
Now = Thu Aug 01 18:08:39 EST 2013
cur_date = 2013/08/01
dateFormat.parse(cur_date) = Thu Aug 01 00:00:00 EST 2013

So you can lose important data about the date by doing this...
Leave formatting to when you want to display the value, not when you want to store it (if you can get away with it)

A: It sounds like you're expecting a Date to "know" its format. It doesn't. A Date object just contains a number of milliseconds since the Unix epoch. It doesn't know about time zones, or calendars, or string formats. It's just a date.
So your code should just be:
myDb.setDOB(new Date());

... and then handle the formatting of that wherever you're displaying it.

A: You re using different date String patterns.  MM is for months, mm is for minutes (see SimpleDateFormat API)
Your setDOB is taking a Date object.  I fail to see why you might want to format your date when giving it is as a parameter in your method call.  Usually one formats a date when it needs to be rendered / stored somewhere.

A: formatter.parse is used to parse the String Date, It returns Date Object.
The date is represented as a Date object or as the milliseconds as example since January 1, 1970, 00:00:00 GMT.
I am not getting what actually your doing. Date object is always represented as in the above format.

A: The Question and other Answers all use troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
LocalDate
Apparently you want a date-only value.
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still "yesterday" in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );  // Or "Asia/Kolkata" , "Pacific/Auckland" , etc.
LocalDate today = LocalDate.now( z );

Generating strings
To generate a string representing the value of that LocalDate, simply call toString(). That method generates a string in standard ISO 8601 format.
String output = today.toString();

2017-01-23

Your desired format is close to that, using slash characters in place of hyphens. I suggest sticking with the standard formats whenever possible. But if you insist, just replace the characters.
String output = today.toString().replace( "-" , "/" );

For other formats use the DateTimeFormatter class. And be aware of that class' ability to automatically localize while generating a string.

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


text:
Q: "Distributivity" of unary operations Motivating example: given an algebraic object, there are many useful subobjects which, seen as operations on the category of objects, follow a distributivity-like law over things like products. That's not very clearly-worded, so as an example consider the units of a ring: (AxB)* = A* x B*. There are plenty of other examples. I don't know much category theory at all - maybe category theory isn't the right tag for this - but this strikes me as the sort of thing someone must have studied. Can anyone recommend material for me to read in this sort of direction? (Sorry if that's a bit vague.)
Speaking of tags, I was tempted to include ac.commutative-algebra but I'm not convinced that commutativity is actually an important property here.

A: Let me elaborate on unknown (google)'s comment.  If $\text{Rng}$ denotes the category of unital rings and $\text{Grp}$ denotes the category of groups, then it turns out that "group of units" is a functor $\text{Rng} \to \text{Grp}$.  In fact, it's representable; the group of units of a ring $R$ can be identified with $\text{Hom}(\mathbb{Z}[x, x^{-1}], R)$ (the set of all ring homomorphisms from $\mathbb{Z}[x, x^{-1}]$ to $R$), where the group structure on the Hom-set comes from a Hopf algebra structure on $\mathbb{Z}[x, x^{-1}]$.  And covariant representable functors preserve limits, including binary products.  (Actually, whether this argument is valid depends on the answer to this question which I posted yesterday.)
(A closely related functor is $\text{Hom}(\mathbb{Z}[x], R)$, which is none other than the forgetful functor $\text{Rng} \to \text{Set}$ which sends a ring to its set of elements.  The fact that this functor preserves limits is precisely why the product of rings can be constructed using a product of the underlying sets.  In more complicated categories where the obvious forgetful functor doesn't preserve limits, this isn't necessarily true.)
Closely related to representability (although I've never been clear on the precise relationship) is the fact that "group of units" has a left adjoint $\text{Grp} \to \text{Rng}$ which constructs the group ring of a group.  And functors which have left adjoints preserve limits.
Presumably many other examples can be handled in a similar vein, although I can't think of any right now, so you'll have to give me more examples.


text:
Q: 'invalid blocktype: HM_Deleteorder_Block_Adminhtml_Sales_Order_Grid' in /app/Mage.php:595 Because we've accidently delete a module, we cannot access the adminpage.
Fatal error: Call to a member function setSaveParametersInSession() on boolean in /var/www/html/webshop/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Container.php on line 66
in the logfiles we can find:
exception 'Mage_Core_Exception' with message 'invalid blocktype: HM_Deleteorder_Block_Adminhtml_Sales_Order_Grid' in /var/www/html/webshop/app/Mage.php:595
Stack trace:
#0 /var/www/html/webshop/app/code/core/Mage/Core/Model/Layout.php(495): Mage::throwException('Ongeldig blokty...')
#1 /var/www/html/webshop/app/code/core/Mage/Core/Model/Layout.php(437): Mage_Core_Model_Layout->_getBlockInstance('adminhtml/sales...', Array)
#2 /var/www/html/webshop/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Container.php(66): Mage_Core_Model_Layout->createBlock('adminhtml/sales...', 'sales_order.gri...')
#3 /var/www/html/webshop/app/code/core/Mage/Core/Block/Abstract.php(293): Mage_Adminhtml_Block_Widget_Grid_Container->_prepareLayout()
#4 /var/www/html/webshop/app/code/core/Mage/Core/Model/Layout.php(456): Mage_Core_Block_Abstract->setLayout(Object(Mage_Core_Model_Layout))
#5 /var/www/html/webshop/app/code/core/Mage/Core/Model/Layout.php(472): Mage_Core_Model_Layout->createBlock('adminhtml/sales...', 'sales_order.gri...')
#6 /var/www/html/webshop/app/code/core/Mage/Core/Model/Layout.php(239): Mage_Core_Model_Layout->addBlock('adminhtml/sales...', 'sales_order.gri...')
#7 /var/www/html/webshop/app/code/core/Mage/Core/Model/Layout.php(205): Mage_Core_Model_Layout->_generateBlock(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#8 /var/www/html/webshop/app/code/core/Mage/Core/Model/Layout.php(210): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#9 /var/www/html/webshop/app/code/core/Mage/Core/Controller/Varien/Action.php(344): Mage_Core_Model_Layout->generateBlocks()
#10 /var/www/html/webshop/app/code/core/Mage/Core/Controller/Varien/Action.php(269): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()
#11 /var/www/html/webshop/app/code/core/Mage/Adminhtml/Controller/Action.php(275): Mage_Core_Controller_Varien_Action->loadLayout(NULL, true, true)
#12 /var/www/html/webshop/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php(59): Mage_Adminhtml_Controller_Action->loadLayout()
#13 /var/www/html/webshop/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php(94): Mage_Adminhtml_Sales_OrderController->_initAction()
#14 /var/www/html/webshop/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_Sales_OrderController->indexAction()
#15 /var/www/html/webshop/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('index')
#16 /var/www/html/webshop/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#17 /var/www/html/webshop/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#18 /var/www/html/webshop/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#19 /var/www/html/webshop/index.php(87): Mage::run('', 'store')
#20 {main}

we've tried to delete all folder with HM_deleteorder, but all is gone. Still we receive this error.
Tried to reinstall, but cannot find the module in the marketplace.

A: Usually this happens because the cached layout contains a reference to the old hm_ block.
Please delete the cache by either:
- deleting var/cache/ in your Magento root
- purging external caches (such as redis)
- run n98-magerun to purge the caches
This should help.


text:
Q: Why createDirectoryAtPath with attributes not work In OS X desktop application
NSFileManager *manager = [NSFileManager defaultManager];

NSDictionary *dirMeta = [NSDictionary dictionaryWithObjectsAndKeys:@"jack", @"creator", nil];
NSLog(@"%@", [dirMeta objectForKey:@"creator"]);//output jack

[manager createDirectoryAtPath:@"/Users/loki/Desktop/fromCap" withIntermediateDirectories:YES attributes:dirMeta error:NULL];

NSDictionary *attri2 = [manager attributesOfItemAtPath:@"/User/loki/Desktop/fromCap" error:nil];
NSLog(@"value is %@", [attri2 objectForKey:@"creator"]);//output null

Am I using createDirectoryAtPath wrongly?
Why attri2 get nothing data out of the directory?

A: The attributes dictionary is used to specify the filesystem attributes of the new directories/files:

attributes The file attributes for the new directory and any newly
  created intermediate directories. You can set the owner and group
  numbers, file permissions, and modification date. If you specify nil
  for this parameter or omit a particular value, one or more default
  values are used as described in the discussion. For a list of keys you
  can include in this dictionary, see "Constants" section lists the
  global constants used as keys in the attributes dictionary. Some of
  the keys, such as NSFileHFSCreatorCode and NSFileHFSTypeCode, do not
  apply to directories.

They are not for attaching arbitrary meta data.  Where did you suppose this meta data would be stored anyway?


text:
Q: How do I enforce coding standards? I want to write a script to enforce some rules on the code of my team.
For example, in our code standards all of the member variables and private functions should start with an underscore:
class A{
private:
    int _count;
    float _amount;
    void _increment_count(){ ++_count; }
}

So I want to throw some warning or error or some sort of message for this class if the variables are declared as follows.
class A{
private:
    int count;
    float amount;
    void increment_count(){ ++_count; }
}

I want to write a script that -- when run with this program as the argument -- will show the respective message.
What options are available for accomplishing this?

A: You should take a look at http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis and maybe save a lot of time implementing your own code analyzer.


text:
Q: Undefined local variable or method `params` Rspec I have the following controller RSpec test that should work however when I try to execute the below code:
require 'spec_helper'
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe UsersController do
  include Devise::TestHelpers #Include devise test helpers
  render_views # Render devise views

  describe "GET 'show'"

  before(:each) do
    @user = User.find(params[:id])
    @attr = {:initials => 'EU', :name => 'Example', :full_name => 'Example User',
             :email => 'user@example.com', :password => 'password', :password_confirmation => 'password'

             #@attr = User.all
    }
  end

  it 'should be successful when showing OWN details' do
    get :show, :id => @attr
    response.should be_success
  end

  it 'should find the correct user' do
    get :show, :id => @attr
    assigns(@attr).should == @attr
  end
end

However I am getting the following output: Undefined locacl variable or method 'params' for RSPRC I believe this set up should be correct.

A: I see a few things going on here.
Your calling params within the before statement but where is the id ever set? No where in this code do I see where the user id is ever actually determined/found. You should set @user explicitly using either an id that you know exists or doing something such as User.first.
Then instead of calling
get :show, :id => @attr

you should be calling
get :show, :id => @user.id

Also I'm not sure why you need to include spec_helper twice. Line 2 should be able to be removed.
One more thing - assigns(@attr).should == @attr doesn't make any sense. It should be assigns(:attr).should == @attr. Otherwise you would be passing the value of @attr into the assigns method.


text:
Q: How to change Figure Label? (Fig.: n instead Figure: n) This question seems to be asked a lot. I tried some different solutions and any of them did not work.
My figure caption is displayed as
Figure 1: Caption Here

But I want to display:
Fig. 1: Caption Here

I tried the instructions from several questions in the stackExchange website.
Currently my code looks like
\documentclass[12pt, a4paper]{article}

\pagestyle{headings}

\usepackage{tikz}
%\addto\captionsenglish{\renewcommand{\figurename}{Fig.}}

\usepackage[font=small,labelfont=bf, figurename=Fig.]{caption}
\renewcommand{\figurename}{Fig.}

\usepackage[english]{babel}
\usepackage[latin1]{inputenc}
\usepackage{latexsym}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{verbatim}
\usepackage{stmaryrd}

\begin{document}
\begin{figure}
Drawing here
\caption{Caption here} \label{fig:label}
\end{figure}

\end{document}

If I uncomment the line \addto... the code does not compile.
I found these references in the following questions:
Change caption name of figures
Figure to Fig in both Caption and Autoref
How to change figure caption to Fig. 1. in stead of Fig. 1:
none of them worked.
I also tried the solution the solution in this other link:
http://www.latex-community.org/forum/viewtopic.php?f=45&t=3639
but no success.
I imagine that some of my packages might be in conflict with the caption one. But which one?
Any advice?

A: Forget about caption:
\documentclass{article}

\makeatletter
\renewcommand{\fnum@figure}{Fig. \thefigure}
\makeatother

\begin{document}

\begin{figure}

Drawing here
\caption{Caption here}

\end{figure}

\end{document}

Here I just modified LaTeX command that shows in your captions. Now it displays as you want.


text:
Q: MaxItemCount in Azure Functions/Cosmos DB For Python API for Azure Functions serverless and Comsmos DB input binding. Is it possible to tune maxitemcount? Or is it dynamically set. I do some queries resulting in large results and it seems the bottleneck is throughput between Cosmos DB and the executing HTTP-triggered function.
/MG

A: Assuming you are using the SQL Query input option, you should be able to use the LIMIT clause along with ORDER BY to set a maximum number of records returned. You may also want to take a look at the metrics on your Cosmos account, just in case the maxing out your available RUs causing the bottleneck.


text:
Q: How to use kotlin libraries in programming? I want to add libraries (like koma , kUnits )to my kotlin program in intellij idea but not getting any way where to add their dependencies. I am unable to find gradle file in my program

A: As the link mentioned in the @Aman Gautam's answer is broken, this is the alternative answer. Just run the code snippet and see the web-page:

Kotlin with Gradle

Table of Contents

Why Kotlin and Gradle

Get Started

Building with Gradle

Build

Gradle Run

Passing Arguments

Using External Libraries

JSON

Why Kotlin and Gradle

Compared with clojure and scala, kotlin is much lighter, as I'm going
to write some android apps, it does matter. I've also tried mirah, but
kotlin seems more promising.

Comming from the groovy world, Gradle has now become the de facto
build tool for android development. I have very little experience with
ant and maven, but gradle is more succinct and declarative.

Get Started

Gradle does have some project templates included, but very limited
compared to lein. A list of templates can be get with gradle help
--task :init, groovy and scala are included, but not kotlin. Just use
the java-library template:

gradle init --type java-library

this will generate a bunch of files:

.
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   └── java
    │       └── Library.java
    └── test
        └── java
            └── LibraryTest.java

7 directories, 8 files

run git init, add a simple .gitignore

.gradle
/build

It is said that the gradle stuff(gradlew, gradle/wrapper) should
be included, so that the project can be build with the exact version
of gradle in the future.

Building with Gradle

Modify build.gradle, add dependencies for kotlin:

apply plugin: 'kotlin'

buildscript {
  ext.kotlin_version = '0.10.195'
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}
dependencies {
    compile 'org.slf4j:slf4j-api:1.7.7'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    testCompile 'junit:junit:4.12'
}

Build

Create the directory to put kotlin source:

mkdir -p src/main/kotlin
touch src/main/kotlin/Main.kt

add a simple Main.kt:

fun main(args: Array<String>) {
    println("kotlin!")
}

now build

gradle build

Gradle Run

It would be sweet to run the program directly, and there is a
application plugin for that purpose. Add two more lines to
build.gradle, to apply the plugin and specify the entry class:

apply plugin: 'application'

mainClassName = "_DefaultPackage"

Now the project can be build and launched with one single command

gradle run

Passing Arguments

It turns out to be a little tricky, but here is what I end up with:

gradle run -Dexec.args="placeholder arg1 arg2"

A run block is needed in build.gradle:

run {
  args System.getProperty("exec.args").split()
}

Update Main.kt to use the args:

fun fib(n: Int):Int {
    return when (n) {
           0,1 -> 1
           else -> fib(n - 1) + fib(n - 2)
    }
}

fun main(args: Array<String>) {
    if (args.size() > 1) {
        println(fib(args[1].toInt()))
    } else {
        println("i need a number")
    }
}

Using External Libraries

Declear your dependencies in build.gradle:

dependencies {
    ...
    compile 'com.github.kevinsawicki:http-request:6.0'
    ...
}

Import, nothing fancy:

import com.github.kevinsawicki.http.HttpRequest

fun main(args: Array<String>) {
    val url:String = "https://hacker-news.firebaseio.com/v0/topstories.json"
    val response:String = HttpRequest.get(url).body()
    println(response)
}

JSON

dependencies {
    ...
    compile 'com.fasterxml.jackson.module:jackson-module-kotlin:2.5.1'
    ...
}

import com.github.kevinsawicki.http.HttpRequest
import com.fasterxml.jackson.module.kotlin.*

fun main(args: Array<String>) {
    val url:String = "https://hacker-news.firebaseio.com/v0/topstories.json"
    val response:String = HttpRequest.get(url).body()
    val mapper = jacksonObjectMapper()
    val ids:Array<Int> = mapper.readValue(response)
    for (id in ids) {
        println(id)
    }
}

A: I have found the answer myself.Head over to the following link for full detail description on 'how to use gradle with koltin'.
http://zweifisch.github.io/kotlin-with-gradle.html


text:
Q: How may I popup a MsgBox error when the user tries to perform an action (for example delete)? I've code with a delete button that deletes a row according to the user's choice.
I want to restrict the user from deleting a specific row or Range (equivalent to the line).
Private Sub Deletar_Click()
    Dim answer As VbMsgBoxResult, tbl As ListObject, error As VbMsgBoxResult
    answer = MsgBox("You want to proceed with the delete?", vbYesNo + vbQuestion, "Excluir Linha"):
    If answer = vbYes & Range.Row(2).Select Then
       error = Msgbox("You cant delete this row",vbCritical+vbRetryCancel,"Error")
    If answer <> vbYes Then Exit Sub

    Set tbl = MySheet.ListObjects("DataTable")
    tbl.DataBodyRange.Rows(Range.Row - tbl.DataBodyRange.Row).Delete
End Sub

I end up getting the following error:
Wrong number or arguments or...

A: EDIT: split out the logic for figuring out what listobject row is selected.
Maybe like this:
Sub Deletar_Click()
    Dim rw As ListRow

    Set rw = SelectedListRow(Selection, mySheet.ListObjects("DataTable"))

    If rw Is Nothing Then     'make sure a row in the data table has been selected
        MsgBox "First select one or more cells in the data row to be deleted"
    ElseIf rw.Index = 1 Then  'first row can't be deleted
        MsgBox "The first row cannot be deleted", vbExclamation
    Else
        'OK to deelte on user confirmation
        If MsgBox("Delete selected row?", vbYesNo + vbQuestion, "Excluir Linha") = vbYes Then
            rw.Delete
        End If
    End If
End Sub

'Given a Range and a ListObject, return a ListRow corresponding to `rng` (or Nothing
'   if rng is noth within the listobject's DatabodyRange
Function SelectedListRow(rng As Range, tbl As ListObject) As ListRow
    Dim sel As Range, rowIndex As Long
    If Not rng.Parent Is tbl.Parent Then Exit Function 'on different sheets...
    Set sel = Application.Intersect(rng.Cells(1), tbl.DataBodyRange) 'only check top-left cell of `rng`
    If Not sel Is Nothing Then
        rowIndex = 1 + (sel.Row - tbl.DataBodyRange.Cells(1).Row) 'which table row is selected?
        Set SelectedListRow = tbl.ListRows(rowIndex)
    End If
End Function


text:
Q: API resolved without sending a response for /api/addproducts, this may result in stalled requests API resolved without sending a response for /api/addproducts, this may result in stalled requests.
This is add product API  and below is my code for that API
I Have debugged it using the console . Below is my code I am struggling to find error but could not succeed to do so.

import Product from "../../models/Products"
import dbConnect from "../../middlewear/db"

export default async function handler (req, res){

    const {method}=req
    dbConnect()
    if(method==='POST'){
        try {
        let product=await  new Product(req.body)
        savedProduct=await product.save()
        return res.status(200).json({ message: "success" });

        } catch (error) {
            res.status(500).json({status:"Internal server error", message:error.message})

        }
    }

    }

THIS IS a DATABASE Connection to NEXT JS application
import mongoose from "mongoose"

const MONGNODB_URL=process.env.MONGNODB_URL

if(!MONGNODB_URL){
    throw new Error(
        "Please define mongo URI inside .env.local"   )
}
let cashed=global.momgoose

if(!cashed){
    cashed=global.mongoose={conn:null,promise:null}
}

async function connectDB(){
    if(cashed.conn){
        return cashed.conn}

    if(!cashed.promise){
    const opts={
        bufferCommands:false
    }

    cashed.promise= await mongoose.connect(MONGNODB_URL,opts).then((mongoose)=>{
        return mongoose
})

}
cashed.conn=await cashed.promise
return cashed.conn
}

export default connectDB

A: The problem got solved by following code

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction

import Product from "../../models/Products"
import dbConnect from "../../middlewear/db"

export default async function handler (req, res){

    const {method}=req
    dbConnect()
    if(method==='POST'){

        let product=await new Product(req.body)
        let savedProduct=await product.save()
        return res.status(200).json({ message: "success",savedProduct });

    }else{
        res.status(424).json({status:"Product not added"})
    }
    }


text:
Q: Arcpy ArcMap mosaic use different raster whenever nodata value I am using ArcPy in ArcMap and have multiple Rasters (Landsat imagery) taken from a given area (Image 1).

My final goal is to create a cloud free image of the complete area. Since the Rasters contain clouds, I first used the BQA given for the data and classified clouds, background, etc for each Raster as nodata. I am doing this to later replace these nodata entries with the entries of other Rasters taken of the same area. When I merge my Rasters with (composites is a list of Rasters)
arcpy.MosaicToNewRaster_management(composites, os.getcwd(), mosaic_name, number_of_bands = number_bands, mosaic_method = 'MAXIMUM')

I obtain a merged image that uses the pixel values of the underlying Raster if its classified as nodata in the above Raster (Image 2).

This is exactly the behavior I want to achieve. However, the disadvantage of this approach is that the code is not doing any color balancing, which I require. When I create a mosaic separately and do color balancing
mosaic = arcpy.CreateMosaicDataset_management("C:/Users/georg/OneDrive/Dokumente/ArcGIS/Default.gdb",  mosaic_name, arcpy.Describe(composites[0]).spatialReference,  num_bands = number_bands)
arcpy.SetRasterProperties_management(mosaic,nodata="1 0;2 0;3 0;4 0;5 0;6 0;7 0")
arcpy.DefineMosaicDatasetNoData_management(mosaic, number_bands, "ALL_BANDS '0'")
arcpy.SetMosaicDatasetProperties_management(mosaic, mosaic_operator='MAX')
arcpy.AddRastersToMosaicDataset_management(mosaic, "Raster Dataset", composites)
arcpy.BuildFootprints_management(mosaic)
arcpy.BuildSeamlines_management(mosaic)
arcpy.BuildPyramidsandStatistics_management(mosaic)
arcpy.ColorBalanceMosaicDataset_management(mosaic, "DODGING", "COLOR_GRID")
arcpy.MosaicToNewRaster_management(mosaic, os.getcwd(), mosaic_name+".tif", number_of_bands = number_bands, mosaic_method = 'MAXIMUM')

the final image classifies a pixel as nodata if the top Raster is nodata at this Pixel (Image 3), whereas it should be using a Pixel from the underlying Raster in such a case. How do I fix this problem? I tried many different settings, but none did work.

A: I am not sure why, but this made me solve my problem:
arcpy.BuildSeamlines_management(mosaic, computation_method = 'COPY_FOOTPRINT')

i.e. I changed the computation method of the seamlines to 'COPY_FOOTPRINT'. I think the default computation method created mostly non-overlapping seamlines and then relied for each pixel on a single raster. However, this is not the behavior I wanted, since I wanted to deliberately use my mosaic method to determine what pixels to use.
Bottom-line: building seamlines may conflict with the mosaic method chosen.