text:
Q: drawing query trees using avg? I was wondering how would avg and group by represented in query trees?
I have a query like this:
SELECT  Stats.StuId, Stats.CrsAve
FROM        (SELECT T.StuId, AVG(T.Grd) AS CrsAvg
        FROM        Transcript T
        WHERE   T.Semester IN ('F2004', 'S2006')
        GROUP BY    T.StuId) AS Stats
WHERE       Stats.CrsAvg >  3.5

So, modules GROUP BY and AVG worry me - how are they drawn?

A: You have to use "Avg", but to optimize the query you can avoid using two select adding a clause "Having":
 SELECT T.StuId, AVG(T.Grd) AS CrsAvg
        FROM        Transcript T
        WHERE   T.Semester IN ('F2004', 'S2006')
        GROUP BY    T.StuId
having AVG(T.Grd) > 3.5

Also, you can consider adding appropriate indexes to the table.


text:
Q: Construct a sequence of time related names We have the following sequence in our code:
val halfHourlyColumnNames = Seq("t0000", "t0030", "t0100", "t0130", "t0200", "t0230", "t0300", "t0330", "t0400", "t0430", "t0500", "t0530", "t0600", "t0630", "t0700", "t0730", "t0800", "t0830", "t0900", "t0930", "t1000", "t1030", "t1100", "t1130", "t1200", "t1230", "t1300", "t1330", "t1400", "t1430", "t1500", "t1530", "t1600", "t1630", "t1700", "t1730", "t1800", "t1830", "t1900", "t1930", "t2000", "t2030", "t2100", "t2130", "t2200", "t2230", "t2300", "t2330")
I would like to rewrite this in a much more concise way. What would be the shortest way to create the above sequence in Scala?

A: The shortest way I know of to do this is with string interpolation and using division and modulus to get the 30s:
(0 to 47).map(i => f"t${i/2}%02d${30*(i%2)}%02d")

A: A variation:
for { time <- 0 to 47 }
    yield "t%02d%02d".format(time/2, (if( time % 2 == 0) 0 else 30))

res0: scala.collection.immutable.IndexedSeq[String] =
Vector(t0000, t0030, t0100, t0130, t0200, t0230, t0300, t0330, t0400, t0430, t0500,
t0530, t0600, t0630, t0700, t0730, t0800, t0830, t0900, t0930, t1000, t1030, t1100,
t1130, t1200, t1230, t1300, t1330, t1400, t1430, t1500, t1530, t1600, t1630, t1700,
t1730, t1800, t1830, t1900, t1930, t2000, t2030, t2100, t2130, t2200, t2230, t2300,
t2330)

A: Just for fun ..
scala> (0 to 2330).map(x => f"t$x%04d").filter(_.matches(".*(00|30)$"))
res20: scala.collection.immutable.IndexedSeq[String] = Vector(t0000, t0030, t0100, t0130, t0200,
t0230, t0300, t0330, t0400, t0430, t0500, t0530, t0600, t0630,t0700, t0730, t0800, t0830, t0900,
t0930, t1000, t1030, t1100, t1130, t1200, t1230, t1300, t1330, t1400, t1430, t1500, t1530, t1600,
t1630, t1700, t1730, t1800, t1830, t1900, t1930, t2000, t2030, t2100, t2130, t2200, t2230, t2300,t2330)

A: Here you go:
scala> (0 to 23).flatMap( h => List(0,30).map( m => "t%02d%02d".format(h,m) ))
res8: scala.collection.immutable.IndexedSeq[String] = Vector(
t0000, t0030, t0100, t0130, t0200, t0230, t0300, t0330, t0400, t0430, t0500,
t0530, t0600, t0630, t0700, t0730, t0800, t0830, t0900, t0930, t1000, t1030,
t1100, t1130, t1200, t1230, t1300, t1330, t1400, t1430, t1500, t1530, t1600,
t1630, t1700, t1730, t1800, t1830, t1900, t1930, t2000, t2030, t2100, t2130,
t2200, t2230, t2300, t2330)

Using Scala 2.10: for comprehension and string interpolation with formatting:
scala> for( h <- 0 to 23; m <- Seq(0,30)) yield f"t$h%02d$m%02d"
res6: scala.collection.immutable.IndexedSeq[String] = Vector(
  t0000, t0030, t0100, t0130, t0200, t0230, t0300, t0330, t0400, t0430, t0500,
  t0530, t0600, t0630, t0700, t0730, t0800, t0830, t0900, t0930, t1000, t1030,
  t1100, t1130, t1200, t1230, t1300, t1330, t1400, t1430, t1500, t1530, t1600,
  t1630, t1700, t1730, t1800, t1830, t1900, t1930, t2000, t2030, t2100, t2130,
  t2200, t2230, t2300, t2330)

A: For comprehensions is more demonstrative for Cartesian product
 scala> for {
         | hour <- 0 to 23
         | minutes <- List(0, 30)
         | } yield "t%02d%02d".format(hour, minutes)
    res0: scala.collection.immutable.IndexedSeq[String] = Vector(t0000, t0030, t0100, t0130, t0200, t0230, t0300, t0330, t0400, t0430, t0500, t0530, t0600, t0630, t0700, t0730, t0800, t0830, t0900, t0930, t1000, t1030, t1100, t1130, t1200, t1230, t1300, t1330, t1400, t1430, t1500, t1530, t1600, t1630, t1700, t1730, t1800, t1830, t1900, t1930, t2000, t2030, t2100, t2130, t2200, t2230, t2300, t2330)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap nav tabs aren't switching nor displaying content! [Electron.js] [Bootstrap] I can't figure out why

*

*The tabs aren't switching when clicked

*The tabs aren't displaying content

I am using electron and bootstrap, i would appreciate if someone had any reccomendations or solutions. I read a few other similar questions however did not find the answer (as far as i know).
A snippet is provided. Thanks

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>

              1

              2

              3

              4

HELLO

HELLO

HELLO

A: I hope this one will help you,
please add this link in head tag only.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

A: Because you have not used bootstrap js files. Your code is working fine. Check here

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

              1

              2

              3

              4

HELLO

HELLO

HELLO

A: All i needed to do was update the bootstrap version in the header. Thanks for reading.

A: Try This:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

1

2

3

4

HELLO

Hello

HELLO


text:
Q: AutoHotKey run command in background I'm trying to run a command with AutoHotKey that I would normally run with cmd.exe. Here is the command:
pandoc -s "C:\input.txt" -o "D:\output.html"

This is how I do it in AutoHotKey:
#a::
run pandoc -s "C:\input.txt" -o "D:\output.html"
return

The only problem is that this opens up the a command prompt called "pandoc". Normally I'd just type in the command in cmd.exe and it would run without any hiccups or any windows opening. For this, however, that pandoc window shows up. Am I doing it correctly? Is there any easy way to suppress the window and run the command in the background?

A: Runs a program without opening a window.  The program is "cmd.exe", the windows command shell. It is invoked with arguments "/c time /t", which outputs the current time. It redirects the output to "c:\t.txt"
program
#a::
  run cmd /c time /t > c:\t.txt, c:\, hide
  return

output
c:\>type c:\t.txt
14:28


text:
Q: Cannot drop, edit, retrieve data from SQL Server table I have created table in SQL Server 2012 which has a column of type decimal(18, 4).
I changed that decimal column to decimal(30, 14) and saved the table.
Now I can't do anything with that table. I can't even retrieve rows, edit, insert or drop and recreate that table.
Your help is highly appreciated.


text:
Q: Error installing Homebrew "unexpected disconnect while reading sideband packet" I tried installing Homebrew on the M1 Mac Mini using the command
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

as it is on the docs.
Then mid-way got this error
==> Tapping homebrew/core
remote: Enumerating objects: 1107077, done.
remote: Counting objects: 100% (228/228), done.
remote: Compressing objects: 100% (157/157), done.
error: 545 bytes of body are still expected.44 MiB | 341.00 KiB/s
fetch-pack: unexpected disconnect while reading sideband packet
fatal: early EOF
fatal: index-pack failed
Failed during: git fetch --force origin refs/heads/master:refs/remotes/origin/master
myuser~ %

A: This is more of github checkout issue rather than Homebrew issue, checkout this suggestion:

It might be your network issue. If the network is too slow, then it might disconnect connection unexpectedly.
If you are having a good internet and still getting this message then it might be an issue with post buffer. You can resolve it by executing the following command in your cmd.
git config --global http.postBuffer 157286400


