Q: Java AES decryption error, encryption is working fine I have a question about using Decrypt in AES.  I wrote the same program that encrypts the text.
Here is my Decrypt class. (I use a 16 byte key).
public static byte[] decryptAES(String message) throws Exception
{
String secretKey = "JohnIsAwesome!1!";
SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(message.getBytes());
}

Here is my main.  The encrypt is working perfectly.
public static void main (String[] args) throws Exception
{
    String text = "MySuperSecretPassword!";
    //Ecrypt the Text, then print it out in an array
    String encryptText = Arrays.toString(encryptAES(text));
    System.out.println("Encrypted Message"+ encryptText);

    //Decrypt the Text, then print it out in an array
    String decryptText = Arrays.toString(decryptAES(text1));
    System.out.println("Decrypted Message"+ decryptText);

}

Encrypt output:
Encrypted Message[16, 69, 84, 118, 68, -36, -67, 125, -86, -106, -4, 24, -59, -77, -41, -32, -37, 104, -44, -42, 112, 87, 87, 101, 28, 99, 60, -27, 34, -88, -17, -114]
If anyone has any ideas why the decryption would not work, It would be greatly appreciated.  I've been banging my head against the wall on this one.
Thank you
Sorry, forgot to add my Encrypt class here as well.
public static byte[] encryptAES(String message) throws Exception
{
    String secretKey = "JohnIsAwesome!1!";
    SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return cipher.doFinal(message.getBytes());
}

A: Arrays.toString(byte[] a) "Returns a string representation of the contents of the specified array." It does not convert a byte array to a String. Instead try using:
new String(decryptAES(text1), "UTF-8");


Q: Mocha: how do I use the assert.reject in typescript with promise in params? how do I use the assert.reject in typescript with promise in params?
here is my code:
import { assert } from "chai";
import { suite, test, timeout, slow } from "mocha-typescript";
import "mocha";
import { car } from "./Car"; // module that run your function

let carVIN: string = "1234567890"; // this car has four wheel;

@suit
export class CarTest() {
  @test
  public async oneWheelsCar() {
      const wheels = await car.findWheelsByCarId(carVIN);
      assert.isRejected(wheels, "Expected to have four wheels");
  }

}

My question is how do I make my carId function to run like promise because my problem is assert.isRejected run early before the carId error return back.
I tried this below:
assert.throws(carId, Error, "Expected to be error ");

and I also try to use try-catch to wrap my function:
import { assert } from "chai";
import { suite, test, timeout, slow } from "mocha-typescript";
import "mocha";
import { car } from "./Car"; // module that run your function

let carVIN: string = "1234567890"; // this car has four wheel;

@suit
export class CarTest() {
  @test
  public async oneWheelsCar() {
      try {
        const wheels = await car.findWheelsByCarId(carVIN);
        assert.isNotString(wheels, "Expected to be error but return four wheels");
      } catch (error) {
        assert.throws(error, Error, "Expected to be error ");
      }

    }

}

I had tried to use chai-as-promise, but the example is not that clear in the their github repo.
Visit https://github.com/domenic/chai-as-promised#readme
Source: https://www.npmjs.com/package/chai-as-promised

A: Problem is await. await resolves promise to actual value or throws exception (simplified view).
So, after this line:
const wheels = await car.findWheelsByCarId(carVIN);

wheels is not a promise, but actual wheel (or whatever).
Change it to:
const wheelsPromise = car.findWheelsByCarId(carVIN); // no await

And then this:
assert.isRejected(wheelsPromise, "Expected to have four wheels");

Should work as expected.


Q: Sorting an ObservableCollection after editing a property of an item I'm trying to bind an ObservableCollection<T> to a DataGrid in WPF.
Below the DataGrid, there are fields to edit the currently selected item from the DataGridlike so:

So the generic T of the ObservableCollection<T> has the following properties:
- Title (Überschrift)
- Description (Beschreibung)
- Path (Pfad)
and it also has a property Reihenfolge which means Order.
With the yellow arrows, I want to be able to modify the order of the entries.
Unfortunately, the ObservableCollection doesn't have an OrderBy-method...

I've tried the following:
In XAML I have defined a CollectionViewSource like this:
<CollectionViewSource Source="{Binding Bilder}" x:Key="Pictures">
    <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="Reihenfolge" />
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

And I have binded the DataGrid to this CollectionViewSource
<DataGrid Grid.Column="0" Grid.Row="1"
          Name="PictureDataGrid"
          ItemsSource="{Binding Source={StaticResource Pictures}}"
          AutoGenerateColumns="False"
          IsReadOnly="True"
          CanUserAddRows="false"
          SelectedItem="{Binding SelectedBild}"
          HorizontalAlignment="Stretch"
          VerticalAlignment="Stretch">
 ...

In the ViewModel, I have these properties:
public ObservableCollection<BildNotifiableModel> Bilder { get; set; }
public BildNotifiableModel SelectedBild { get; set; }

and two methods which are called with DelegateCommands that update the order
 private void MoveSeiteUp()
 {
     const int smallestReihenfolge = 1;
     if (this.SelectedBild.Reihenfolge > smallestReihenfolge) {
            var bildToSwapReihenfolgeWith = this.Bilder.Single(b => b.Reihenfolge == this.SelectedBild.Reihenfolge - 1);
            this.SelectedBild.Reihenfolge--;
            bildToSwapReihenfolgeWith.Reihenfolge++;

            RaisePropertyChanged(nameof(this.Bilder));
        }
    }

    private void MoveSeiteDown()
    {
        if (this.SelectedBild.Reihenfolge < MaxAllowedImages) {
            var bildToSwapReihenfolgeWith = this.Bilder.Single(b => b.Reihenfolge == this.SelectedBild.Reihenfolge + 1);
            this.SelectedBild.Reihenfolge++;
            bildToSwapReihenfolgeWith.Reihenfolge--;

            RaisePropertyChanged(nameof(this.Bilder));
        }
    }

The order gets updated correctly, but unfortunately, the view doesn't reflect the changes... only after closing and reopening the view, the entries in the DataGrid are in the correct order.

*

*What am I doing wrong here?

*How can I make the DataGrid update, when changing the order?

Thanks in advance

A: I think the problem is that the CollectionView doesn't listen for the PropertyChanged-Events from its elements and also RaisePropertyChanged(nameof(this.Bilder)); dosen't work because the CollectionView is not really changed.
I would recomend to create the CollectionView in code via CollectionViewSource.GetDefaultView(list). So you can control the CollectionView from your model and call ICollectionView.Refresh if needed.

A: In your Methods, create a new Collection and add it to "Bilder". Just raising the PropertyChanged will execute an evaluation for referential equality. If it is the same - which it will be, if you just move items inside around - it will not update the DataGrid.
If you are not using the ObservableCollections attributes, like automatically updates, when items are added or removed, you might also change it to a "normal" List.
private void MoveSeiteUp()
{
 const int smallestReihenfolge = 1;
 if (this.SelectedBild.Reihenfolge > smallestReihenfolge) {
        var bildToSwapReihenfolgeWith = this.Bilder.Single(b => b.Reihenfolge == this.SelectedBild.Reihenfolge - 1);
        this.SelectedBild.Reihenfolge--;
        bildToSwapReihenfolgeWith.Reihenfolge++;

        this.Bilder = new ObservableCollection<BildNotifiableModel> (this.Bilder);

        RaisePropertyChanged(nameof(this.Bilder));
    }
}

private void MoveSeiteDown()
{
    if (this.SelectedBild.Reihenfolge < MaxAllowedImages) {
        var bildToSwapReihenfolgeWith = this.Bilder.Single(b => b.Reihenfolge == this.SelectedBild.Reihenfolge + 1);
        this.SelectedBild.Reihenfolge++;
        bildToSwapReihenfolgeWith.Reihenfolge--;

        this.Bilder = new ObservableCollection<BildNotifiableModel> (this.Bilder);

        RaisePropertyChanged(nameof(this.Bilder));
    }
}


Q: When does a double become NaN? I am trying to understand which circumstances can cause a double to become NaN.
For instance, 0/0 is nan. This is also stated in the official Documentation.
https://learn.microsoft.com/en-us/dotnet/api/system.double.nan?view=net-6.0
However, my debug code indicates that the division is not by 0:
public class StandardDeviation
{
    public StandardDeviation()
    {
        Clear();
    }
    private double M { get; set; }
    private double S { get; set; }
    private uint Iteration { get; set; }
    public double Value
    {
        get
        {
            return Math.Sqrt(S / (Iteration - 2));
        }

    }
    public void AddValue(double value)
    {
        if (double.IsNaN(value))
        {
            throw new ArgumentException("value IS nan!");
        }
        double tmpM = M;
        M += (value - tmpM) / Iteration;
        S += (value - tmpM) * (value - M);
        Iteration++;
        if (double.IsNaN(M))
        {
            Console.WriteLine($"\nNAN EXCEPTION!!! divide by: {Iteration}");
Console.WriteLine($"\nNAN EXCEPTION!!! tmpM: {tmpM}");
            throw new ArgumentException("m IS nan!");
        }
    }
    public void Clear()
    {
        M = 0.0;
        S = 0.0;
        Iteration = 1;
    }
}

console message:
NAN EXCEPTION!!! divide by: 3
NAN EXCEPTION!!! tmpM: ∞

The issue primairly seems to be prevalent in release configuration, which makes it hard to debug.
Whenever the exception is thrown, Iteration = 3.