text:
Q: Scoping issue with callbacks in coffeescript I'm really new to Coffeescript/Javascript and I'm writing a little package for Atom. I have no idea why the create_dir function is not visible to the inner function. I suspect there is some kind of scoping problem going on,
{CompositeDisposable, Directory, File} = require 'atom'

module.exports = ImageAssistant =
    subscriptions: null

    activate: (state) ->
        # Events subscribed to in atom's system can be easily cleaned up
        # with a CompositeDisposable
        @subscriptions = new CompositeDisposable

        # Register command that toggles this view
        @subscriptions.add atom.workspace.observeTextEditors((editor) ->
            textEditorElement = atom.views.getView(editor)

            # on drag and drop event
            textEditorElement.addEventListener("drop", (e) ->
                e.preventDefault?()
                e.stopPropagation?()

                editor = atom.workspace.getActiveTextEditor()
                return unless editor

                dropped_files = e.dataTransfer.files
                target_file = editor.getPath()

                fs = require 'fs'
                path = require 'path'
                crypto = require "crypto"

                assets_path = path.join(target_file, "..", "assets")

                for f in dropped_files
                    if fs.lstatSync(f.path).isFile()
                        buffer = new Buffer(fs.readFileSync(f.path))
                        md5 = crypto.createHash 'md5'
                        md5.update(buffer)

                        img_filename = "#{path.parse(target_file).name}-#{md5.digest('hex').slice(0,8)}#{path.extname(f.path)}"
                        console.log img_filename

                        assets_dir = new Directory(assets_path)

                        @create_dir assets_dir, ()=>
                            fs.writeFile path.join(assets_dir, img_filename), buffer, 'binary', ()=>
                                console.log "Copied file over to #{assets_dir}"
                                editor.insertText "![](#{path.join("assets", img_filename)})"

                        return false
            )
        )

    create_dir: (dir_path, callback)=>
        dir_handle = new Directory(dir_path)

        dir_handle.exists().then (existed) =>
            if not existed
                dir_handle.create().then (created) =>
                    if created
                        console.log "Creation of #{dir_path} successful"
                        callback()
            else
                callback()

    deactivate: ->
        @subscriptions.dispose()

The error I'm getting:
 atom-markdown-image-assistant.coffee:43 Uncaught TypeError: _this.create_dir is not a function(anonymous function) @ atom-markdown-image-assistant.coffee:43
    /Applications/Atom.app/Contents/Resources/app.asar/node_modules/jquery/dist/jquery.js:8630 GET https://atom.io/api/packages/markdown-image-assistant 404 (Not Found)send @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/jquery/dist/jquery.js:8630jQuery.extend.ajax @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/jquery/dist/jquery.js:8166(anonymous function) @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/notifications/lib/user-utilities.js:258module.exports.getLatestPackageData @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/notifications/lib/user-utilities.js:257module.exports.checkPackageUpToDate @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/notifications/lib/user-utilities.js:271NotificationElement.renderFatalError @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/notifications/lib/notification-elem…:204NotificationElement.render @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/notifications/lib/notification-elem…:159NotificationElement.initialize @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/notifications/lib/notification-elem…:50(anonymous function) @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/notifications/lib/main.js:89module.exports.ViewRegistry.createView @ /Applications/Atom.app/Contents/Resources/app.asar/src/view-registry.js:119module.exports.ViewRegistry.getView @ /Applications/Atom.app/Contents/Resources/app.asar/src/view-registry.js:86Notifications.addNotificationView @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/notifications/lib/main.js:126(anonymous function) @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/notifications/lib/main.js:27module.exports.Emitter.simpleDispatch @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/event-kit/lib/emitter.js:25module.exports.Emitter.emit @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/event-kit/lib/emitter.js:125module.exports.NotificationManager.addNotification @ /Applications/Atom.app/Contents/Resources/app.asar/src/notification-manager.js:54module.exports.NotificationManager.addFatalError @ /Applications/Atom.app/Contents/Resources/app.asar/src/notification-manager.js:45(anonymous function) @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/notifications/lib/main.js:53module.exports.Emitter.simpleDispatch @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/event-kit/lib/emitter.js:25module.exports.Emitter.emit @ /Applications/Atom.app/Contents/Resources/app.asar/node_modules/event-kit/lib/emitter.js:125(anonymous function) @ /Applications/Atom.app/Contents/Resources/app.asar/src/atom-environment.js:837

I've tried changing all -> to => as suggested here: Multiple Callbacks in CoffeeScript but that didn't fix my issue with the function being undefined.

A: This is due to using a plain object instead of class, see @muistooshort's answer here: Anonymous function works as callback but defined function does not


text:
Q: "atg.project" was unable to instantiate class "atg.eclipse.project.wizard.ProjectWizard". java.lang.NullPointerException when i creating the new ATG project getting the below exception in eclipse

The selected wizard could not be started. Plug-in atg.project was
  unable to instantiate class
  atg.eclipse.project.wizard.ProjectWizard.
  java.lang.NullPointerException

i already added the plugins and using the eclipse 64 bit kepler version, please suggest more on this. below is the exception stack trace
java.lang.NullPointerException
    at atg.eclipse.framework.extension.ATGClassLoadingHook.addClassPathEntry(ATGClassLoadingHook.java:109)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findClassPathEntry(ClasspathManager.java:177)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.buildClasspath(ClasspathManager.java:156)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.initialize(ClasspathManager.java:89)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.initialize(DefaultClassLoader.java:204)
    at org.eclipse.osgi.internal.loader.BundleLoader.createBCL(BundleLoader.java:919)
    at org.eclipse.osgi.internal.loader.BundleLoader.createBCLPrevileged(BundleLoader.java:895)
    at org.eclipse.osgi.internal.loader.BundleLoader.createClassLoader(BundleLoader.java:379)
    at org.eclipse.osgi.internal.loader.BundleLoader.loadClass(BundleLoader.java:335)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:229)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1212)
    at org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI.createExecutableExtension(RegistryStrategyOSGI.java:174)
    at org.eclipse.core.internal.registry.ExtensionRegistry.createExecutableExtension(ExtensionRegistry.java:905)
    at org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:243)
    at org.eclipse.core.internal.registry.ConfigurationElementHandle.createExecutableExtension(ConfigurationElementHandle.java:55)
    at org.eclipse.ui.internal.WorkbenchPlugin$1.run(WorkbenchPlugin.java:282)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ui.internal.WorkbenchPlugin.createExtension(WorkbenchPlugin.java:278)
    at org.eclipse.ui.internal.dialogs.WorkbenchPreferenceNode.createPage(WorkbenchPreferenceNode.java:47)
    at org.eclipse.jface.preference.PreferenceDialog.createPage(PreferenceDialog.java:1340)
    at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.createPage(FilteredPreferenceDialog.java:377)
    at org.eclipse.jface.preference.PreferenceDialog.showPage(PreferenceDialog.java:1231)
    at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.showPage(FilteredPreferenceDialog.java:675)
    at org.eclipse.jface.preference.PreferenceDialog$10.run(PreferenceDialog.java:709)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.jface.preference.PreferenceDialog$9.selectionChanged(PreferenceDialog.java:705)
    at org.eclipse.jface.viewers.StructuredViewer$3.run(StructuredViewer.java:888)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
    at org.eclipse.jface.viewers.StructuredViewer.firePostSelectionChanged(StructuredViewer.java:886)
    at org.eclipse.jface.viewers.StructuredViewer.setSelection(StructuredViewer.java:1726)
    at org.eclipse.jface.viewers.TreeViewer.setSelection(TreeViewer.java:1139)
    at org.eclipse.jface.preference.PreferenceDialog.selectSavedItem(PreferenceDialog.java:1055)
    at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.selectSavedItem(FilteredPreferenceDialog.java:730)
    at org.eclipse.jface.preference.PreferenceDialog$4.run(PreferenceDialog.java:376)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.jface.preference.PreferenceDialog.createContents(PreferenceDialog.java:372)
    at org.eclipse.jface.window.Window.create(Window.java:432)
    at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:1104)
    at org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.createDialogOn(WorkbenchPreferenceDialog.java:102)
    at org.eclipse.ui.dialogs.PreferencesUtil.createPreferenceDialogOn(PreferencesUtil.java:192)
    at org.eclipse.ui.dialogs.PreferencesUtil.createPreferenceDialogOn(PreferencesUtil.java:116)
    at org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:64)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:499)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
    at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
    at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:411)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1057)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4170)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3759)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1113)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:997)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:140)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:611)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:567)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:354)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:181)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:636)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:591)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1450)


text:
Q: Select records that match several tags I implemented a standard tagging system on SQLite with two tables.
Table annotation:
CREATE TABLE IF NOT EXISTS annotation (
        id INTEGER PRIMARY KEY,
        comment TEXT
)

Table label:
CREATE TABLE IF NOT EXISTS label (
        id INTEGER PRIMARY KEY,
        annot_id INTEGER NOT NULL REFERENCES annotation(id),
        tag TEXT NOT NULL
)

I can easily find the annotations that match tags 'tag1' OR 'tag2' :
SELECT * FROM annotation
        JOIN label ON label.annot_id = annotation.id
        WHERE label.tag IN ('tag1', 'tag2') GROUP BY annotation.id

*

*But how do I select the annotations that match tags 'tag1' AND
'tag2'?

*How do I select the annotations that match tags 'tag1'
AND 'tag2' but NOT 'tag3'?

Should I use INTERSECT? Is it efficient or is there a better way to express these?

A: I would definitely go with INTERSECT for question 1 and EXCEPT for question 2. After many years of experience with SQL I find it best to go with whatever the platform offers in cases where it directly addresses what you want to do.
The only exception would be if you had a really good reason not to. In this case, intersect and except are not ansi standard, so you are stuck with sqlite for as long as you use them.
If you want to go old school and use ONLY straight up SQL it is possible using subqueries, one for tag A, one for tag B, and one for tag C. Using an outer join with an "is null" condition is a common idiom to perform the exclusion.
Here is an sqlite example:
create table annotation (id integer, comment varchar);
create table label (id integer, annot_id integer, tag varchar);
insert into annotation values (1,'annot 1'),(2,'annot 2');
insert into label values (1,1,'tag1'),(2,1,'tag2'),(3,1,'tag2');
insert into label values (1,2,'tag1'),(2,2,'tag2'),(3,2,'tag3');

select distinct x.id,x.comment from annotation x
join label a on a.annot_id=x.id and a.tag='tag1'
join label b on b.annot_id=x.id and b.tag='tag2'
left join label c on c.annot_id=x.id and c.tag='tag3'
where
  c.id is null;

This is set up so that both annotation 1 and 2 have tag1 and tag2 but label 2 has tag3 so should be excluded the output is only annotation 1:

id
comment

1
annot 1


text:
Q: Android layout even spacing Here's a comparison of what my editor and device is showing:

The problem is:

*

*row containing TextView's should take 50% of the screen

*row containing Icon should take remaining 50% of the screen

It works correctly in editor, but as you can see, layout behaves much differently on actual device.
Where's my problem and how to solve it?
Library used for icon is:
https://github.com/code-mc/material-icon-lib
It extends directly from ImageView.
Layout XML:
<TableLayout
    android:id="@+id/menuLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="*" >

    <TableRow
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
        <LinearLayout
            android:layout_weight="1"
            android:orientation="horizontal"
            android:layout_height="match_parent"
            android:layout_width="match_parent">
            <android.support.v7.widget.AppCompatTextView
                android:id="@+id/teenSelection"
                android:textColor="@color/WHITE"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:layout_weight="1"
                android:textStyle="bold"
                android:textSize="30sp"
                android:text="TEEN" />
            <android.support.v7.widget.AppCompatTextView
                android:id="@+id/adultSelection"
                android:textColor="@color/WHITE"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:layout_weight="1"
                android:textStyle="bold"
                android:textSize="30sp"
                android:text="ADULT"/>
            <android.support.v7.widget.AppCompatTextView
                android:id="@+id/seniorSelection"
                android:textColor="@color/WHITE"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:layout_weight="1"
                android:textStyle="bold"
                android:textSize="30sp"
                android:text="SENIOR"/>
        </LinearLayout>
    </TableRow>

    <TableRow
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
        <net.steamcrafted.materialiconlib.MaterialIconView
            android:layout_weight="1"
            android:id="@+id/confirmButton"
            app:materialIcon="check"
            app:materialIconColor="#fff"
            android:scaleType="center"
            android:layout_height="match_parent"
            android:layout_width="match_parent"/>
    </TableRow>

</TableLayout>

A: you have set your heights of the two TableRows to wrap_content, but they must be match_parent like this:
<TableRow
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:layout_width="match_parent">

otherwise the weight for the height is ignored.

A: You should try PercentRelativeLayout
in app level build.gradle add this
compile 'com.android.support:percent:23.3.0'

and change your layout with this.
<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/layoutTop"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:weightSum="3"
        app:layout_heightPercent="50%"
        app:layout_widthPercent="100%">

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/teenSelection"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="TEEN"
            android:textColor="@android:color/white"
            android:textSize="30sp"
            android:textStyle="bold" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/adultSelection"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="ADULT"
            android:textColor="@android:color/white"
            android:textSize="30sp"
            android:textStyle="bold" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/seniorSelection"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="SENIOR"
            android:textColor="@android:color/white"
            android:textSize="30sp"
            android:textStyle="bold" />
    </LinearLayout>

    <net.steamcrafted.materialiconlib.MaterialIconView
        android:id="@+id/confirmButton"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_below="@+id/layoutTop"
        android:scaleType="center"
        app:layout_heightPercent="50%"
        app:layout_widthPercent="100%"
        app:materialIcon="check"
        app:materialIconColor="#fff" />

</android.support.percent.PercentRelativeLayout>

A: add your TableRow in LinearLayout like this.
i worked. i did test.
<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:stretchColumns="*">

    <LinearLayout
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:layout_width="match_parent">

        <TableRow
            android:layout_weight="1"
            android:orientation="vertical"
            android:layout_height="match_parent"
            android:layout_width="match_parent">
            <LinearLayout
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_width="match_parent">
                <android.support.v7.widget.AppCompatTextView
                    android:id="@+id/teenSelection"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:layout_weight="1"
                    android:background="@color/black_slow"
                    android:textStyle="bold"
                    android:textSize="30sp"
                    android:text="TEEN" />
                <android.support.v7.widget.AppCompatTextView
                    android:id="@+id/adultSelection"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:layout_weight="1"
                    android:background="@color/black_slowest"
                    android:textStyle="bold"
                    android:textSize="30sp"
                    android:text="ADULT"/>
                <android.support.v7.widget.AppCompatTextView
                    android:id="@+id/seniorSelection"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:background="@color/colorPrimaryDark"
                    android:layout_weight="1"
                    android:textStyle="bold"
                    android:textSize="30sp"
                    android:text="SENIOR"/>
            </LinearLayout>
        </TableRow>

        <TableRow
            android:layout_weight="1"
            android:orientation="vertical"
            android:layout_height="match_parent"
            android:layout_width="match_parent">
            <net.steamcrafted.materialiconlib.MaterialIconView
                android:id="@+id/confirmButton"
                app:materialIcon="check"
                app:materialIconColor="#fff"
                android:scaleType="center"
                android:layout_height="match_parent"
                android:layout_width="match_parent"/>
        </TableRow>
    </LinearLayout>

</TableLayout>


text:
Q: prevent solution from being simplified I want to the solution got back from z3 without simplification using let statements.
For example if  I give the following:
(declare-const x Int)
  (elim-quantifiers (exists ((x.1 Int))
    (and (or (and (= (- x.1 2) 0) (<= (- x.1 9) 0))
             (and (or (= (- x.1 2) 0) (and (<= (- x.1 4) 0)
                                      (and (<= (- 4 x.1) 0)
                                           (<= (- x.1 11) 0)))) (<= (- x.1 9) 0))) (= (- (+ x.1 2) x) 0))))

I get back the solution as:
(let ((a!1 (and (or (and (<= x 4) (>= x 4)) (and (<= x 6) (>= x 6) (<= x 13)))
                (<= x 11))))
    (or (and (<= x 4) (>= x 4) (<= x 11)) a!1))

Is there a way to tell Z3 not to extract some complex expressions into a let statement ? It will be easier for me to parse the result if I get the answer flat without let statement.

A: We can set the following options to prevent the Z3 pretty printer from using lets
(set-option :pp-min-alias-size 1000000)
(set-option :pp-max-depth      1000000)

Any big number will do the trick.
We have to keep in mind that it may not be feasible to display some formulas that contain a lot of shared sub-expressions when we avoid the lets. Internally, Z3 stores the formulas as DAGs instead of Trees. If we do not use the lets, the pretty-print of such formulas may be exponentially bigger than their internal representation. So, we should not abuse the options above.

A: I am using z3-4.5.0 and looks like the options names have changed a little. If pp-max-depth did not work for you, try pp.max_depth and pp.min_alias_size.
I am using the Java API and the following worked with me
com.microsoft.z3.Global.setParameter("pp.min_alias_size", "1000000");
com.microsoft.z3.Global.setParameter("pp.max_depth", "1000000");