Q: reduce, reduceByKey, reduceGroups in Spark or Flink reduce: function takes accumulated value and next value to find some aggregation.
reduceByKey: is also the same operation with specified key.
reduceGroups: is apply specified operation to the grouped data.
I don't know how memory managed for these operations. For example, how data is taken while using reduce function(e.g all data loaded to the memory?)? I want to know how data is managed for reduce operations. I also want to know what is the difference between these operations according to the data management.

A: Reduce is one of the cheapest operations in Spark,since that the only thing it does is actually grouping similar data to the same node.The only cost of a reduce operation is the reading of the tuple and a decision of where it should be grouped.
This means that the simple reduce,in contrast to the reduceByKey or reduceGroups is more expensive because Spark does not know how to make the grouping and searches for correlations among tuples.
Reduce can also ignore a tuple if it does not meet any requirement.


Q: Error making/compiling objective C file Today I had my first lesson in Objective_C, it was about how to create "HELLO WORLD". After I downloaded the compiler and wrote the program I had to run it through the "shell" ,as stated in the tutorial, using the command "make" but i receive "No target specified and no makefile found. stop" error
To note, I program objectivec under windows OS
main.m Code:
//
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"***Sweet tutos***\n");
NSLog(@"***Hello World!***\n");//This will output Hello World!

[pool release];
return 0;

}
GNU makfile:
 # This script was developed for SweetTutos Tutorials
 # www.sweettutos.wordpress.com
 #
 include $(GNUSTEP_MAKEFILES)/common.make
 # make a simple program in Objective-C, call it SweetTutos
 TOOL_NAME = SweetTutos
 # The implementation Objective-C file which is going to be compiled
 SweetTutos_OBJC_FILES = main.m
 # Header files of your project
 #SweetTutos_HEADER_FILES = xxx.h //here goes all header files (.h). For the moment,
 on n'en a pas.
 # Define compilation flags
 ADDITIONAL_CPPFLAGS = -Wall -Wno-import
 # Include rules for creating a command line tool for Objective-C
 include $(GNUSTEP_MAKEFILES)/tool.make

A: "no makefile found" usually means you have no file named literally GNUmakefile, makefile or Makefile in the current directory (or the directory pointed at if you use -C).
In the Makefile you need to specify at least one rule so that make can do something. The first rule in the file (sequentially, not chronologically) becomes the default rule, so you don't actually have to specify a target like the error message indicates.


Q: Putting Submit button at the bottom of the form
I want the submit button to be at the bottom of the form. I have tried using
,
,
,
 and . So far the only solution I have come up with is to repeat
 multiple times which is a messy solution and one that is only compatible on laptops the same size as mine.
 <form method="post" action="">
      {% csrf_token %}

      {% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}