text:
Q: Environment specific variables with requirejs I would like to set a requirejs configuration variable which would be available via module.config.
The optimizer does not seem to pass this through.
Is this possible, or should I handle this step via my build process.

A: You have to set it in your config file for a specific module like this and as long as your told r.js to use this config file it should work:
requirejs.config({

  config: {
    'path/to/myModule': {
      someSetting: 'someSetting'
    }
  }
});

A: A simple solution seems to be to be:

*

*Create a config file for each environment (eg., config, config-production)

*When you want your config, require('/path/to/config')

*When you call r.js, just put in a paths argument (eg., r.js -o build.js paths.config=config-production)

*You now have your production configuration settings


text:
Q: using module afte requiring with WebPack I'm starting to learn ReactJS and I have decided to use WebPack to manage dependencies. Now I wish to add, for instance arrayJS. How can I use the provided methods after requiring it?
var React = require('react');
var array = require('array');

var DATA = {
  items: [
    { id: 1, name: 'a1' },
    { id: 2, name: 'a3' },
    { id: 3, name: 'a4' },
    { id: 4, name: 'a2' }
  ]
};

...

How can I sort items by name using the 'sort' method provided by arrayJS?
Something like DATA.items.sort('name')
Thanks

A: arrayjs requires you to wrap your array in their constructor so after your code you can just write:
var wrappedArray = array(DATA.items);

var sortedArray = wrappedArray.sort('name');


text:
Q: using preg_match to match a number between 5 and 10 characters long I am trying to use preg_match to match a number that's between 5 and 10 characters long. However, I want the ENTIRE number. I have
preg_match("/\d{5, 10}/", $str, $match)

but the above code will match the first 5 digits of a number that is let's say 10 characters long. How can I make it return the entire length of the number?

A: The quantifier syntax is {x,y}, not {x,<space>y}.
preg_match("/\d{5,10}/", $str, $match) works just fine.


text:
Q: Android Studio - Passing variable with intent add extra, ends up with null after fixing the null pointer exception of a previous question, (Not sure if posting a different question for the same code is okay, do let me know if it is not) I've come across a new problem. When I try passing the date variable from this first activity to another, it is always empty. I've also tried just setting a public getter or the variable and it is also empty. However, using a toast to check within the class shows that the variable does indeed contain the date. I am trying to pass the date class to be added into a database by the other classes in the application package. Any help would be much appreciated.
CalendarActivity.java
package com.example.zaphk.studenthelperapplication3.calendar;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CalendarView;
import android.widget.Toast;

import com.example.zaphk.studenthelperapplication3.R;

public class CalendarActivity extends AppCompatActivity {
    public static final String EXTRA_TEXT = "com.example.zaphk.studenthelperapplication3";
    private  static final String TAG = "CalendarActivity";
    private CalendarView mCalendarView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.calendar_layout);
        mCalendarView = (CalendarView) findViewById(R.id.calendarView);
        mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView CalendarView, int year, int month, int dayOfMonth) {
                String date = year + "/" + month + "/"+ dayOfMonth ;
                Log.d(TAG, "onSelectedDayChange: yyyy/mm/dd:" + date);
                Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
                intent.putExtra(Intent.EXTRA_TEXT,date);
                startActivity(intent);

                Toast.makeText(CalendarActivity.this,date,Toast.LENGTH_SHORT).show();

            }
        });
    }
}

The class I am trying to receive it from : CalendarEvent.java
package com.example.zaphk.studenthelperapplication3.calendar;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar;
import com.example.zaphk.studenthelperapplication3.calendar.database.CalendarAdapter;
import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar_DbHelper;
import com.example.zaphk.studenthelperapplication3.utils.MyDividerItemDecoration;
import com.example.zaphk.studenthelperapplication3.utils.RecyclerTouchListener;

import com.example.zaphk.studenthelperapplication3.R;

public class CalendarEvent extends AppCompatActivity {
    private CalendarAdapter mAdapter;
    private List<Calendar> notesList = new ArrayList<>();
    private CoordinatorLayout coordinatorLayout;
    private RecyclerView recyclerView;
    private TextView noNotesView;
    Intent intent = getIntent();
    public String date;

    private Calendar_DbHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        intent = getIntent();
        date = intent.getStringExtra(CalendarActivity.EXTRA_TEXT);

        setContentView(R.layout.activity_notes);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        coordinatorLayout = findViewById(R.id.coordinator_layout);
        recyclerView = findViewById(R.id.recycler_view);
        noNotesView = findViewById(R.id.empty_notes_view);

        db = new Calendar_DbHelper(this);

        notesList.addAll(db.getAllNotes());

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNoteDialog(false, null, -1);
            }
        });

        mAdapter = new CalendarAdapter(this, notesList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
        recyclerView.setAdapter(mAdapter);

        toggleEmptyNotes();

        /**
         * On long press on RecyclerView item, open alert dialog
         * with options to choose
         * Edit and Delete
         * */
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
                recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, final int position) {
            }

            @Override
            public void onLongClick(View view, int position) {
                showActionsDialog(position);
            }
        }));
    }

    /**
     * Inserting new note in db
     * and refreshing the list
     */
    private void createNote(String note) {

        // inserting note in db and getting
        // newly inserted note id
        long id = db.insertNote(note);

        // get the newly inserted note from db
        Calendar n = db.getNote(id);

        if (n != null) {
            // adding new note to array list at 0 position
            notesList.add(0, n);

            // refreshing the list
            mAdapter.notifyDataSetChanged();

            toggleEmptyNotes();
        }
    }

    /**
     * Updating note in db and updating
     * item in the list by its position
     */
    private void updateNote(String note, int position) {
        Calendar n = notesList.get(position);
        // updating note text
        n.setNote(note);

        // updating note in db
        db.updateNote(n);

        // refreshing the list
        notesList.set(position, n);
        mAdapter.notifyItemChanged(position);

        toggleEmptyNotes();
    }

    /**
     * Deleting note from SQLite and removing the
     * item from the list by its position
     */
    private void deleteNote(int position) {
        // deleting the note from db
        db.deleteNote(notesList.get(position));

        // removing the note from the list
        notesList.remove(position);
        mAdapter.notifyItemRemoved(position);

        toggleEmptyNotes();
    }

    /**
     * Opens dialog with Edit - Delete options
     * Edit - 0
     * Delete - 0
     */
    private void showActionsDialog(final int position) {
        CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose option");
        builder.setItems(colors, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    showNoteDialog(true, notesList.get(position), position);
                } else {
                    deleteNote(position);
                }
            }
        });
        builder.show();
    }

    /**
     * Shows alert dialog with EditText options to enter / edit
     * a note.
     * when shouldUpdate=true, it automatically displays old note and changes the
     * button text to UPDATE
     */
    private void showNoteDialog(final boolean shouldUpdate, final Calendar note, final int position) {
        LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
        View view = layoutInflaterAndroid.inflate(R.layout.note_dialog, null);

        AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(CalendarEvent.this);
        alertDialogBuilderUserInput.setView(view);

        final EditText inputNote = view.findViewById(R.id.note);
        TextView dialogTitle = view.findViewById(R.id.dialog_title);
        dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_note_title) : getString(R.string.lbl_edit_note_title));

        if (shouldUpdate && note != null) {
            inputNote.setText(note.getNote());
        }
        alertDialogBuilderUserInput
                .setCancelable(false)
                .setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogBox, int id) {

                    }
                })
                .setNegativeButton("cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogBox, int id) {
                                dialogBox.cancel();
                            }
                        });

        final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
        alertDialog.show();

        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Show toast message when no text is entered
                if (TextUtils.isEmpty(inputNote.getText().toString())) {
                    Toast.makeText(CalendarEvent.this, "Enter note!", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    alertDialog.dismiss();
                }

                // check if user updating note
                if (shouldUpdate && note != null) {
                    // update note by it's id
                    updateNote(inputNote.getText().toString(), position);
                } else {
                    // create new note
                    createNote(inputNote.getText().toString());
                }
            }
        });
    }

    /**
     * Toggling list and empty notes view
     */
    private void toggleEmptyNotes() {
        // you can check notesList.size() > 0

        if (db.getNotesCount() > 0) {
            noNotesView.setVisibility(View.GONE);
        } else {
            noNotesView.setVisibility(View.VISIBLE);
        }
    }

    public String getDate(){

        return date;
    }
}

A: You are using wrong key while passing data between activity.
Replace below line,
intent.putExtra(Intent.EXTRA_TEXT,date);

With this one,
intent.putExtra(CalendarActivity.EXTRA_TEXT,date);

A: You use the key of Intent.EXTRA_TEXT.
intent.putExtra(Intent.EXTRA_TEXT,date)

But you use the other key to receive. It's not the same key.
intent.getStringExtra(CalendarActivity.EXTRA_TEXT);

A: As per I know (Not pretty sure)
Intent.EXTRA_TEXT

is used for implicit intents.
For explicit (i.e.Activity to Activity)
Do as below
Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
intent.putExtra("DATE",date);
startActivity(intent);

To receive
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_notes);
    intent = getIntent();
    String date = intent.getStringExtra("DATE");
}

Where "DATE" is String KEY.

A: I would say that CalendarActivity.EXTRA_TEXT is probably empty because you have not imported that class in to CalendarEvent.java
import com.example.zaphk.studenthelperapplication3.calendar.CalendarActivity; in CalendarEvent.java
and as other people have said the put and get on the Intent need to be the the same String value.


text:
Q: \sectionmark not working on the first page with book documentclass and titlesec I would like to kindly ask for a help.
I am using two sided book documentclass, and I have a long section title.
My main question is how to make it shorter in the headers. It seems to interfeer with titlesec package (which I am using for something else).
I tried the following from the https://texfaq.org/FAQ-runheadtoobig
\documentclass[twoside, a4paper, 12pt]{book}
\usepackage{lipsum}
\usepackage{titlesec}

\titlespacing*{\paragraph}
{0pt}{1ex plus 0ex minus .2ex}{3ex}

\begin{document}
    \chapter{test}
    \paragraph{Test paragraph}
    \lipsum

    \section[This is a loooooooong looooooooooong looooooooooooong title in TOC]{This is a loooooooong looooooooooong looooooooooooong title%
        \sectionmark{This is a loooooooong looooooooo\ldots}}
    \sectionmark{This is a loooooooong looooooooo\ldots}
    \lipsum
    \lipsum
\end{document}

but it is not working, I still get the header on the first page of section long.
I would be happy even for some automated variant.
Thank you
Libor

A: In the book, and other standard classes the divisional commands, like \chapter take one optional argument.
\chapter[title for Toc and header]{Main title}

It seems that you want a short title in the header but long ones in the ToC and body.
The memoir class (a superset of book and report) offers two optional arguments like:
\chapter[toc-title][head-title]{main-title}
\chapter[toc-and-head-title]{main-title}
\chapter{main-title} % main title used in all three places

And similarly for \section and the other divisional commands.
Perhaps consider using the memoir class.

A: Just put additional \sectionmark before \section
\sectionmark{This is a loooooooong looooooooo\ldots}
\section[This is a loooooooong looooooooooong looooooooooooong title in TOC]{This is a loooooooong looooooooooong looooooooooooong title}
\sectionmark{This is a loooooooong looooooooo\ldots}


text:
Q: When a Firebase user is deleted from Firebase console (after user login), it is not reflected in the application The user.uid is still coming (with the help of this uid != null, I am assuming the user is logged in).
I also tried addAuthStateListener(mAuthListener), but I am still getting UID of the previously deleted user.
Without using database track of banned or deleted user ids is it possible to remove that user instantly.

A: When a user signs in to Firebase, they get an access/ID token that is valid for an hour. This ID token cannot be revoked, as that would require Firebase to perform a quite expensive check on each call.
So when you delete the user's account from the console, they may retain access for up to an hour, at which point they will need to refresh their token, which will fail (since you deleted their account). So their access will automatically disappear within an hour.
A few points:

*

*If you want to lock the user out of the application before their ID token expires, you'll want to keep an additional list of banned UIDs somewhere. For example, if you're using a Firebase database, you can keep a global list of bannedUIDs, and add the UID to that. Then in your server-side security rules, you can check if the UID who's trying to access the database isn't banned.

*If you delete the user's account, they can just sign up again and create a new account. For this reason it is typically better to disable their account, which accomplishes the same (they won't be able to get a new ID token after their current one expires), but prevents them from signing up again with the same credentials.

Also see:

*

*the video Five tips to secure your app

*User keeps login even if I delete the account

*Why firebase user still signed in after I deleted it from firebase dashboard

*Does deleting account from Firebase automatically logs user out?

*User authentication persisted after having cancelled the user from console.firebase.google.com

*Firebase user deleted but still logged in on device


text:
Q: stuck on gmaps4rails data from array I would like to take an array and load the data into the json object, but i am stuck on exactly how to do it.
TripsController
def index
@trips = Trip.all
@markers = Array.new
@trips.each do |trip|
  for marker in trip.markers
    @markers.push(marker)
  end
end

@gmaps_options =
{
  "markers"     => { "data" => '[{ "lng": "-99.9018131", "lat": "31.9685988"},
                                 { "lng": "-102.552784", "lat": "23.634501"},
                                 { "lng": "-122.3667", "lat": "40.5833"},
                                 { "lng": "-121.8356", "lat": "39.7400"}
                                  ]', },
  "polylines"   => { "data" => ' [ [
                     {"lng": -99.9018131, "lat": 31.9685988},
                     {"lng": -102.552784, "lat": 23.634501},
                     ], [
                      { "lng": "-122.3667", "lat": "40.5833"},
                      { "lng": "-121.8356", "lat": "39.7400"}
                      ] ]' }
}

respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @trips }
  end
end

The longitude and latitude are hardcoded right now but i would like to load the @markers into the longitude latitude,
"lng": @markers[0].longitude, "lat": @markers[0].latitude

This makes the map not render, just a gray box.
In the view the map is called with gmaps(@gmaps_options)
Any help would be greatly appreciated.

A: it looks like you have your variable reference inside of a quoted string.
try adding the value to the string
'[{ "lng":' + @markers[0].longitude.to_s + ', "lat": @markers[0].latitude ....'


text:
Q: Event when machine has been locked/unlocked (Electron Windows) So i have some tasks that i need to be notified when the user locks their machine. This is in order to pause those tasks. Equally i need to know when the machine has been successfully unlocked in order to resume said tasks. This is purely for a Windows only function so doesn't need to be cross-platform.
Ive looked through the Electron docs and found this about the powerMonitor API's however it only has events for suspend and resume. I assume they refer to the machine going to sleep as locking and un-locking does not trigger them on my machine (Win 10).
I know very little of how core Windows works, with its messages/event system. However i have found this which lists information about the WM_WTSSESSION_CHANGE which seems to be what i need. Notably the WTS_SESSION_LOCK (0x7) and WTS_SESSION_UNLOCK (0x8) status codes.
However i can't find a way either with electron or NodeJS directly to listen to Windows messages.
Any advice on the problem would be greatly appreciated. Thanks

A: Just in case someone ends up on this old question, powerMonitor now supports two events for this: lock-screen and unlock-screen, so you can just (in the main process):
const {powerMonitor} = require("electron");

powerMonitor.addListener('lock-screen', () => {
  // Screen is locked, do something
});

powerMonitor.addListener('unlock-screen', () => {
  // Screen is unlocked, do something else
});

A: You can do this using 'electron-edge-js'
Here is the solution:
if( process.platform == 'win32' || process.platform == 'win64' ) {
    var edge = require( 'electron-edge-js' );

    var checkLockStatus = edge.func( function() {/*
        using System;
        using System.Threading.Tasks;
        using Microsoft.Win32;
        using System.Collections.Generic;

        public class Startup : IDisposable
        {
            private Func<object, Task<object>> callbackFn;
            public async Task<object> Invoke(IDictionary<string, object> input)
            {
                callbackFn = (Func<object, Task<object>>)input["callbackFn"];
                SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
                return null;

            }

            public async void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
            {
                 if (e.Reason == SessionSwitchReason.SessionLock)
                {
                    callbackFn( "locked" );
                }
                else if (e.Reason == SessionSwitchReason.SessionUnlock)
                {
                   callbackFn( "unlocked" );
                }
            }

            public void Dispose()
            {
                SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
            }
        }
    */} );

    checkLockStatus( {
        callbackFn: function( state ) {
            console.log( state );
        }
    } );
}


text:
Q: Set Window Resizable In IB this can be done easily by checking the 'Resize' checkbox on or off.
My problem is I want my main NSWindow to not be resizable, until a button is clicked, and then i want it to be resizable.
I've scoured the Internet but can't find anything? Can a window not be made to be resizable or not programmatically?
Thanks in advance everyone!