{# Include the visible fields #}
{% for field in form.visible_fields %}

        {{ field.errors }}
        {{ field.label_tag }}

        {{ field }}

{% endfor %}

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

    </form>

Update
I tried Gumbos suggestion (CSS How to place a submit button on a new line?). But there is something about the map which is making the submit button act strangely. For testing purposes I created a submit button after every field. Gumbos suggestion worked fine for text boxes and list boxes. But not maps.

{% extends "blog/base.html" %}

{% block content %}

{% load crispy_forms_tags %}

{{ form.media }}

    <form method="post" action="">
        {% csrf_token %}
        {% for hidden in form.hidden_fields %}
        {{ hidden }}
        {% endfor %}

        {# Include the visible fields #}
        {% for field in form.visible_fields %}

        {{ field.errors }}
        {{ field.label_tag }}

        {{ field }}
        <input type="submit" value="Submit">
        {% endfor %}
  </form>

{% endblock content %}

A: I think you need to remove the float and change br into div
<form method="post" action="">
  {% csrf_token %}

  {% for hidden in form.hidden_fields %}
  {{ hidden }}
  {% endfor %}

    {# Include the visible fields #}
    {% for field in form.visible_fields %}

      {{ field.errors }}
      {{ field.label_tag }}

    {{ field }}

    {% endfor %}

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

</form>

A: Check out this post Overwrite float:left property in span for the answer.
With Bens help I was able to overwrite some of the default CSS.


Q: timestamp in milliseconds and date range - elasticsearch query string I have a timstamp in milliseconds, like 1645825932144
I'd like to make a date range query with elastic search query string for being able to get all records whom timestamp is in the last 24h:
timestamp:[now-24h TO now]
This does not work as timestamp is in milliseconds and now produces strings like 2001-01-01 13:00:00
Is it possible to achieve this with a cast or something?
I read about range queries and date math, but did not find anything.

A: It's easy to compute the timestamp in milliseconds for now and now-24h so why not do it in your application logic and build the query out of those values?
For instance (in JS),
const now = new Date().getTime();
const now24h = now - 86400000;
const query = `timestamp:[${now24h} TO ${now}]`;

query would contain the following value:
timestamp:[1647785319578 TO 1647871719578]

UPDATE:
PS: I might have misunderstood the initial need, but I'm leaving the above answer as it might help others.
What you need to do in your case is to change your mapping so that your date field accepts both formats (normal date and timestamp), like this:
PUT your-index/_mapping
{
    "properties": {
      "timestamp": {
        "type": "date",
        "format": "date_optional_time||epoch_millis"
      }
    }
}

Then you'll be able to query like this by mix and matching timestamps and date math:
GET test/_search?q=timestamp:[now-24h TO 1645825932144]

and also like this:
GET test/_search?q=timestamp:[1645825932144 TO now]


Q: How to integrate firebase/angularfire with Nx I am try to use firebase (angularfire) with Angular/Nx.
I found the plugin @nxtend/firebase.
https://nxtend.dev/docs/firebase/getting-started/
When trying to add it via ng add @nxtend/firebase I get the following error:
An unhandled exception occurred: Schematic "ng-add" not found in collection "@nxtend/firebase".
The next command gives another error: nx generate @nxtend/firebase:init
Error:
Unable to resolve @nxtend/firebase:init.
Cannot find generator 'init' in ....\node_modules@nxtend\firebase\collection.json.
I am using @nrwl/workspace": "12.9.0" - and Angular 12.x
Now my Questions:

*

*How to fix that?

*Can it be that @nxtend/firebase": "^11.1.2" ist not compatible with Angular 12.x?

And most important:
3. Ay suggestions how to integrate firebase/angularfire with Nx? Because unfortunatelly this seems to be a complicated task...

A: I already successfully setup nx + angular + firebase. (ps. with only one app in nx monorepo)
details and pictures can be found here:
https://blog-host-d6b29.web.app/2022/11/27/nx-angular-fire.html
I suggest you also try to setup a new nx + angular workspace, walk through my steps and see how it works.
--
to work with angular & firebase, I suggest using The official Angular library for Firebase "@angular/fire".
https://github.com/angular/angularfire


Q: pyspark -- an error appears only in IPython, but not in vanila python If I start pyspark by typing /usr/bin/pyspark in the console, the following sample code runs without any error. However, if I use it with IPython, either by invoking
$IPYTHON_OPTS="notebook" /usr/bin/pyspark # notebook

or by
$IPYTHON=1 /usr/bin/pyspark

then an exception is raised.
This is the code:
from pyspark import SparkContext,SparkConf
from pyspark import SQLContext
from pyspark.sql.types import *
# sc is a SparkContex object created when pyspark is invoked
sqc = SQLContext(sc)

And this is the error message:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-f0bbbc9cdb50> in <module>()
      3 from pyspark.sql.types import *
      4 # sc is a SparkContex object created when pyspark is invoked
----> 5 sqc = SQLContext(sc)

/opt/cloudera/parcels/CDH-5.4.2-1.cdh5.4.2.p0.2/lib/spark/python/pyspark/sql/context.py in __init__(self, sparkContext, sqlContext)
     91         """
     92         self._sc = sparkContext
---> 93         self._jsc = self._sc._jsc
     94         self._jvm = self._sc._jvm
     95         self._scala_SQLContext = sqlContext

AttributeError: 'module' object has no attribute '_jsc'

What causes this error and how can I fix it?
UPDATE
It turns out that the problem exists if I use Anaconda python distribution for Linux:
    ~$ ipython --version
    4.0.0
    ~$ python --version
    Python 2.7.10 :: Anaconda 2.3.0 (64-bit)

But, if I disable the anaconda distribution and use Python that comes with the system, everything works well
    $ ipython --version
    4.0.0
    $ python --version
    Python 2.7.3
    $ cat /etc/issue
    Debian GNU/Linux 7 \n \l

So, the problem is with Anaconda, but still don't know what the problem is

A: not sure about the specific error, as it should have the same issue for vanilla and anaconda spark, however, a couple of things you can check:
Make sure the same python version is installed on both your drivers and workers. Different versions can cause issues with serialization.
IPYTHON_OPTS is generally deprecated. Instead I define the following environment variables:
# tells pyspark to use notebook
export PYSPARK_DRIVER_PYTHON_OPS="notebook"
# tells pyspark to use the jupyter executable instead of python. In your case you might want this to be ipython instead
export PYSPARK_DRIVER_PYTHON=/opt/anaconda2/bin/jupyter
# tells pyspark where the python executable is on the executors. It MUST be the same version of python (preferably with the same packages if you are using them in a UDF or similar
export PYSPARK_PYTHON=/opt/anaconda2/bin/python

Of course I see you are not adding a master to the command line so this would run spark locally if you haven't changed you spark defaults (i.e. no workers).


Q: Unable to click on a link inside textview message on android mobile app-Appium Anyone help on this....

code

I want to access the hyperlink within my text as depicted in the pic :

Notes:
I tried directly clicking in text by using id but didnt worked.
I tried using scrollTo() but still it didnt worked.
I tried with linkText even that didnt worked.

A: clickable is set to false. You have to set it true in xml file and later on handle onClick event in your activity class

A: image  only you need to handle onclick listener in Android java file where you make reference the text of your xml like
 TextView mytext=(TextView)findviewbyid(R.id.ref of your TextView);
 mytext.setOnClickList();


Q: Using ViewFlipper with onclick to switch views I'm using ViewFLipper with Random.nextInt(). to change layouts onClick (Button). Now I have 3 xml layouts. 1_view.xml 2_view.xml 3_view.xml. Starting from 1_view.xml I have a button there. When button clicked I should get a random layout. it works. But the problem is now, sometimes I get the same layout (1_view.xml). When a user clicks a button on (1_view.xml), I want them to go to the layouts I have left (2_view.xml and 3_view.xml).
Codes
Main.xml

 <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dip" >

        <TextView
            android:id="@+id/TVLeft"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_gravity="left|top"
            android:text="0"
            android:textColor="#4CB848"
            android:textSize="40sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/TVRight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/TVLeft"
            android:gravity="right"
            android:text="0"
            android:textColor="#FF0000"
            android:textSize="40sp"
            android:textStyle="bold" />
    </RelativeLayout>

    <ViewFlipper
        android:id="@+id/viewFlipper1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <include
            android:id="@+id/1_View"
            layout="@layout/1_view" />

        <include
            android:id="@+id/2_View"
            layout="@layout/2_view" />

        <include
            android:id="@+id/3_View"
            layout="@layout/3_view" />
    </ViewFlipper>
</LinearLayout>

Main.java
        // FlipperView
        MyViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper1);

        TVRight = (TextView) findViewById(R.id.TVRight);
        TVLeft = (TextView) findViewById(R.id.TVLeft);

        // 1_view.xml
        Q1_btn1 = (Button) findViewById(R.id.btn_1);
        Q1_btn2 = (Button) findViewById(R.id.btn_2);
        Q1_btn3 = (Button) findViewById(R.id.btn_3);
        Q1_btn4 = (Button) findViewById(R.id.btn_4);

        Q1_btn1.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Wrongnum++;
                WrongResult.setText(Integer.toString(Wrongnum));

            }

        });

        Q1_btn2.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Rightnum++;
                RightResult.setText(Integer.toString(Rightnum));

                Random RandomView = new Random();
                MyViewFlipper.setDisplayedChild(RandomView.nextInt(3));

            }
        });
        Q1_btn3.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Wrongnum++;
                WrongResult.setText(Integer.toString(Wrongnum));

            }
        });
        Q1_btn4.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Wrongnum++;
                WrongResult.setText(Integer.toString(Wrongnum));

            }
        });

A: You can do this in your code:
 Random RandomView = new Random();
 int nextViewIndex = RandomView.nextInt(3);
 while (nextViewIndex == MyViewFlipper.getDisplayedChild()) {
     nextViewIndex = RandomView.nextInt(3);
 }
 MyViewFlipper.setDisplayedChild(nextViewIndex);

Basically just call Random.nextInt() until it doesn't match current viewFlipper's index.
To only show a viewFlipper once randomly:
// Intialize this once
List<Integer> vfIndices = new ArrayList<Integer>();
for (int i = 0; i < MyViewFlipper.getChildCount(); i++) {
   vfIndices.add(i);
}

// when button is clicked
if (vfIndices.size() == 0) {
   return; // no more view flipper to show!
}
int viewIndex = RandomView.nextInt(vfIndices.size());
MyViewFlipper.setDisplayedChild(vfIndices.get(viewIndex));
vfIndicies.remove(viewIndex);

The idea is use an ArrayList to keep track of the viewFlipper index that has not been shown. When button is clicked, pick an index randomly from this array and set the viewFlipper to. Then remove that index from the ArrayList. Next time the button is clicked, it will show one of the remaining flippers.


Q: Searching in couchdb or do river thru an elastic search I understand we create views on couchdb and then we can search. Another interesting approach is to connect couchdb with elasticsearch thru river and search in elasticsearch. I have two questions:

*

*in terms of disk space usage, will elasticsearch be more efficient?

*what would be the pros and cons of using couchdb search vs using elasticsearch on top of couchdb?

Thanks!

A: Only thing CouchDB queries can give you is the key -> value mapping. You can search the ordered dictionary, but you cannot search in the multi-dimensional data, with regular expression or even the key that contain a keyword as a substring (e.g. you have data "Mr. John Smith", and you want it to be found by the query with the keyword "John"). ElasticSearch fills the gap and provides additional indexing of the data. It is mainly useful for full-text indexing, but also supports geospatial data.

A: In terms of disk usage:

*

*https://github.com/logstash/logstash/wiki/Elasticsearch-Storage-Optimization

*http://till.klampaeckel.de/blog/archives/95-Operating-CouchDB.html
As Marcin pointed out, Elasticsearch excels in full-text-search and its flexibility of analyzer and search functionality.


Q: Banner overlay a html5 video and something happen when click on play i'm searching for a long time a solution for my necessities but i can't find anything help me.
Well, i have a html5 player with a video (with exception, if not support, use flash) i wanna insert a banner into this video at a certain time and for a certain duration, full screen and normal size.
what javascript code should i use?
the html should be easy:
div
 banner (hidden)
  video
/div
what javascript code should i use?
2° Question: i always have this player, i want that when the user click for the first time on play, happen something, like open an full size image, or open a video, ecc.
I not found so much on internet about advertising and coding, and i'm not very good with javascript.
So, i hope some one there can help me, thank you.

A: *

*Display your ad image on page load and ask user to click to play video.

*Load your video with a proper player plugin

*Start playing video

*Continuously check video duration using player API

*At a specific duration like (15th second) display and overlay div on top of your video

*Done.

Also if you're not that good with javascript probably it's better to start with something less complicated.


Q: Thin Controllers in Laravel 4 I am trying to work out the 'best' way of structuring my controllers/models in a new Laravel 4 app.
Obviously I want to keep the controllers thin and lightweight. So I want to work with Repos/Services to separate things, however I don't really know how to implement this in Laravel 4. Laravel 3 gave us some idea of how this should work, but no samples.
Has any one figured out the neatest way to do this, or have any sample code I could take a peek at?

A: I agree on the fact that it isn't very clear where to store these classes in Laravel 4.
A simple solution would be creating repositories/services folders in your main app/ folder and updating your main composer.json file to have them autoloaded:
{
    "require": {
        "laravel/framework": "4.0.*"
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/tests/TestCase.php",
            "app/repositories",
            "app/services"
        ]
    },
    "minimum-stability": "dev"
}

Note: everytime you create a new class you have to run composer dump-autoload.
In case of repositories, you can have Laravel inject them into your controllers automatically. I find this a good screencast on this subject.

A: I found this collection of tutorials to be a great introduction on the proper place to store your custom service providers and other files that you want to inject into your project:

*

*http://fideloper.com/laravel-4-application-setup-app-library-autoloading

*http://fideloper.com/laravel-4-where-to-put-bindings

*http://fideloper.com/error-handling-with-content-negotiation
These tutorials come from this collection:
http://fideloper.com/tag/laravel-4

A: The first thing that I do when I get a fresh install of Laravel is:

*

*Remove the "models" folder

*Create a src folder

*Under the src, create a Application folder (or the name of the app)

*On Application folder, create Entities, Repositories, Services and Tests

So, in this case your namespace will be Application\Entities, Application\Repositories and Application\Services
In composer.json:
{
    "require": {
        "laravel/framework": "4.0.*"
    },
    "autoload": {
        "psr-0": {
            "Application": "app/src/"
        },
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/database/migrations",
        ]
    },
    "minimum-stability": "dev"
}

To each one of those you'll need to create the classes and a service provider to bind a repository to an entity.
Here is a tutorial explaining how to create the repositories:
http://culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories/
Anyway, I'm still looking for the best architecture. If anyone has a better idea, I'll be glad to hear it!


Q: Table export jquery - display issue I have a table with a Header Row and a Sub-header row. The Header row has colspan of 3 for most cells.
When exporting to Excel, I cannot get this Header Row to:

*

*Show as merged cell.

*Leave blank spaces if it cannot merge.

As a result the Header row is shorter than the sub-header row.
I have tried the following, but it doesn't export the hidden cells.
Contacted
Number
Number

Is anything extra needed to make data-tableexport-display="always" work?
TL;DR, How to deal with colspan not displaying as merged cell?


Q: Changing color of HTML element using radio button I have 10 groups of radio button with two options, each group separated by a
.

Do you like to walk?

    <input type="radio" value="a" name="radgrp1"/> Yes

    <input type="radio" value="b" name="radgrp1"/> No

Would you prefer to walk without effort?

    <input type="radio" value="a" name="radgrp2"/> Yes

    <input type="radio" value="b" name="radgrp2"/> No

Then I have 10  tags that point to each group.
 Goto 1
 Goto 2

What I am looking to achieve is the moment a user clicks on "Yes" option, color of respective  tag ie Goto 1, Goto 2 etc turns green.

A: A common technique is to create a relationship between elements by using data attributes. In your case, you could put an attribute on each input/radio button that references the id of the element you want to affect.
<input type="radio" value="a" name="radgrp1" data-target="a1" /> Yes

Then using some jQuery you could do this:
$('input[type="radio"]').change(function(){
    var id = $(this).attr('data-target');
    $('#' + id).css('background-color', 'rgb(255, 255, 255)');
});

A: You may try this (assumed there is no document.body.onclick event handler other than this)
var radios = document.querySelectorAll('input[name^=radgrp]');
document.body.onclick = function(e){
    var evt = e || window.event, target = evt.target || evt.srcElement;
    if(target.name) {
        var prefix = target.name.substr(0, 6), suffix = target.name.substr(6);
        if(prefix && prefix == 'radgrp') {
            if(target.value == 'a' ) {
                document.getElementById('a' + suffix).style.color = 'green';
            }
            else {
                document.getElementById('a' + suffix).style.color = '';
            }
        }
    }
};

Put this code just before the closing  tag between

Also, you may check this for registering events using different approaches.
Update :
querySelectorAll won't work in IE-6 so you may try this alternative solution for IE-6 to work. Also, if you use jQuery (put the code in  between


Q: Tabs in the Pyqt4 Which command to use to "break" a row of tabs? I would like to have, for example, 3 tabs in one row and 3 tabs just below it. The skeleton I have referenced as tabs is:
# layout tab
tabs = qg.QTabWidget()

# Create tabs
tab1    = qg.QWidget()
tab2    = qg.QWidget()
tab3    = qg.QWidget()
tab4    = qg.QWidget()
tab5    = qg.QWidget()
tab6    = qg.QWidget()

tabs.addTab(tab1,"Properties")
tabs.addTab(tab2,"Nodes")
tabs.addTab(tab3,"Bars")
tabs.addTab(tab4,"Restrains")
tabs.addTab(tab5,"Nodal Loads")
tabs.addTab(tab6,"Dist.Loads")

Here is an example of what I want


Q: Two Layouts for row in ListView I have two layouts that are used according to product availability (available and missing) in stock. I tried to use them but without success, so I created a standard layout and change the Shape that contains the settings for each case. This is the best way to do? How can I use both in my Layouts APPLICATION?
Ps .: Remember that the ListView will not be with alternating colors (zebra style), but according to product availability.
using System;
using Android.App;
using Android.Views;
using Android.Widget;
using ServiceClass.Auvo_WebService;
using Android.Content;
using AppClass_Mobile;

public class AdapterProduct : BaseAdapter
{
    private Activity _Activity = null;

    private static   Product[] _ListOfProduct;

    public static    User _InstaceOfUser;

    public static    LayoutInflater _Inflater = null;

    private View   _View;

public AdapterProduct(Activity activity, Product[] listOfProduct)
{
    _Activity = activity;

    _ListOfProduct = listOfProduct;

    try
    {
        _Inflater = (LayoutInflater)_Activity.GetSystemService(Context.LayoutInflaterService);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}

public override View GetView(int position, View convertView, ViewGroup parent)
{
    _View = convertView;

    ViewHolderProduct holderProduct;

    try
    {
        if (_View != null)
            holderProduct = _View.Tag as ViewHolderProduct;

        else
        {
            _View = _Activity.LayoutInflater.Inflate(Resource.Layout.LayoutGenericProd, null);

            holderProduct = CriaHolder(position);
        }

        PopulaHolder(holderProduct, position);

        _View.Tag = holderProduct;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }

    return _View;
}

private void PopulaHolder(ViewHolderProduct holderProduct, int position)
{

    if (_ListOfProduct[position].ThisProductIsOk)
    {
        holderProduct.descrProd.SetBackgroundResource(Resource.Layout.ShapeRoundedCornerOut);

        holderProduct.descrProd.SetTextColor(Android.Graphics.Color.Black);
    }

    else
        holderProduct.descrProd.SetBackgroundResource(Resource.Layout.ShapeRoundedCornerIn);

    holderProduct.descrProd.Text = _ListOfProduct[position].Name;

    holderProduct.lastUpDate.Text = _ListOfProduct[position].DataProduct.ToString("HH:mm");
}

private ViewHolderProduct CriaHolder(int position)
{
    ViewHolderProduct holderProduct = new ViewHolderProduct();

    holderProduct.descrProd = _View.FindViewById<TextView>(Resource.Id.descrProd);

    holderProduct.lastUpDate = _View.FindViewById<TextView>(Resource.Id.lastUpDate);

    return holderProduct;
}

public override Java.Lang.Object GetItem(int position)
{
    return null;
}

public override long GetItemId(int position)
{
    return position;
}

public override int Count
{
    get { return _ListOfProduct.Length; }
}

public int GetCount()
{
    return _ListOfProduct.Length;
}

public void AddItem(Product product, User User)
{
    try
    {
        if (User.SerialNum == _InstaceOfUser.SerialNum)
            AddPordInList(product);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}

private void AddPordInList(Product product)
{
    Array.Resize(ref _ListOfProduct, _ListOfProduct.Length + 1);

    _ListOfProduct[GetCount() - 1] = product;

    this.NotifyDataSetChanged();
}

private class ViewHolderProduct : Java.Lang.Object
{
    public TextView  descrProd { get; set; }
    public TextView  lastUpDate { get; set; }
    public ImageView statusProd { get; set; }
}
}


Q: SignalR in windows forms SignalR is very interesting and impressive in real time web applications. Now I am doing a simple chat applciation using windows forms.
Whenever, I use ".wait()", it threw an error 'one or more errors' and while invoke the message from text box, there is an error 'start must be call before send'.
I don't know where i made mistake. I tried many of the solutions. But it doesn't work. Everything is perfect in web and console applications.
Can anyone help me?
Can you give some examples with how it works...?
I couldn't see any samples of signalR in windows forms.

A: Assuming you are trying to do a SignalR Client in Windows Forms Appliation then check this post(http://mscodingblog.blogspot.com/2012/12/testing-signalr-in-wpf-console-and.html) on how to do client side SignalR in WPF application in VB.  With similar approach I guess you could make Signalr client working in Windows Forms Application.


Q: How to translate shutter speed values into usable data? I'm gathering light statistics of EXIF data for a large collection of photos and I'm trying to find the simplest way (i.e. performance doesn't matter) of translating Exposure Time values to/from usable data. There is (as far as I can find) no standard for what values camera manufacturers might use i.e. I can't just scan the web for random images and hard-code a map.
Here are is a sample set of values I've encountered (" indicates seconds):

279", 30", 5", 3.2", 1.6", 1.3", 1", 1/1.3, 1/1.6, 1/2, 1/2.5, 1/3, 1/4, 1/5, 1/8, 1/13, 1/8000, 1/16000

Also take into consideration that I'd also like to find the average (mean) ... but it should be one of the actual shutter speeds collected and not just some arbitrary number.
EDIT:
By usable data I mean some sort of creative? numbering system that I can convert to/from for performing calculations. I thought about just multiplying everything by 1,000,000 except some fractions when divided are quite exotic.
EDIT #2:
To clarify, I'm using ExposureTime instead of ShutterSpeed because it contains photographer friendly values e.g. 1/50. ShutterSpeed is more of an approximation (which varies between camera manufacturers) and leads to values such as 1/49.

A: You want to parse them into some kind of time-duration object.
A simple way, looking at that data, would be to check wheter " or / occurs, if " parse as seconds, / parse as fraction of seconds. I don't really understand what else you could mean. For an example you'd need to specify a language--also, there might be a parser out there already.

A: Shutter speed is encoded in the EXIF metadata as an SRATIONAL, 32-bits for the numerator and 32-bits for the denominator.  Sample code that retrieves it, using System.Drawing:
        var bmp = new Bitmap(@"c:\temp\canon-ixus.jpg");
        if (bmp.PropertyIdList.Contains(37377)) {
            byte[] spencoded = bmp.GetPropertyItem(37377).Value;
            int numerator = BitConverter.ToInt32(spencoded, 0);
            int denominator = BitConverter.ToInt32(spencoded, 4);
            Console.WriteLine("Shutter speed = {0}/{1}", numerator, denominator);
        }

Output: Shutter speed = 553859/65536, sample image retrieved here.

A: It seems there are three types of string you will encounter:

*

*String with double quotes " for seconds

*String with leading 1/

*String with no special characters

I propose you simply test for these conditions and parse the value accordingly using floats:
    string[] InputSpeeds = new[] { "279\"", "30\"", "5\"", "3.2\"", "1.6\"", "1.3\"", "1\"", "1/1.3", "1/1.6", "1/2", "1/2.5", "1/3", "1/4", "1/5", "1/8", "1/13", "1/8000", "1/16000" };
    List<float> OutputSpeeds = new List<float>();

    foreach (string s in InputSpeeds)
    {
        float ConvertedSpeed;
        if (s.Contains("\""))
        {
            float.TryParse(s.Replace("\"", String.Empty), out ConvertedSpeed);
            OutputSpeeds.Add(ConvertedSpeed);
        }
        else if (s.Contains("1/"))
        {
            float.TryParse(s.Remove(0, 2), out ConvertedSpeed);
            if (ConvertedSpeed == 0)
            {
                OutputSpeeds.Add(0F);
            }
            else
            {
                OutputSpeeds.Add(1 / ConvertedSpeed);
            }
        }
        else
        {
            float.TryParse(s, out ConvertedSpeed);
            OutputSpeeds.Add(ConvertedSpeed);
        }
    }

If you want TimeSpans simply change the List<float> to List<TimeSpan> and instead of adding the float to the list, use TimeSpan.FromSeconds(ConvertedSpeed);


Q: Filter list of old bookmark URLs to exclude websites no longer in service using Vim I'm trying to learn some more about Vim and the Linux command line; the project I'm working on is:
Trying to convert a browser's export of bookmarks.html into a plain text list of URLs that still work.

*

*First, I used lynx -dump -listonly bookmarks.html > bookmarks to format the HTML to plain text:

   1. https://example.com/vim-is-cool.html
   2. https://example.com/index.html

*Used Vim to strip the numbers and leading spaces away (:% s/.\+ /)

*Used Vim to remove everything but the top level domain (:%! cut -d'/' -f1,2,3)

*Used Vim to remove duplicates with :sort u

*To test one of the links, I'd use:

curl -I https://www.example.com | grep HTTP | sed 's/HTTP\/1\.1 //g'
200 OK

Now, I'd like to:

*Check the shortlist of short URLs via the same command (I'm not sure how to iterate the same command for every line in Vim's buffer)

*Filter the file containing all full URLs based on whether cURL gets a 200 OK for the short URL (this part is also way beyond me)

*Write the remaining list of working full URLs to bookmarks4 (most likely I could handle this)

If reasonably possible, I'd like to complete all of that without scripting in shell/bash or leaving Vim.

A: This might work for you (all GNU utilities using bash):
lynx -dump -listonly bookmarks.html |
grep -o 'https\?://[^/]*' |
sort -u |
parallel -k 'curl -I -m2 {} |& grep -q "HTTP/[0-9.]\+ 200" && echo {}' >bookmarks4

Use lynx to format links.
Use grep to format urls.
Use sort to sort and remove duplicates.
Use parallel to check the urls using curl and checking its output for a 200 reply using grep. Output those urls that meet the requirements to bookmarks4.
To output the original urls, perhaps:
lynx -dump -listonly bookmarks.html |
grep http |
parallel --rpl '{url} s:.*(https?.*):$1:' \
         --rpl '{dom} s:.*(https?\://[^/]*).*:$1:' \
        'curl -m2 -I {dom} |& grep -q "HTTP/[0-9.]\+ 200" && echo {url}' |
sort -u >bookmarks4


Q: Rebase from commit I have a framework that I coded, it's into a Github repository, as the master branch. Into that branch are only the core files of the framework, so I named it the core branch.
Now into other branches, I list projects that use said core framework — I did this because I though working with branches would be easier but as I just discovered, it's not. Seriously.
So to sum up : I have a core branch, and a project branch that uses that core. Now on the project branch, I do mostly commits related to the project (added image X, modified stylesheet Y) but sometimes I modify the core, to make it better.
Now what I'd like to do, and again I thought this would be simple, is when I start working on the core more than the project, merge the changes to the core into the core branch.
There's several solution and it's all starting to confuse me, and since I would like not to mess up my core branch, how should I proceed ?
I know I can cherry pick commits and push it but I'd really like to keep the history of changes to the core files, so I've been directed to rebasing.
Problem is : if I rebase my core branch to a specific commit on the project branch, it will push all the files and stuff that have nothing to do with the core. So how do I rebase from a certain commit (and not to, which seems to be the default ?).
Here is some sort of idea of what commits on the project branch might look like :
project branch
00:12 - Added image X
00:14 - Modified stylesheet Y to have a pink background (pink is pretty)
00:16 - Modified class core.background to handle pink background
00:18 - Modified class core.string to always capitalize Pink (because it's so pretty)

How do I merge the last two commits into core branch without merging the two first one that were project-related, and by keeping history — ie. keeping those two changes to the core as two commits and not one ?

Edit : more precisions.
My core framework defines a project's folder organization and thus needs to be at the root of the project folder. That's why it's not a submodule, which would have been the dream.
Also, I tried a fork of the core, but apparently you can't fork your own projects.
If there is another way besides branches to do what I want, I'm all ears.

A: git branches don't really work like that - the branches all relate to the repository. Separating projects, or parts of projects, into separate branches isn't really the right way to go. Eventually, most branches should be merged into a release branch of some type, or discarded.

I have a core branch, and a project branch that uses that core. Now on the project branch, I do mostly commits related to the project...
I'd really like to keep the history of changes to the core files [separate]

From that, I think it sounds a lot like you have a good use case for two separate repositories, one for core-files and one for project - you want to keep the history of core and project separate. Rather than keeping them in the same repository in different branches, I'd advocate pulling the core-files into a git submodule of projects. That'd give you several advantages right off the bat:

*

*project and core history are separate.

*Using core with another project is very simple; import core as a git submodule of the otherproject.

*The history of both project and core is much, much easier to maintain, because you're not having to cherry-pick between branches anymore.


Q: API for google apis console? Is there any way how to access  https://code.google.com/apis/console with any kind of api? I need to access it with python and add subdomains to oauth2 callbacks dynamically, thanks.

A: No, there's no API to programmatically configure projects in the APIs Console.


Q: OpenAL Memory not release in iOS I used OpenAL to play sounds ,I used alGetError();  check every OpenAL functions , no errors ,after finished used OpenAL
I release the buffer、source 、 context 、 OpenAL device
I used Instrument to check the memory used , there still some memory cannot be release
// relese source buffer
alSourcei(sourceId, AL_BUFFER, 0);
alDeleteSources(1, &sourceId);
alDeleteBuffers(1, &bufferId);

//release context device
bool res = alcMakeContextCurrent( NULL );
alcDestroyContext( context );
BOOL res = alcCloseDevice( device );

the leaked memory probally when I first and second used   alGenBuffers( 1, &bufferId ); judge by the size of leakd memory,and I am not quite sure
I have setup the OpenAL Context and device before used any OpenAL functions，I used alGetError(); check every steps ,no errors
is this normal, OpenAL just cache the memory?
Anybody have any ideas? Thanks
How openAL reclaim memory?


Q: Can't customize bootstraps tab's border-top - have blank space with 100% width in absolute position Can't customize bootstrap's tabs border-top - have blank space with 100% width in absolute position after the line.
http://jsfiddle.net/Vimpil/0mmv73oh/
li.active:after {
    position: absolute;
    width: 97%;
    padding: 1px;
    top: -1px;
    content: '';
    background: #000;
    height: 4px;
}

A: This extra space is because of margin-right applied to links in Bootstrap's default styles.
You can fix this by overriding that styles or remove width and use left: 0 and right: 2px to stretch line.

jQuery(function () {
    jQuery('#myTab a:last').tab('show')
})
@import url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css');

li.active:after {
  position: absolute;
  padding: 1px;
  top: -1px;
  content: '';
  background: #000;
  height: 4px;
  right: 2px;
  left: 0;
}

Home

Profile

Messages

Settings

Home

Profile

Message

Settings


Q: Error at backbone model fetch to slim framework I'm trying to get a simple app working. It uses backbone, the slim framework and cordova. For now, all i'm trying to do is fetch user models from a MySQL database. Client side code looks like:
// Cordova is ready
function onDeviceReady()
{
    // This little code snippet prepends our root to any Ajax call.
    $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
        options.url = 'http://localhost/~nmeibergen/IBMI/www/' + options.url;
    });

    var profileView = new ProfileView();

    var Router = Backbone.Router.extend({
        routes: {
          "": "home"
        }
    });

    var router = new Router();
    router.on('route:home', function() {
        profileView.render();
    });

    Backbone.history.start();
}

var Users = Backbone.Collection.extend({
    url: 'index.php/users',
    model: User
});

var User = Backbone.Model.extend({
    urlRoot: 'index.php/users',

    defaults: {
        user_id: 1,
        name: 'Nathan',
    }
});

var ProfileView = Backbone.View.extend({

    el: '#home',

    render: function () {
        var users = new Users();
        alert('all fine');
        users.fetch();
    }
});

Whenever I simply go to http://localhost/~nmeibergen/IBMI/www/index.php/users, I get the expected JSON object:
[{"user_id":"1","name":"Jhonathan "},{"user_id":"0","name":"Nathan"}]

However when running the above code it hits the alert 'all fine', but then gives me the following error and stack trace:
TypeError: 'undefined' is not an object (evaluating 'targetModel.prototype') in backbone.js:1:689
            set        backbone.js:1:689
            success    backbone.js:1:686
            fire       jquery-1.11.1.js:3119
            fireWith   jquery-1.11.1.js:3231
            done       jquery-1.11.1.js:9275
            callback   jquery-1.11.1.js:9685

I can't seem to find out what is wrong with the code, it should be pretty basic. Thank you for looking!

A: When you say this:
var x = 6;

The var x declaration will be hoisted to the top of the current scope. However, the assignment part will not be hoisted. The result is that you're saying this:
var x;
// Everything from the top of the scope to your `var x = 6` goes here.
x = 6;

In your case, you're doing this:
var Users = Backbone.Collection.extend({
    url: 'index.php/users',
    model: User
});

var User = Backbone.Model.extend({
    urlRoot: 'index.php/users',

    defaults: {
        user_id: 1,
        name: 'Nathan',
    }
});

so var User is hoisted to the top of the scope but User = Backbone.Model.extend(...) happens after Users = Backbone.Collection.extend(...). Rearranging the code to match what really happens, we have:
var Users, User;

Users = Backbone.Collection.extend({
    //...
    model: User
});
User = Backbone.Model.extend({
    //...
});

What do you think the value of User will be when it is used in the definition of Users? User will be undefined just like any other uninitialized variable.
Demo: http://jsfiddle.net/ambiguous/xYkmc/
You need to define your User before Users:
var User = Backbone.Model.extend({
    urlRoot: 'index.php/users',

    defaults: {
        user_id: 1,
        name: 'Nathan',
    }
});

var Users = Backbone.Collection.extend({
    url: 'index.php/users',
    model: User
});

Demo: http://jsfiddle.net/ambiguous/E7V84/


Q: Turing a monolithic application into a Microservice based architecture and keeping the GIT history I'm planning to split a monolithic application into a micro service based architecture, but I want to keep the GIT history.
The monolit should be split into three micro services.
My first approach would be, copying the GIT Repository three times and removing all non domain specific parts from the new micro service which should keep the most parts of the git history alive. But I am not shure if this is the best way keeping the version control history.

A: You can use git filter-branch with the --subdirectory-filter option to filter a subdirectory of your repository and thus make the repository contain the subfolder as root directory. This is described in step 5 here, documentation here might also help. You would have to clone your repository three times and run filter-branch in each of those for a different part of your project.
Since (with said --subdirectory-filter) only subdirectories can be treated this way, you may have to rearrange your repository before. The advantage over the naive deletion of other parts is, however, that by using filter-branch you will only preseve history that concerns the actual content of your repository, and do not have any history of the parts filtered out.


Q: SignalR Hub hosted in azure misses to send message to few connections - AspNetCore.SignalR I am using Microsoft.AspNetCore.SignalR to broadcast a message to all connected clients. The Hub is hosted in Azure as App Service.
I am able to see the connected client's Connection IDs by inserting them to a table in DB.
When I hit broadcast the messages are send only to 8 out of 10 clients(Always misses few clients). The status of the missed out clients are logged as connected in DB.
My Hub Code:
public class NotificationHub : Hub
{
   public override async Task OnConnectedAsync()
   {
     ****Here I insert the connection IDs to DB with connected status***
     await Groups.AddToGroupAsync(Context.ConnectionId, "SignalRUsers_" + Context.ConnectionId);
     await base.OnConnectedAsync();
   }
}

I am calling the HubContext from outside the Hub as I need to broadcast the message on external process completion.
My Broadcaster Code:
public class SignalBroadcaster : ISignalBroadcaster
{
  private readonly IHubContext<NotificationHub> _hubContext;

  public class SignalRConnections
  {
    public string ConnectionId { get; set; }
    public DateTime ConnectedOn { get; set; }
    public string Status { get; set; }

  }

  public SignalBroadcaster(IHubContext<NotificationHub1> hubContext)
  {
    _hubContext = hubContext;
  }

  public async void BroadcastToAll(ISignal signal, TelemetryClient log)
  {
    List<SignalRConnections> lstsignalRConnections = new List<SignalRConnections>();

    try
    {
        using (SqlConnection conn = new SqlConnection(Environment.GetEnvironmentVariable("XXXXXXX")))
        {
            using (SqlCommand command = new SqlCommand("", conn))
            {
                try
                {
                    conn.Open();

                    command.CommandText = "SELECT * FROM SignalRXXXXXXX WHERE SignalRStatus = 'CONNECTED'";

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            SignalRConnections signalRConnections = new SignalRConnections()
                            {
                                ConnectionId = reader.GetString(0),
                                ConnectedOn = reader.GetDateTime(1),
                                Status = reader.GetString(2),

                            };

                            lstsignalRConnections.Add(signalRConnections);
                        }
                    }

                }
                catch (Exception ex)
                {
                    //command.CommandText = "INSERT INTO SignalRConnections (ConnectionId,ConnectedOn,SignalRStatus) VALUES ('" + Context.ConnectionId + "',GETDATE(),'DISCONNECTED')";
                    //command.ExecuteNonQuery();
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        foreach (var item in lstsignalRConnections)
        {
            try
            {
                await _hubContext.Clients.Client(item.ConnectionId).SendAsync("ReceiveMessage", signal.JobId, signal.QuantificationResult, signal.JobType);
                log.TrackTrace("SignalR sent: " + item.ConnectionId);
            }
            catch(Exception ex)
            {
                log.TrackTrace("SignalR send failed: " + item.ConnectionId + " Exception :" + ex.ToString());
            }
        }
    }
    catch (Exception ex)
    {
      Exception exp=  new Exception(String.Format(Constants.GETDATAEXCEPTIONMESSAGE, "BroadcastToAll ", ex.InnerException));
    }

}
}

Please ignore the DB connection mess here as I am doing it for testing purpose. Will refactor later.
My client Code:
connection.on("ReceiveMessage", (user, message,msg1) => {

var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg + msg1;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(err => console.log(err));

Please help me why it is missing few clients randomly. I tried searching lot of articles and help but could not find something specific to this issue.


Q: Facebook Graph for URLs - Getting the number of shares for a group of pages How can we know the sum of all Facebook shares for all URLs that start with:
http://www.guardian.co.uk/artanddesign/
There's an API method for a specific URL that is:
https://graph.facebook.com/?ids=http://www.guardian.co.uk/artanddesign/2012/feb/19/frank-gehry-new-york-interview
But I can't make it sum all the URLs that start with
http://www.guardian.co.uk/artanddesign/.
Notes:

*

*I can't iterate trough all the URL's in the directory "artsanddesign".

*Please note that the URL's above are just examples.

*I can't access insights because I don't have permissions to add a meta-tag on the root directory of the site

*Maybe the solution is using the Facebook Query Language (FQL)? How could it work?

A: I don't believe there's any way to get information for all URLs that match a certain pattern, I think you have to specify the individual URLs manually - this shouldn't be a bug problem if it's your own site, as you'll already have a database of all possible article URLs, but if you're checking someone else's site it could be difficult.


Q: cannot run the cardboard demo on iOS device I have done everything google developer website told,but the problem is Xcode still has some problems when compiling the demo project.
The problem is:ld:

/Users/Day1/Desktop/temp files/New Unity Project 3/cardboarddeomsave2/Libraries/Plugins/iOS/libvrunity.a(unity-6C9520564923BB79.o)
      does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE),
      obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64
      clang: error: linker command failed with exit code 1 (use -v to see invocation)

Another thing I have realize is that, before I compile the project, the right side of the Xcode scene has one area which is red. (libiconv.2.dylib is red) Is there any correlations here?
(By the way I have upgraded my OS X to OS X EI Captian beta and my Xcode is Xcode 7.0 beta)

A: I was reaching this problem as well and this seemed to solve my problem. (It builds for me and deploys the application, but then fails to run while still connected. If I stop the connection and restart the app so that it is only running from the phone, it runs perfectly fine.)

*

*In Xcode, select the folder view in the left pane top menu and
select your project in the left pane.

*Then in the menu above the main panel, select Build Settings.

*In Build Settings, make sure that "All" is selected (not "Basic")

*Scroll down to Build Options and set "Bitcode Enabled" to NO.


Q: WHat is the use of @Valid when @NonNull does the job for us? Code in controller -
@PostMapping("/employees")
    public Employee saveEmployee(@Valid @RequestBody Employee employee) {
        return employeeService.saveEmployee(employee);
    }

Entity Object -
@NotNull(message = "Department must not be null")
@Column(name = "department")
private String department;

Suppose I pass an item with a null department field. @NonNull will throw an exception in that case. But I have seen @Valid being used for the same purpose. Can somebody elaborate why @Valid needs to be used in addition to @NonNull?

A: If you omit the @Valid Spring will omit the validation on the web layer. Which basically means your controller, will not trigger validation. Validation is done by the RequestMappingHandlerAdapter when an @Valid(adted) annotation is found on an @ModelAttribute or @RequestBody annotated method argument.
JPA will also use a configured validator and trigger validation as well. So a validation exception will be thrown upon writing into the database.  You can disable this with spring.jpa.properties.javax.persistence.validation.mode=none in your application.properties (or the YAML equivalent). When disabling both no validation will be done. In that case you only hope is a database constraint that the column isn't allowed to be null.
So validation is still done but the location where the validation is done is different. Due to the difference you will also get a different exception.
You have to wonder do you really want to do this somewhere upon persisting the entity with the risk of having executed some complex/time consuming business logic, or quickly upon submission of the form.

A: So that the object can be validated in the Controller layer you need @Valid (or @Validated) to trigger its validation.
You can read more about this on the following online resources:

*

*https://www.baeldung.com/spring-boot-bean-validation

*https://www.baeldung.com/spring-valid-vs-validated
On which you can read:

Of course, the most relevant part is the use of the @Valid annotation.
When Spring Boot finds an argument annotated with @Valid, it
automatically bootstraps the default JSR 380 implementation —
Hibernate Validator — and validates the argument.


Q: LSTM Text Generation Applied on a Time Series with Keras I am currently working on time series prediction. LSTM for Regression with Time Steps subsection in the link gets me going pretty well. However, I want to predict into the further future, not only one-step ahead (i.e. predict every step into the future up to 30th step -- so a sequence generation), and text generation on LSTM networks sounds like the thing I am looking for.
To give an example for my ultimate goal, think of the famous Shakespeare text generators. I am trying to either feed all of Shakespeare's works and get a new Shakespeare "play," or complete an unfinished Shakespeare play (because he died without completing this particular work). Is there a way to translate this feature of sequence generation to time series, if so, can you point me towards any resources or examples.
Thank you.


Q: Using ostream overloading on pointers to objects So, I have a struct Bike, which looks like this
struct Bike {
    std::string brand;
    std::string model;
    bool is_reserved;

    friend std::ostream& operator<<(std::ostream out, const Bike& b);
};
std::ostream& operator<<(std::ostream out, const Bike& b) {
    return out
        << "| Brand: " << b.brand << '\n'
        << "| Model: " << b.model << '\n';
}

And another class BikeRentalService, which has a std::vector<Bike*> called bikes_m. This class also has a method print_available_bikes(), which is supposed to iterate over said std::vector<Bike*> and print each Bike by using the overloaded operator<< shown above. This method looks like that:
void BikeRentalService::print_available_bikes(std::ostream& out) {
    if (bikes_m.empty()) {
        out << "| None" << '\n';
    }
    else {
        for (auto bike : bikes_m) {
            if (!bike->is_reserved) {
                out << bike;
            }
        }
    }
}

The problem is that using this function just prints out the addresses of those Bike objects. Dereferencing the objects before using out << does not work either, Visual Studio says it can't reference std::basic_ostream because it is a "deleted function".
Writing the for loop as (auto *bike : bikes_m) does not change anything.

A: The rigth way to overload the ostream operator is as follows:
struct Bike {
    std::string brand;
    std::string model;
    bool is_reserved;

    friend std::ostream& operator<<(std::ostream& out, const Bike& b); // <- note passing out by reference
};
std::ostream& operator<<(std::ostream& out, const Bike& b) {
    return out
        << "| Brand: " << b.brand << '\n'
        << "| Model: " << b.model << '\n';
}

Also, as noted by @KyleKnoepfel you should change out << bike; to out << *bike; too.


Q: Why can I retrieve environment variable in one part of my code, but not another? I've stored an API token as an environment variable in my wsgi file. I'm able to retrieve it in one instance in my Django app, but not another.
I'm able to use the token successfully during a save_model operation in my admin. When I use nearly identical code in a management command I get an auth error.
My wsgi.py file:
import os
import sys
from django.core.wsgi import get_wsgi_application

os.environ['SLACK_TOKEN'] = '12344567890qazxswedcvfrtgbnhyujmkiolp'
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
application = get_wsgi_application()

Working admin.py usage:
import os
from slacker import Slacker

    def save_model(self, request, obj, form, change):
            if obj.condition == True:
                super().save_model(request, obj, form, change)
                token = os.getenv('SLACK_TOKEN')
                slack = Slacker(token)
                slack.chat.post_message('#test-channel', 'mymessage')

Not working management command usage:
import os
from slacker import Slacker

    def handle(self, *args, **options):
        try:
            #test condition
        except:
            token = os.getenv('SLACK_TOKEN')
            slack = Slacker(token)
            slack.chat.post_message('#newsflow-test', 'mymessage')

Troubleshooting indicates the env variable isn't loading -- print(token) produces None response when I run the management command or try to retrieve the token in the Django shell.

A: wsgi.py is imported by your Python application server, e.g. gunicorn. Management commands are executed directly and bypass importing wsgi.py. You should use some mechanism, e.g. django-dotenv to load environment variables from a .env file both in your manage.py script and wsgi.py application initializer.


Q: junk after document element Firefox Error Loading Content With JQuery Get I have a page (which is unfortunately behind a login system), which basically has a nav bar down the left of a list of articles, and when you click on an article, it loads the content from a .inc file stored on the server, using a provided file path.
This works fine on Google Chrome.
However, on Firefox, when the page loads, I get this weird javascript error:
"junk after document element" - When I click the error, it takes me to line 2 of the content from the first article being loaded.
Let me show you some code.
This is the last JS function which is run when the page has finished loading, and it's purpose is to load the initial article.
function initialise_family_center_page()
{
    if (current_element_id == "" || current_element_id == "family_center_general_info") //If this is the first article to be loaded
    {
        //Get the file path of the inc file to load

        var content_directory = file path....;

        jQuery.get(content_directory, function(data)
        {
            $('#family_center_main_content').html(data);    //Load the content
        });
    }
}

The content in the .inc file being loaded is as follows:

Some text

Some text

It's worth mentioning at this point, that in Chrome and Firefox, the content loads. However in firefox, because of the JS error, you can no longer use the rest of the page because the JS has stopped working.
Interesting point, which I discovered from googling the problem, is if I change the content of the file to:

Some Text

Some Text

Then the error does not appear and the page works (until you load the next content file without the  tags.
However, this is not a suitable fix because there are thousands and thousands of files.
Can anyone help?

A: I had this same problem. I had created a base page where clicking on a nav element triggered an $.ajax() fetch of an inc file that would populate the main div on the page - as follows:
$(document).ready(function(){
  // Set trigger and container variables
  var trigger = $('nav.primary ul li a'),
      container = $('#se-main');
  trigger.on('click', function(){
    // Set click target from data attribute
    target = this.target;
    $.ajax({
        url:'../inc/'+target + '.inc',
        success: function(data){
            // Load target page into container
            container.html(data);
        },
        dataType: "text" // this seems to be ignored in Firefox
    });
// snip other stuff
});

The Firefox console always logged the 'junk after document element' error unless I edited the INC files and wrapped the text in . (The page content still updated, though - so the user wasn't held up by it).
To fix this: add inc to the text/html line in the apache mime.types config file.
Find the line with
text/html                   html htm

change to
text/html                   html htm inc

Then restart apache.
That worked for me.
Default file locations:
Linux: /etc/mime.types;
WAMP: [wampdir]\bin\apache\[apacheversion]\conf\mime.types
XAMPP: [xamppdir]\apache\conf\mime.types
Where [wampdir] is wherever you installed WAMP/XAMPP, and [apacheversion] is the version of apache that WAMP is using.
This solution is no use if you don't have access to the mime.types file, or if you're running on shared hosting.
In that case - assuming that you have access to .htaccess - adding the following to .htaccess might work -
AddType text/html .html .htm .inc


Q: Can't get image from camera with intent chooser on 4.2.2 AVD I'm working on a part of my application that allows a user to select an image either from camera or from  gallery, using an Intent chooser.
It's working fine on my 2.2.1 android phone, but when i compile it on a 4.2.2 AVD it returns a null pointer error when i use the camera,
 public void onClick(View View)
{
    Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
    galleryIntent.setType("image/*");
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);

    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

    Intent chooser = new Intent(Intent.ACTION_CHOOSER);
    chooser.putExtra(Intent.EXTRA_INTENT, galleryIntent);
    chooser.putExtra(Intent.EXTRA_TITLE, "Chooser");

    Intent[] intentArray =  {cameraIntent};
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
    startActivityForResult(chooser,REQUEST_CODE);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
    {
    try
            {
            if (bitmap != null)
                {
                    bitmap.recycle();
                }

            InputStream stream = getContentResolver().openInputStream(data.getData());
            bitmap = BitmapFactory.decodeStream(stream);
            stream.close();
            imageView.setImageBitmap(bitmap);
            }

        catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }

        catch (IOException e)
            {
                e.printStackTrace();
            }
    super.onActivityResult(requestCode, resultCode, data);
    }
}

this is the error i get:
05-05 05:03:31.730: E/AndroidRuntime(820): Caused by: java.lang.NullPointerException
And it said that the problem is in this line :
InputStream stream = getContentResolver().openInputStream(data.getData());

What am i doing wrong?
Updated:
Now it's working and here is the solution:
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
    {
        if(data.getData()!=null)
        {
            try
            {
            if (bitmap != null)
                {
                    bitmap.recycle();
                }

            InputStream stream = getContentResolver().openInputStream(data.getData());
            bitmap = BitmapFactory.decodeStream(stream);
            stream.close();
            imageView.setImageBitmap(bitmap);
            }

        catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }

        catch (IOException e)
            {
                e.printStackTrace();
            }
        }

        else
        {
            bitmap=(Bitmap) data.getExtras().get("data");
            imageView.setImageBitmap(bitmap);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}

Thank you for you help!

A: Hi have a try with this code.
following code is for camera button click works :
imgviewCamera.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 //define the file-name to save photo taken by Camera activity
                String fileName = "new-photo-name.jpg";
                //create parameters for Intent with filename
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, fileName);
                values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
                //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                //create new Intent
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(intent, PICK_Camera_IMAGE);
            }
        });

OnActivityresult code will be like below

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Uri selectedImageUri = null;
        String filePath = null;
        switch (requestCode) {
                case PICK_Camera_IMAGE:
                     if (resultCode == RESULT_OK) {
                        //use imageUri here to access the image
                        selectedImageUri = imageUri;

                    } else if (resultCode == RESULT_CANCELED) {
                        Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                    }
                     break;
            }

            if(selectedImageUri != null){
                    try {
                        // OI FILE Manager
                        String filemanagerstring = selectedImageUri.getPath();

                        // MEDIA GALLERY
                        String selectedImagePath = getPath(selectedImageUri);

                        if (selectedImagePath != null) {
                            filePath = selectedImagePath;
                        } else if (filemanagerstring != null) {
                            filePath = filemanagerstring;
                        } else {
                            Toast.makeText(getApplicationContext(), "Unknown path",
                                    Toast.LENGTH_LONG).show();
                            Log.e("Bitmap", "Unknown path");
                        }

                        if (filePath != null) {

                            Toast.makeText(getApplicationContext(), " path" + filePath,
                                    Toast.LENGTH_LONG).show();

                        Intent i = new Intent(getApplicationContext(), EditorActivity.class);
                            // passing array index
                            i.putExtra("id", filePath);
                            startActivity(i);

                        }
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Internal error",
                                Toast.LENGTH_LONG).show();
                        Log.e(e.getClass().getName(), e.getMessage(), e);
                    }
            }

    }

     public String getPath(Uri uri) {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            if (cursor != null) {
                // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
                // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }

dont forget to add camera permission in manifest file.
hope this will help you.


Q: In AVD emulator how to see sdcard folder and install an APK to the AVD? I have created an Android emulator (Android Virtual Device), but I am unable to find out the SD card I have built during creation of this.
How can I find the SD card and its content and also how to install APK files to the AVD?

A: These days the location of the emulated SD card is at /storage/emulated/0

A: On linux sdcard image is located in:
~/.android/avd/<avd name>.avd/sdcard.img

You can mount it for example with (assuming /mnt/sdcard is existing directory):
sudo mount sdcard.img -o loop /mnt/sdcard

To install apk file use adb:
adb install your_app.apk

A:
DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files.

A: Drag & Drop
To install apk in avd, just manually drag and drop the apk file in the opened emulated device
The same if you want to copy a file to the sd card

A: if you are using Eclipse. You should switch to DDMS perspective from top-right corner  there after selecting your device you can see folder tree. to install apk manually you can use adb command
adb install apklocation.apk

A: I have used the following procedure.
Android Studio 3.4.1
View>Tool Windows>Device File Explorer

A: *

*switch to DDMS perspective

*select the emulator in devices list, whose sdcard you want to explore.

*open File Explorer tab on right hand side.

*expand tree structure. mnt/sdcard/
refer to image below

To install apk manually:
copy your apk to to sdk/platform-tools folder and run following command in the same folder
adb install apklocation.apk

A: I have used the following procedure.
Procedure to install the apk files in Android Emulator(AVD):
Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder
Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator.
Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools

*

*Go to Start -> Run -> cmd

*Type cd “C:\Program Files (x86)\Android\android-sdk\platform-tools”

*Type adb install example.apk

*After getting success command

*Go to Application icon in Android emulator, we can see the your
application

A: //in linux
// in your home folder .android hidden folder is there go to that there you can find the avd folder open that and check your avd name that you created open that and you can see the sdcard.img that is your sdcard file.
//To install apk in linux
$adb install ./yourfolder/myapkfile.apk

A: Adding to the usefile DDMS/File Explorer solution, for those that don't know, if you want to read a file you need to select the "Pull File from Device" button on the file viewer toolbar. Unfortunately you can't just drag out, or double click to read.


Q: Saving variables in swing Text field I know how to make a text field but I have no idea how to take the info inputted un the text field and save it into a variable. also be able to save only after pressing enter.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class scratch1 {
    public static void main(String args[]) {

        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        JPanel panel = new JPanel(); // the panel is not visible in output
        JLabel label = new JLabel("Enter Base:");
        JTextField tf = new JTextField(2); // accepts upto 2 characters
        panel.add(label); // Components Added using Flow Layout
        panel.add(tf);

        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.setVisible(true);
    }

A: Try this code, read the comments to understand the code. I hope this code helps you.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

class main {

    static String var; // The text input gets stored in this variable

    public static void main(String args[]) {

        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        JPanel panel = new JPanel();
        JLabel label = new JLabel("Enter Base:");
        JTextField tf = new JTextField(2);
        panel.add(label);
        panel.add(tf);

        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.setVisible(true);

        tf.addActionListener(new ActionListener() { // Action to be performed when "Enter" key is pressed
            @Override
            public void actionPerformed(ActionEvent e) {
                var = tf.getText(); // Getting text input from JTextField(tf)
            }
        });
    }
}


Q: Allow others to develop plugins for my app I'm developing a home screen replacement for Android with search functionality in the app drawer. I not only want to allow (not force) users to search for installed apps, but also other content like Stack Overflow, Wikipedia or their local files.
Currently I'm developing these so-called "Lenses" myself, but I thought it'd be a cool idea if others could develop them as well. So what I'm wondering is if there's any way to allow other developers to do just that; Developing additional lenses for my app.
All lenses should inherit from the following class;
Lens.java
public abstract class Lens
{
    protected Context context;

    protected Lens (Context context)
    {
        this.context = context;
    }

    public abstract List<LensSearchResult> search (String str) throws IOException, JSONException;

    public abstract String getName ();

    public abstract String getDescription ();

    public void onClick (String url)
    {
        if (url.startsWith ("http://") || url.startsWith ("https://"))
        {
            Intent intent = new Intent (Intent.ACTION_VIEW);
            intent.setData (Uri.parse (url));

            this.context.startActivity (intent);
        }
        else
        {
            throw new UnsupportedOperationException ();
        }
    }

    public void onLongPress (String url)
    {
    }

    protected String downloadStr (String url) throws IOException, JSONException
    {
        // Not important. Provided for convenience.
    }

    protected Drawable downloadImage (String url) throws IOException, JSONException
    {
        // Not important. Provided for convenience.
    }
}

The developer should pass Context from their constructor to the superclass, implement List<LensSearchResult> search (String str), String getName (), and String getDescription (). If we're talking about a URL, that's all they need to do. Otherwise they should also override void onClick (String url) and if they wish to do so void onLongPress (String url).
That's basically what a "Lens" would consist of.
So what would I have to do (if at all possible) to make it possible for other developers to create "Lenses" for my app? Ideally they would be able to distribute them in, for example, the Google Play Store, but if necessary I can develop my own platform where others could upload their lenses. Either way I'd still need some way to run someone else's code from within my app.

A:
If you can think of a better way (perhaps like what DashClock does) I'm all ears :)

Design your API around IPC. Have third-party plugins implement a Service, a ContentProvider, and/or a BroadcastReceiver that your host app works with. While a bound service using AIDL would seem to be the most natural way of converting your existing API to one that uses IPC, bound services for plugins have all sorts of issues (e.g., API versioning) that are messy to deal with over time.
In your own app, you might wrap the low-level IPC plumbing in some classes that resemble your existing API. And if you wanted to have third-party developers use some library that you publish to have them create their plugins, you're welcome to do that too. You'll want to create a few plugins yourself, to test out your API and provide samples for third-party developers.
Given all of that, there are any number of ways that you can discover when plugins are installed and removed. ACTION_PACKAGE_ADDED and ACTION_PACKAGE_REMOVED broadcasts, for example, can tell you when other apps are added and removed. You can then use PackageManager to see if they are one of your plugins (e.g., do they implement your IPC endpoint?). Or, use methods on PackageManager like queryIntentServices() to poll for plugin implementations, if that makes more sense.

A: An actual app that uses plugins might give you ideas. Here is the plugin developer page of an app that uses them:
http://www.twofortyfouram.com/developer


Q: Google Play is showing wrong API level After uploading my APK in Google Play it shows in APK details :

API levels : 14-17

and publicly showing "4.0 and up" in play store.
Although my previous version has API levels 14+ but i changed my app and set following minSDK and targetSDK:
<uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="12"
        android:maxSdkVersion="17"/>

But after uploading new APK GOOGLE PLAY is showing wrong API level. It shows "API levels : 14-17". I am tired about this fact. Why not it shows 11-17 and publicly "3.0 and up".
Would anybody knows the real fact ?


Q: D8: Program type already present: com.MyCompany.Game.BuildConfig I get this error after i add GoogleMobileAds plugin into my project. I have shared codes of AndroidManifest.xml of GoogleMobileAds plugin. Can anyone please help ?
(UnityEngine.GUIUtility:processEvent(Int32, IntPtr) (at C:/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:179))

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="com.MyCompany.Game" android:versionName="1.0" android:versionCode="1">
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="28" />
  <application>
    <uses-library android:required="true" android:name="org.apache.http.legacy" />
    <activity
      android:isGame="true"
      android:hardwareAccelerated="true"
      android:name="com.unity3d.player.UnityPlayerNativeActivity" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
      <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
    </activity>
    <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-1010101010101010~1010101010" />
  </application>
</manifest>


Q: For Azure Data Factories is there a way to 'Validate all' using powershell rather than the GUI?
*

*A working Azure Data Factory (ADF) exists that contains pipelines with activities that are dependent on database tables

*The definition of a database table changes

*The next time the pipeline runs it fails

*Of course we can set up something so it fails gracefully but ...

*I need to proactively execute a scheduled Powershell script that iterates through all ADFs (iterating is easy) to do the equivalent of the 'Validate All' (validating is impossible?) functionality that the GUI provides

*I do realise that the Utopian CI/CD DevOps environment I dream about will one day in the next year or so achieve this via other ways

*I need the automation validation method today - not in a year!

I've looked at what I think are all of the powershell cmdlets available and short of somehow deleting and redeploying each ADF (fraught with danger) I can't find a simple method to validate an Azure Data Factory via Powershell.
Thanks in advance

A: In the ".Net" SDK, each of the models has a "Validate()" method.  I have not yet found anything similar in the Powershell commands.
In my experience, the (GUI) validation is not foolproof.  Some things are only tested at runtime.

A: I know it has been a while and you said you didn't want the validation to work in an year - but after a couple of years we finally have both the Validate all and Export ARM template features from the Data Factory user experience via a publicly available npm package @microsoft/azure-data-factory-utilities. The full guidance can be found on this documentation.


Q: how to delete a saved project in Advanced REST client standalone app? I'm trying to delete unused projects in ARC as they are stacking up. I couldn't find any setting related to this.
I found deleting an API call in ARC standalone app(how to delete a saved request in chrome's arc (Advanced REST Client) extension?) but not for saved project

A: I found it upon clicking kebab menu (vertical ellipsis) next to the project I want to delete and selected 'open details' and then there is 'delete project' button


Q: How to open specific web browsers using hyperlinks? I have a simple app which contains a link, I want on mobile apps eg LinkedIn  people to click this link and open it in a browser eg safari
I tried this
May open on Safari'

When I click this link it opens in a native LinkedIn app browser in iPhone
what do I need to change to get this working?

A: The browser that gets used is a user setting on the device based on what they have installed, not something you can control.  Best you can do is recommend that it works best in Safarior or whichever browser.

A: Excerpt from Quora:
The short answer you can't specify that a specific browser will be opened by a hyperlink.
If you are viewing a web page or an app or something that shows a hyperlink and you click on that link then the operating system will receive an event that indicates a hyperlink was launched. It will then look for the default browser, launch that browser and then pass the URL to the browser.
You can change the default browser at any time but the operating system will only open that specify browser.
If you were really determined you might be able to write multiple browser launcher browsers that you would register with the operating system. Then any time you clicked on a link your browser would launch and you could present yourself with a list of alternative browsers to open the link with.
FYI Safari has an option to open the current web page in another browser. It is in menu bar near developer tools.

A: you can configure the edge browser such way- but i couldnt found any solution for other browsers
May open on edge'