A: The Swift 3 solution to this issue is to use the OptionSet class described at:
https://developer.apple.com/reference/swift/optionset
In short:
To replace the set of flags, you now do something like:
myWindow.styleMask = [ .resizable, .titled, .closable ]

To add a flag, do something like:
myWindow.styleMask.insert( [ .miniaturizable, .fullscreen ] )

To remove a flag, something like:
myWindow.styleMask.remove( [ .resizable ] )

A: Since 10.6, you can change the style mask of a window using -[NSWindow setStyleMask:].  So, you'd do something like this:
In Objective-C
To make it resizable:
window.styleMask |= NSWindowStyleMaskResizable;

To make it non-resizable:
window.styleMask &= ~NSWindowStyleMaskResizable;

In Swift
To make it resizable:
mainWindow.styleMask = mainWindow.styleMask | NSWindowStyleMaskResizable

To make it non-resizable:
mainWindow.styleMask = mainWindow.styleMask & ~NSWindowStyleMaskResizable

A: You can't change the style mask of a window after creating it, but you can set the window's minimum and maximum frame size to the same size. Do that after you and your resizable window awake from nib, and then change the maximum and optionally the minimum size back when the user clicks the button.

A: In Swift 3,
if enabled {
  window.styleMask.update(with: .resizable)
} else {
  window.styleMask.remove(.resizable)
}

A: In Xcode 8 / Swift 3, try something like:
// e.g., on a view controller's viewDidAppear() method:
if let styleMask = view.window?.styleMask
{
    view.window!.styleMask = NSWindowStyleMask(rawValue: styleMask.rawValue | NSWindowStyleMask.resizable.rawValue)
}

A: I am new to macOS development. None of the above solutions worked for me (Swift 4.2). I also didn't learn that much (copy/paste doesn't help with that).
I have created this NSWindow subclass. I use it in Interface builder.
class MainDocumentChooserW: NSWindow {

    // NOTE: This method is called when the Window is used via Interface builder.
    // Setting the styleMask like this will override the IB settings.
    override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing backingStoreType: NSWindow.BackingStoreType, defer flag: Bool) {
        super.init(contentRect: contentRect, styleMask: style, backing: backingStoreType, defer: flag)
        styleMask = [.miniaturizable, .titled, .closable]
    }
}

Tested on macOS: High Sierra 10.13.6 (17G5019).


text:
Q: Symfony/Doctrine: Getting last insert id from processForm? How do I get the last insert ID after a process form request such as this one:
$this->form = new StudyPlanForm();

$this->processForm($request, $this->form);

I would use save() but I can't figure out a way to save without having to do $studyplan->setField($request->getParameter(...)) for every single field.

A: Try:
.. form processing ..
$id = $this->form->getObject()->id;

Update:
It is possible to fetch object from your form only if it is an instance of sfFormObject.

A: Change your processForm function like this:
protected function processForm(sfWebRequest $request, sfForm $form)
{
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $obj = $form->save();
    }

    return $obj;
}

The save method returns the object persisted on db, so you can get the id from that. So you can do:
$this->form = new StudyPlanForm();

$obj = $this->processForm($request, $this->form);
if ($obj != null){
    //do whatever you want like $obj->getId()
}


text:
Q: Dart json_serializable erro, Dart analysis: expected this library to be part of "....User.dart",not "......user.dart" I was using build_runner and json_serializable to bind my json model,but get a error
This is my code structure:

My user.dart was:
import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User extends Object {

  @JsonKey(name: 'login')
  String login;

  @JsonKey(name: 'avatar_url')
  String avatarUrl;

  @JsonKey(name: 'type')
  String type;

  @JsonKey(name: 'name')
  String name;

  @JsonKey(name: 'company')
  String company;

  @JsonKey(name: 'blog')
  String blog;

  @JsonKey(name: 'location')
  String location;

  @JsonKey(name: 'email')
  String email;

  @JsonKey(name: 'hireable')
  bool hireable;

  @JsonKey(name: 'bio')
  String bio;

  @JsonKey(name: 'public_repos')
  int publicRepos;

  @JsonKey(name: 'followers')
  int followers;

  @JsonKey(name: 'following')
  int following;

  @JsonKey(name: 'created_at')
  String createdAt;

  @JsonKey(name: 'updated_at')
  String updatedAt;

  @JsonKey(name: 'total_private_repos')
  int totalPrivateRepos;

  @JsonKey(name: 'owned_private_repos')
  int ownedPrivateRepos;

  User(this.login,this.avatarUrl,this.type,this.name,this.company,this.blog,this.location,this.email,this.hireable,this.bio,this.publicRepos,this.followers,this.following,this.createdAt,this.updatedAt,this.totalPrivateRepos,this.ownedPrivateRepos,);

  factory User.fromJson(Map<String, dynamic> srcJson) => _$UserFromJson(srcJson);

  Map<String, dynamic> toJson() => _$UserToJson(this);

}

After command run flutter packages pub run build_runner watch
,I get this user.g.dart:
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

User _$UserFromJson(Map<String, dynamic> json) {
  return User(
    json['login'] as String,
    json['avatar_url'] as String,
    json['type'] as String,
    json['name'] as String,
    json['company'] as String,
    json['blog'] as String,
    json['location'] as String,
    json['email'] as String,
    json['hireable'] as bool,
    json['bio'] as String,
    json['public_repos'] as int,
    json['followers'] as int,
    json['following'] as int,
    json['created_at'] as String,
    json['updated_at'] as String,
    json['total_private_repos'] as int,
    json['owned_private_repos'] as int,
  );
}

Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
      'login': instance.login,
      'avatar_url': instance.avatarUrl,
      'type': instance.type,
      'name': instance.name,
      'company': instance.company,
      'blog': instance.blog,
      'location': instance.location,
      'email': instance.email,
      'hireable': instance.hireable,
      'bio': instance.bio,
      'public_repos': instance.publicRepos,
      'followers': instance.followers,
      'following': instance.following,
      'created_at': instance.createdAt,
      'updated_at': instance.updatedAt,
      'total_private_repos': instance.totalPrivateRepos,
      'owned_private_repos': instance.ownedPrivateRepos,
    };

But the dart analysis show:

The error only happened on my user.part,other .part(like profille.part,repo.part)not.
I wanna know why this error occured

A: Same thing happened to me. Here is how I fixed it:
I copied the code of user.dart into another text editor and completely deleted user.dart and user.g.dart
then I created a new user.dart and pasted the contents back. And then I ran flutter packages pub run build_runner watch and it fixed the issue.
I think what happened is that you (and I) accidentally created "User.dart" instead of "user.dart", and VSCode cached this somewhere and looked it up from the cache. But that is just my guess.

A: Another solution for this problem, that I've found is closing VSCode, then deleting cache directories from your's project repository(like .dart_tool, .vscode) and running the build_runner again.

A: For me, I had to go to the generated .g.dart file, and then there correct the part of statement to refer to the correct file.

A: Try to rename that file to another name and rename that file name back to the original name.
I am able to solve this issue via above method.

A: Just closing and reopening vs code did the trick for me.


text:
Q: How to convert a test message to an integer number to produce ciphertext in RSA The function ConvertToInt(message) should convert a text message to an integer number so ciphertext in RSA can be produced using the formula M^e mod n. Here M is the message that must be encoded into a single number. Instead, my following function ConvertToInt returns an array with elements each of which is the ASCII value of the characters. So the result becomes a character by character encryption instead of a string.
Which is the proper way to convert the message to an integer and calculate the proper RSA encrypted result?
Here is my code:
def ConvertToInt(message):
    l = len(message)
    arra = []
    i = 0
    while(i<l):
        j=ord(message[i])
        arra.append(j)
        i += 1
    return arra

def mod_ex(b, k, m):

    i = 1
    j = 0
    while(j<=k):
        b = (b*i) % m
        i = b
        j += 1
    return b
def PowMod(s,modulo,exponent):

    bin_e = bin(exponent)
    bin_e = bin_e [::-1]
    ln = len(bin_e)
    result = 1
    slen = len(s)
    for i in range(0,slen,+1):
        for j in range(0,ln-2,+1):
            if(bin_e[j]=='1'):
                result *= mod_ex(s[i],j,modulo)
        s[i] = result%modulo
        result = 1
    return s

def Encrypt(message, modulo, exponent):

  s = ConvertToInt(message)
  return PowMod(s, modulo, exponent)

x = Encrypt("Aa",473,17)
print(x)

A: Here is a ConvertToInt function that effectively calculated a number out of a string which can be used in RSA Encryption, cz RSA encryption must need a number to operate.
def ConvertToInt(message):
grd = 1
num = 0
message = message [::-1]
for i in range(0,len(message),+1):
    num = num+ord(message[i])*grd
    grd *= 256
return num

Get the full RSA Code in python here:

*

*https://github.com/Sazzad-Saju/RSA_Algorithm

A: I think it depends on your application. But, as we are using encryption for communicating often, it is better to use Encoding that is more compatible with communication systems. For example, Base64 is one of the popular encodings used for encryption schemes(either Symmetric or Asymmetric).


text:
Q: Is there a way to reuse aggregate steps? I have a graph database storing different types of entities and I am building an API to fetch entities from the graph. It is however a bit more complicated since for each type of entity there is a set of rules that are used for fetching related entities as well as the original.
To do this I used an aggregate step to aggregate all related entities that I am fetching into a collection.
An added requirement is to fetch a batch of entities (and related entities). I was going to do this by changing the has step that is fetching entities to use P.within and map the aggregation to each of the found entities.
This works if I continue fetching a single entity, but if I want to fetch two then my result set will be correct for the first one but the result set for the second contains the results of the first one as well as its own results.
I think this is because second one will simply add to the aggregated collection from the first one since the aggregation key is the same.
I haven't found any way to clear the collection between the first and the second, nor any way to have a dynamic aggregation side effect key.
Code:

return graph.traversal().V()
    .hasLabel(ENTITY_LABEL)
    .has("entity_ref", P.within(entityRefs)) // entityRefs is a list of entities I am looking for
    .flatMap(
        __.aggregate("match")
          .sideEffect(
                // The logic that applies the rules lives here. It will add items to "match" collection.
          )
          .select("match")
          .fold()
    )
    .toStream()
    ...

The result should be a list of lists of entities where the first list of entities in the outer list contains results for the first entity in entityRefs, and the second list of entities contains results for the second entity in entityRefs.
Example:
I want to fetch the vertices for entity refs A and B and their related entities.
Let's say I expect the results to then be [[A, C], [B, D, E]], but I get the results [[A, C], [A, C, B, D, E]] (The second results contain the results from the first one).
Questions:

*

*Is there a way to clear the "match" collection after the selection?

*Is there a way to have dynamic side effect keys such that I create a collection for each entityRef?

*Is there perhaps a different way I can do this?

*Have I misidentified the problem?

EDIT:
This is an example that is a miniature version of the problem. The graph is setup like so:
g.addV('entity').property('id',1).property('type', 'customer').as('1').
  addV('entity').property('id',2).property('type', 'email').as('2').
  addV('entity').property('id',6).property('type', 'customer').as('6').
  addV('entity').property('id',3).property('type', 'product').as('3').
  addV('entity').property('id',4).property('type', 'subLocation').as('4').
  addV('entity').property('id',7).property('type', 'location').as('7').
  addV('entity').property('id',5).property('type', 'productGroup').as('5').
  addE('AKA').from('1').to('2').
  addE('AKA').from('2').to('6').
  addE('HOSTED_AT').from('3').to('4').
  addE('LOCATED_AT').from('4').to('7').
  addE('PART_OF').from('3').to('5').iterate()

I want to fetch a batch of entities, given their ids and fetch related entities. Which related entities should be returned is a function of the type of the original entity.
My current query is like this (slightly modified for this example):
g.V().
    hasLabel('entity').
    has('id', P.within(1,3)).
    flatMap(
        aggregate('match').
        sideEffect(
            choose(values('type')).
                option('customer',
                    both('AKA').
                        has('type', P.within('email', 'phone')).
                        sideEffect(
                            has('type', 'email').
                                aggregate('match')).
                        both('AKA').
                        has('type', 'customer').
                        aggregate('match')).
                option('product',
                    bothE('HOSTED_AT', 'PART_OF').
                        choose(label()).
                        option('PART_OF',
                            bothV().
                                has('type', P.eq('productGroup')).
                                aggregate('match')).
                        option('HOSTED_AT',
                            bothV().
                                has('type', P.eq('subLocation')).
                                aggregate('match').
                                both('LOCATED_AT').
                                has('type', P.eq('location')).
                                aggregate('match')))
        ).
        select('match').
        unfold().
        dedup().
        values('id').
        fold()
    ).
    toList()

If I only fetch for one entity i get correct results. For id: 1 I get [1,2,6] and for id: 3 I get [3,5,4,7]. However when i fetch for both I get:
==>[3,5,4,7]
==>[3,5,4,7,1,2,6]

The first result is correct, but the second contains the results for both ids.

A: You can leverage the (not too well documented to be honest but seemingly powerful traversal step) group().by(key).by(value).
That way you can drop the aggregate() side effect step that is causing you trouble. As an alternative to collect multiple vertices matching some traversal into a list I used union().
An example that uses the graph you posted(I only included the Customer option for brevity):
g.V().
    hasLabel('entity').
    has('id', P.within(1,3)).
    <String, List<Entity>>group()
      .by("id")
      .by(choose(values("type"))
        .option('customer', union(
          identity(),
          both('AKA').has('type', 'email'),
          both('AKA').has('type', within('email', 'phone')).both('AKA').has('type', 'customer'))
          .map((traversal) -> new Entity(traversal.get())) //Or whatever business class you have
          .fold() //This is important to collect all 3 paths in the union together
        .option('product', union()))
     .next()

This traversal has the obvious drawback of the code being a bit more verbose. It declares it will step over the 'AKA' from a Customer twice. Your traversal only declared it once.
It does however keep the by(value) part of the group() step separate between different keys. Which is what we wanted.


text:
Q: Kmeans unique words taggs I want to obtain a list of unique taggs from K-Means clustering. I have the following code:
def cluster_tagging(variable_a_taggear):

document = result[variable_a_taggear]
vectorizer = TfidfVectorizer(ngram_range=(1, 5))

X = vectorizer.fit_transform(document)

true_k = 180
puntos2= true_k

if model_setting == 'MiniBatchKMeans':
    #model = MiniBatchKMeans(n_clusters=true_k, init='k-means++', max_iter=1000, n_init=1)
    pass
elif model_setting == 'KMeans':
    model = KMeans(n_clusters=true_k, init='k-means++', max_iter=10000000, n_init=1)

model.fit(X)

order_centroids = model.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
#print(terms[:8])

cluster_ = []
key_ = []
ID = []

cluster_col = 'Cluster_%s'%(variable_a_taggear)
keywords_col = 'Keywords_%s'%(variable_a_taggear)
word_cloud = pd.DataFrame(columns=[cluster_col, keywords_col])

for i in range(puntos2):
    print('Cluster %s:' % (i))
    cluster_.append(i)
    key_1 = []
    key_1 = list(set(key_1))
    key_.append(key_1)

    for ind in order_centroids[i, :8]:
        print('%s' % terms[ind])
        terms_ = terms[ind]
        key_1.append(terms_)

print('first key_', key_)
info = {cluster_col:cluster_,keywords_col:key_}

word_cloud = pd.DataFrame(info)
word_cloud.head()

#print('Prediction')

predicted = model.predict(vectorizer.transform(document))
lst2 = result['Ticket ID']
predictions = pd.DataFrame(list(zip(predicted, lst2)), columns =[cluster_col, 'Ticket ID'])

#predictions = pd.DataFrame(predicted,result['Ticket ID'])
predictions.columns = [cluster_col, 'Ticket ID']
#print(predictions)

resultado = pd.merge(predictions, word_cloud, left_on=cluster_col, right_on=cluster_col, how='inner')
print(resultado.head())
return resultado

As you can observe with n-grams I obtain repeated words as part of different n-grams. For example, for one cluster I have the following taggs: [['fecha iniciar', 'iniciar', 'modificar fecha iniciar cc', 'proceder modificar fecha iniciar', 'proceder modificar fecha iniciar cc', 'fecha iniciar cc', 'iniciar cc', 'fecha'] How can I obtain a list of unique words for each cluster?
Thanks

A: Question: How can I obtain a list of unique words for each cluster?
You can use nltk to separate words within a sentence and numpy.unique to get unique values within an array.
import numpy as np
from nltk.tokenize import word_tokenize

cluster_tags  = ['fecha iniciar', 'iniciar', ..., 'fecha']
one_string = ' '.join(cluster_tags)
np.unique(word_tokenize(one_string))

If you are certain that all words are always separated by a clean space ' ', you can simply split them...
np.unique(' '.join(cluster_tags).split())

Bonus tip:
If you want, you could count the frequency of each word.
# See answer by Max Malysh: https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists
from collections import Counter
from pandas.core.common import flatten

tokenized = [word_tokenize(text) for text in cluster_tags]
Counter(flatten(tokenized))


text:
Q: What does the filtered column of a EXPLAIN'ed query mean in MySQL? mysql> EXPLAIN EXTENDED SELECT * FROM table WHERE column = 1 LIMIT 10;
+----+-------------+----------+------+---------------+--------------+---------+-------+--------+----------+-------+
| id | select_type | table    | type | possible_keys | key          | key_len | ref   | rows   | filtered | Extra |
+----+-------------+----------+------+---------------+--------------+---------+-------+--------+----------+-------+
|  1 | SIMPLE      | table    | ref  | column        | column       | 1       | const | 341878 |   100.00 |       |
+----+-------------+----------+------+---------------+--------------+---------+-------+--------+----------+-------+
1 row in set, 1 warning (0.00 sec)

What does the filtered column mean, and should the number be high or low?  Yes, I've read the docs, but I don't quite understand what the number indicates or what values are considered desirable.

A: The filtered column is an estimated percentage that specifies the number of rows that will be joined with the previous table. In your case it's 100%, i.e. all rows.
The rows, as you presumably know, is an estimation of the number of rows examined by the query, so rows x filtered / 100 will be the number of joins that have to be made (the number of rows left after applying the table condition).
For additional info, see What's New in MySQL Optimizer - What's new in MySQL Query Optimizer (slide 10).
EDIT:
There is an Appendix in the High performance MySQL (2nd edition) book which suggests that the optimizer currently uses this estimate (filtered) only for the ALL, index, range and index_merge access methods.


text:
Q: GWT Mobile Framework for Windows Phone 7 I am trying to find a suitable GWT Mobile Framework to use with Windows Phone 7. All the ones I have found rely on webkit browsers i.e. GwtMobile,M-Gwt.
Anyone know of a Mobile GWT Framework that works with the IE on WP7?

A: There are currently no HTML mobile frameworks that support the WP7 metro theme. However, some of the iOS themed frameworks do support WP7. The latest versions of jQuery Mobile work just fine on the WP7 browser, and there is a GWT / jWueryMobile framework available called jqm4gwt.


text:
Q: When I add more than one states to an  in a state-list drawable, it stops working. Why? What I want:
An ImageView with a transparent background. When it is clicked, its background should turn blue, and should remain blue until something else is clicked. I am using state-list drawable for it.
What is happening:
The code is given as follows. The problem is that the background does turn blue, but it does not remain blue. So I thought it is because android:state_pressed just represents the moment when the widget is being clicked. So I also added android:state_selected="true" to button_state_list_drawable.xml right after android:state_pressed="true". What happened then is that the background stopped turning blue even when the imageview is being clicked.
How do I fix this?
ImageView defined in XML like this:
<ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fragment_imageView"
        android:src="@drawable/ic_photo"
        android:background="@drawable/button_state_list_drawable"
        android:clickable="true" />

The button_state_list_drawable.xml is:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:drawable="@drawable/button_pressed_state_drawable"
        android:state_pressed="true"
        android:state_selected="true" />

    <item android:drawable="@drawable/button_enabled_state_drawable" />

</selector>

The button_pressed_state_drawable.xml is:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <size android:width="50dp"
        android:height="50dp" />

    <padding android:left="25dp"
        android:right="25dp"
        android:top="25dp"
        android:bottom="25dp" />

    <stroke android:color="#fff"
        android:width="1dp" />

    <solid android:color="#1aafd0" />

</shape>

The button_enabled_state_drawable.xml is:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <size android:width="50dp"
        android:height="50dp" />

    <padding android:left="25dp"
        android:right="25dp"
        android:top="25dp"
        android:bottom="25dp" />

    <stroke android:color="#fff"
        android:width="1dp" />

    <solid android:color="@android:color/transparent" />

</shape>

A: I don´t know if this is the solution, but I have to show some code. You haven´t added a default state to your selector and I can´t see your selected state (you wrote it in yur question, but you haven´t posted it). It must be something like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

   <item android:drawable="@drawable/button_enabled_state_drawable"
        android:state_enabled="true" />

   <item android:drawable="@drawable/button_pressed_state_drawable"
        android:state_pressed="true" />

    <item android:drawable="@drawable/your_selected_state_drawable"
        android:state_selected="true" />

    <item android:drawable="@drawable/your_button_default_drawable"/>

</selector>

And I think you have to add programmatically the selected state (I´m not sure for this or if it does it automatically)
yourImageView.setOnClickListener(new OnClickListener(){
      @Override
  public void onClick(View v){

        if(yourImageView.isSelected()){
            yourImageView.setSelected(false);
          }else{
            yourImageView.setSelected(true);
          }
    }
});

A: I recently had this problem, and this is what I did.
In your button_state_list_drawable.xml, add this somewhere before you default state item:
<item android:drawable="@drawable/button_pressed_state_drawable"
        android:state_selected="true"
        android:state_pressed="false" />

Also remove android:state_selected="true" from your state_pressed item.
Then in the beginning of your click listener for the ImageView, write
yourImageView.setSelected(true);

This had solved my problem. Hope it helps you.


text:
Q: Unity3D Webcam Autofocus Callback? I want to take a picture from camera using Unity. Taking picture itself is not a big deal but I want more accurate one using autofocus callback method like in Android (onAutoFocus(boolean success, Camera camera)) So I can take a picture if callback returns success true. Is there any way to do it in Unity or I need some plugin for that? If there is one can somebody reference to it? Thanks a lot!

A: There is a plugin called Camera Capture Kit available on the assetstore that seems to be able to do what you want. We used the code to make theese features available on both Android as well as iPhone.
    https://www.assetstore.unity3d.com/en/#!/content/56673

Camera Capture Kit comes with a plug-n-play camera app which enables Auto-focus - you can set the autofocus mode by calling .
CameraCapture.UnitySetFocusMode( webCamTextureReferance, FocusModes.Autofocus );

That will represent AVCaptureFocusModeAutoFocus and you should be able to trigger a callback for the focus event yourself by adding a piece of code like this in the function initCapture in the file Assets/Tastybits/Native/iOS/CameraCapture.mm :
[camDevice addObserver:self forKeyPath:@"adjustingFocus" options:flags context:nil];

Now, Camera Capture Kit doesn't give you a callback when focus is being done on iOS so you will have to add it yourself and calling back to unity yourself using SendMessage.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if( [keyPath isEqualToString:@"adjustingFocus"] ){
    BOOL adjustingFocus = [ [change objectForKey:NSKeyValueChangeNewKey] isEqualToNumber:[NSNumber numberWithInt:1] ];
    NSLog(@"Is adjusting focus? %@", adjustingFocus ? @"YES" : @"NO" );
    if(adjustingFocus)
      UnitySendMessage( "FocusController", "FocusChanged", "1" );
    else
      UnitySendMessage( "FocusController", "FocusChanged", "0" );
}}


text:
Q: custom android button look and feel
The two buttons in the bottom of the screen are Scan and Leads, if we click on any button, the view of the button is visible like pressed as u see in image for lead button, this view will change according to the button click, and here i am unable to create that kind of look and feel for buttons. please provide me the sample code or suggest me to achieve this look and feel.
Thanking you

A: <?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/button_some_name_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/button_some_name_default"/>

</selector>

Have this in your /drawable/ folder as button_some_name.xml
Then have the button_some_name_pressed.png & button_some_name_pressed.png in your drawable-ldpi drawable-mdpi etc
There are other states to consider as well
ref: http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

A: this is custom button .A custom button is very easy to create, you just have to make different images for the different state of the button  and place it into your res/drawable folder.
below link contain the step by step description for creating this:
http://androidemulator.wordpress.com/2011/11/03/creating-custom-buttons-in-android-applications/


text:
Q: How to throttle the amount of request to an API? There is a crm system, which provides webhooks to notify about some events happening in it (for instance, user creates some entity or moves it to the next 'status'). At some event a webhook triggers my script, that creates a new entity in this crm system using it's API. The system's API has a rate limit – 7 request per second. By violating this rule the access to the API may be restricted for the account for some time.
The problem is, that if user changes 'status' of 1000 entities the webhook triggers my script 1000 times, so it calls the API 1000 times and that may violate the rate limit. Is there any way to temporarily 'store' all requests that came from the webhook and then launch the script no more than n-times per second?
The script is written in php and is located on my Apache server now, but later it may be put on client's server or somewhere else.
I've read about Rabbit MQ and Kafka. But it seems to be an overkill for this task. Or maybe it's OK? I just don't have enough experience with these systems.
Any help would be appreciated.