text:
Q: Yank words separated only by periods I have a line like this in a file

<echo>The app vendor is... app.server.name</echo>

With the cursor over the 'r' in 'server', how can I yank 'app.server.name' without going into visual mode, or without having to guess the number of words to yank.
yiw will only yank the word inbetween the periods.

A: Byt<

B (to get you to the beginning of the punctuated word)
yt< (to yank forward, up to but excluding the "<").

A: 1. Quick and dirty: include dots in 'word' matching
 :se iskeyword+=46

Now yiw will do what you want :)
2. Proper solution: define a text object
As Benoit mentions, the above might be side effects that you don't want1
In an earlier answer ( vim: select inside dots) I describe how to definte a text object to select inside dots (shown below). You could use that as a basis to define a similar text object that selects words including dots:
This doesn't require any changes to the iskeyword setting :)

xnoremap <silent>.  f.oT.o
xnoremap <silent>a. f.oF.o
xnoremap <silent>i. t.oT.o

onoremap <silent>.  :<C-u>exec 'normal v' . v:count1 . '.'<CR>
onoremap <silent>a. :<C-u>exec 'normal v' . v:count1 . 'a.'<CR>
onoremap <silent>i. :<C-u>exec 'normal v' . v:count1 . 'i.'<CR>

Examples for the following buffer contents (cursor on the letter w):
someobject.some-property-with-hyphens.SUB.otherproperty

*

*v. selects some-property-with-hyphens. in visual mode

*va. selects .some-property-with-hyphens. in visual mode

*vi. selects some-property-with-hyphens in visual mode

  Motions can be chained and accept a count:

*

*v.. selects some-property-with-hyphens.SUB. in visual mode

*v2. also selects some-property-with-hyphens.SUB. in visual mode

*v2a. selects .some-property-with-hyphens.SUB. in visual mode

*v2i. selects some-property-with-hyphens.SUB in visual mode

  You can use the operators as operators to any editing command:

*

*d. results in someobject.SUB.otherproperty

*ci.shortname results in someobject.shortname.SUB.otherproperty

*c2.get(" results in someobject.get("otherproperty
It doesn't matter where in a 'dot-delimited-identifier' the cursor is to start with. Note that for convenience, all visual mode mappings position the cursor at the end of the selection (so you can do continue extending the selection by e.g. % and other motions).

1 see a bit of background information here: vim: select inside dots


text:
Q: Why do the asymptotes appear in the graph of $u$ against $v$ for the thin lens equation and what does this represent? For the thin lens equation,
$$\frac{1}{v} = \frac{1}{u}+\frac{1}{f}$$ when $u$ and $v$ are plotted to determine $f$ you get a graph like this. Why do the asymptotes appear and why can we use them as a way to find $f$? Can the $1/f$ part of the equation be thought of as translating the graph? Furthermore, what would this then actually represent in physical terms?

A:
Why do the asymptotes appear and why can we use them as a way to find $f$?

First Why asymptotes appear?
$$\frac{1}{y}=\frac{1}{x}+\frac{1}{f}$$
That's the same thing i.e. the lens formula.
$$\Rightarrow y=\frac{xf}{x+f}, $$
$$\lim_{x\rightarrow -f}y=+\infty$$
or $$\lim_{u\rightarrow -f}v=+\infty$$
What does means is basically if you set the location of the object at focal length, you get the image at infinity.
Now Why we use this? First, it's not the only way to determine focal length but It's showing you the way to find focal length by just watching the image and vary the object locations.

Can the $1/f$ part of the equation be thought of as translating the graph?

No! Just plot the graph, It's not translating rather It's changing the asymptotes.

Furthermore, what would this then actually represent in physical terms?

It's the inverse of focal length that's all. You can call it the Power of lense.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pyside: detecting single and double clicks on a QWidget I am building a UI in Maya that when a button is clicked will generate a bunch of horizontal layouts containing widgets inside of a QScrollArea.  I am trying to figure out how to get each row to recognize a single / double click.  When a particular row is clicked, I would like it to return the widget that was clicked so that I can do something with it. I am thinking I will probably have to attach a container widget to the row layouts to recognize the mouse clicks?
I have figured out how in general to recognize single and double clicks and have it print something - but I am having a hard time figuring out how to link that to a widget.

A: Below is a demo that should do most of what you want. The key method is childAt, which gets the child widget at a given point. Obviously, for this to work, all of the target widgets must be descendants of the widget that handles the events. The lastpos check is used to detect a true click-event (i.e. a mouse-press and -release on the same widget).
import sys
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.scroll = QtGui.QScrollArea()
        self.scroll.setWidgetResizable(True)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.scroll)
        widget = QtGui.QWidget()
        layout = QtGui.QVBoxLayout(widget)
        for text in 'red green yellow purple orange blue'.split():
            item = QtGui.QFrame()
            item.setObjectName(text)
            item.setStyleSheet('background-color: %s' % text)
            layout.addWidget(item)
        self.scroll.setWidget(widget)
        self._lastpos = None

    def mousePressEvent(self, event):
        self._lastpos = event.pos()

    def mouseReleaseEvent(self, event):
        widget = self.childAt(event.pos())
        if (widget is not None and self._lastpos is not None and
            widget is self.childAt(self._lastpos)):
            if widget.objectName():
                print('click:', widget.objectName())
        self._lastpos = None

    def mouseDoubleClickEvent(self, event):
        widget = self.childAt(event.pos())
        if widget is not None and widget.objectName():
            print('dblclick:', widget.objectName())

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 300, 400)
    window.show()
    sys.exit(app.exec_())


text:
Q: Child browser plugin vs navigator.app.loadurl I want to know what is major difference between Childbrowser plugin and navigator.app.loadurl. There is any performance variance among these two?
To my understanding the Childbrowser plugin is native for both IOS and android. Anything else
Childbrowser:
window.plugins.childBrowser.showWebPage("http://www.google.com", { showLocationBar: false });

Navigator:
navigator.app.loadUrl('http://www.google.com', { openExternal:true } );

A: The ChildBrowser plugin allows you a bit more fine grained control of the browser. For instance you get events when the location changes in the child browser which is useful for doing things like oauth.
Other than that the code is nearly identical on Android which is the only platform that supports navigator.app.loadUrl().

A: try it
Link

function openUrlInBlankBrowser()
{
    navigator.app.loadUrl('http://www.google.com', { openExternal:true } );
}


text:
Q: I am trying to run node.js, how do I resolve "Cannot find module" error? I am trying to run node.js on OS X Terminal (10.6.8 if anyone cares) but whenever I type in:
node server.js

I receive this error message:
module.js:338
    throw err;
          ^
Error: Cannot find module  '/Work/Mass_Exchange/front_end_dev/MXWeb/server.js'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Anybody know what's causing it and how I can fix it?

A: My guess would be you are not in the same folder in the terminal, cause I wouldn't expect your code to call upon itself, but couldn't tell with not even a small code snippet.


text:
Q: Openvpn password authentication I am trying to connect openvpn windows client to openvpn server running on ubuntu. The VPN works fine when using 'certificate only' authentication, . But when trying to authenticate using below script, I am getting below error on the client:
Mon Jan 21 14:59:07 2013 SENT CONTROL [server]: 'PUSH_REQUEST' (status=1)
Mon Jan 21 14:59:07 2013 AUTH: Received AUTH_FAILED control message
Mon Jan 21 14:59:07 2013 TCP/UDP: Closing socket
Mon Jan 21 14:59:07 2013 SIGTERM[soft,auth-failure] received, process exiting

The vpn_user.sh is an executable and accessible by the server.conf file.
Any assistance is appreciated.

here is the authenticating script:
#!/bin/sh
#vpn_user.sh

ALLOWED_USER="user1"

ALLOWED_PASS="password1"
echo "$username"
echo "$password"

if ["$username"=="$ALLOWED_USER"] && ["$password"=="$ALLOWED_PASS"]
    then exit 0
fi

exit 1

server configuration:
#server.conf
port 1194
proto udp
dev tap0

client-cert-not-required
auth-user-pass-verify vpn_user.sh via-env
script-security 3
username-as-common-name
tmp-dir /dev/shm

ca ca.crt
cert server.crt
key server.key  # This file should be kept secret
dh dh1024.pem
ifconfig-pool-persist ipp.txt
server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100
client-to-client
duplicate-cn
keepalive 10 120
comp-lzo
persist-key
persist-tun
status openvpn-status.log
log         openvpn.log
verb 3

client configuration
client
dev tap
proto udp
remote 10.xx.xx.xx 1194
auth-user-pass
resolv-retry infinite
persist-key
persist-tun
ca ca.crt
dh dh1024.pem
comp-lzo
verb 3

A: 1. The script you have entered has missing spaces in if line, it should be:
if [ "$username" == "$ALLOWED_USER" ] && [ "$password" == "$ALLOWED_PASS" ]
What shows up when script is executed? Here are my examples of testing:
# username=user1 password=password1 ./vpn_user.sh && echo "authentication OK" || echo "Authentication failed"
user1
password1
authentication OK

# username=user1 password=wrong-pass ./vpn_user.sh && echo "authentication OK" || echo "Authentication failed"**
user1
wrong-pass
Authentication failed

2. Also check your server.conf. You may need to put the full path to your script
This is the important section:
auth-user-pass-verify /full/path/to/vpn_user.sh via-env
script-security 3

3. Chroot-ed execution may cause difficulties.
If you run openvpn under chroot - then your script needs to be visible under chroot-ed process, also shell for script needs to be available, together with any needed libraries. In such case you need to chroot and test execution of script under chroot.
This can be tricky and a quick solution for this for me was to write own small program and compile is (as static - no need for external libs).
Exact instructions, sorce code, compile instruction, etc. - should be still available at:
http://openbsdsupport.org/openvpn-on-openbsd.html
or even better - try to go directly to the related section:
http://openbsdsupport.org/openvpn-on-openbsd.html#AuthenticationVariant1simple
4. Openvpn clients also needs to be configured to use password authentication.
Verify the option in client's config client-config.ovpn
password auth-user-pass

A: root@myserver:/var/www# cat /tmp/quickAuth.sh
#!/bin/bash
#vpn_user.sh

ALLOWED_USER="user"
ALLOWED_PASS="password"

echo "$username"
echo "$password"
echo $ALLOWED_USER
echo $ALLOWED_PASS

if [[ "$username" == "$ALLOWED_USER"  && "$password"="$ALLOWED_PASS" ]]
then
 exit 0
else
  exit 1
fi

Client config
client
dev tun
proto udp
remote remote ip server 1194(server port)
resolv-retry infinite
nobind
user nobody
group nogroup
persist-key
persist-tun
mute-replay-warnings
ca ca.crt
cert client.crt
key client.key
ns-cert-type server
auth-user-pass
comp-lzo
route xxx.xxx.xxx.xxx  255.255.255.255 the ip that i want to route throw the openvpn(if default was not made)
verb 3

The prb is with sh script


text:
Q: Convert NLCD 2016 Raster to Vector My goal is to create a .shp file in CRS EPSG 4326 - WGS 84 of land cover data for several counties in California. My idea is to use the NLCD 2016 dataset in QGIS to convert it into the desired shapefile. However, when I try to set all layers to WGS 84 (simply by clicking properties->source->and changing the drop down CRS (ignoring the warning that this will not change the original data)), the resulting image looks like this:

How can I get the NLCD data to overlay the OpenStreet basemap (set to WGS 84 in same manner as NLCD raster) correctly?

A: Setting CRS of a layer just by its properties does not reproject the layer. It does not change the underlying data (as the warning suggested, which you ignored). For example an XY point -8505413,3187458 (EPSG:3857) will not be changed to EPSG:4326 (WGS 84) equivalent (~ -75.48,26.66) but the QGIS will think that -8505413,3187458 is in EPSG:4326.
To reproject the NLCD Raster (change actual data), use GDAL WARP in QGIS.


text:
Q: $C$-parity in $\pi^0\pi^+\pi^-$ system I'm studying the conservation of the quantum number in the decay $\omega^0\rightarrow\pi^0\pi^+\pi^-$. Since
$P(\omega^0)=-1$
and
$P(\pi^0\pi^+\pi^-)=P(\pi^0)P(\pi^+)P(\pi^-)(-1)^{L_{+-}}(-1)^{L_{(+-)0}}=(-1)(-1)^{L_{+-}}(-1)^{L_{(+-)0}}$
To conserve parity $L_{+-}=L_{(+-)0}=1$
But to conserve C-parity
$C(\omega^0)=-1$
and
$C(\pi^0\pi^+\pi^-)=C(\pi^0)C(\pi^+\pi^-)(-1)^{L_{(+-)0}}=(-1)^{L_{(+-)0}}(-1)^{L_{+-}}$
since $C(\pi^0)=1$. Therefore if $L_{+-}=L_{(+-)0}=1$, C-parity is not conserved.
What am I missing?

A: I think the problem with your would-be inconsistency (its a strong decay!) is the angular momentum factor you mysteriously inserted in the formula composing Cs.
Composing parity entails the spherical harmonics whose p-waves have negative parity, and they are two of them, as you soundly determined. (In fact, as a mental prop, you may consider the decay as a sequence, $\omega\to \rho^0\pi^0\to 3\pi$, the last step of which is also p-wave. Recall $J^{PC}: ~~~\omega ~~1^{--}; ~~ \rho^0 ~~1^{--}; ~~ \pi^0 ~~O^{-+}$.  )
But the composition of the two meaningful (neutral particle) Cs is
$$
C(\omega)= C(\rho^0)C(\pi^0)= (-)(+)= (-),
$$
consistent. Recall, $C(\rho^0)\equiv C(\pi^+\pi^-)$, as the $\rho^0$ is a notional placeholder for the $\pi^+\pi^-$ p-wave eigenstate of C. There is no notional charge conjugation inserting the relative angular momentum $L_{(+-)0}$ between two charged particle constituents here.

Edit on comment : It is an XY problem... The WP point is correct for the C of a particle-antiparticle pair, and the $L_{+-}$ reminds you of the antisymmetry you already incorporated into the  $C=-$  of the placeholder $\rho^0$, which I put in for $\pi^+\pi^-$, to focus your thinking; nobody claimed you have to go through this channel; only that it easily summarizes the math.

*

*But there is no such  $(-)^L$ factor, as you wrongly inferred, for combining two neutral particles with well-defined C!

So, $L_{(+-)0}$ cannot and should not appear in the total C formula  that you invented out of whole cloth: it is pointless and wrong. Most good texts explain this.


text:
Q: JLabels with JTextFields in LinkedHashMap I have a program that at one part demands a user to determine the amount of days per week in 40 weeks (def = 5).
The user firstly fills in the amount of days the 40 weeks will have, to then set the days per week.
Now, I have both JLabel (KEY) and JTextfield (VALUE) stored in a LinkedHashMap,
  LinkedHashMap<JLabel, JTextField> weeksMap = new LinkedHashMap<JLabel,JTextField>();
  for (int i=1; i<=40; i++)  {
      JLabel weekL = new JLabel("Week "+i);
      JTextField weekF = new JTextField(10);
      weekF.setText("5");
            //SetWeekAction sWA = new SetWeekAction(mainPane, weekL, weekF);
            //weekF.addActionListener(sWA);
      weeksMap.put((weekL), weekF);
  }

and they will be added to the panel after user sets the total amount of days in the certain year.
EDIT - NOTE: the reason for having these two in a HashMap is I cannot create elements on lick, otherwise I could create infinite labels and text fields and I do not wish to work with buttonpressed=true or such. I need both text fields and labels 'prepared' before the 'click' happens.
 for (Map.Entry<JLabel, JTextField> entry : weeksMap.entrySet()) {
        index++;
        weeksPane.add(entry.getKey());
        weeksPane.add(entry.getValue());
 }

The GUI view

How do I get the text field of for example 'Week 23'? The for loop goes through the List and adds the Objects correctly, but I have no reference to that certain object anymore.

A: You can use one ArrayList for storing text field and label text
ArrayList<JTextField> weeks = new ArrayList<JTextField>();

for (int i=1; i<=40; i++)  {
    JTextField weekF = new JTextField(10);
    weekF.setName("Week "+i);
    weekF.setText("5");
    JLabel weekL = new JLabel(weekF.getName());
    weekL.setLabelFor(weekF);
    weeks.put(weekF);
}

On update event you can invalidate and redraw weeks panel

A: I can think of one simple solution of making two separate LinkedHashMap one as LinkedHashMap < integer, JLabel> and another as LinkedHashMap
Now in your loop you can add value in both the LinkedHashMap using the int value from loop as key for  JLabel and JTextField while storing them in your both LinkedHashMap.
 Since both JLabel and JTextField are now attached with the integer value according to the loop number in which they were created you can access them using those integer value.
Hope this can solve your problem.


text:
Q: How to prevent an Interface from implementing in inherited class? interface I
class A implements I
class B extends A
class C extends A
class D extends A
class E extends A

What can I do so that only class D doesnot get the methods of I.
I am currently thinking to override all the methods of 'I' in D with no body.
Am I thinking in the right direction or is there a better way?
Edit: D only doesnot want the methods contained in interface I. Rest of A's methods are inherited.
A is the base class. interface I is the interface for ordering videos B,C,E are users with different privileges and D is the admin.
The admins can not order videos so donot need the methods carried by the interface.

A: You probably want to rethink your design. If D extends A then D should do everything A can, like implementing the interface I. This is the basis of the very important Liskov Substitution Principle in OOP programming.
You can rework your design to still share the relevant code while retaining logical inheritance:
    A
   /|
  D A' implements I
   /|\
  B C E

It might also be possible that (as @OliCharlesworth pointed out) a solution using composition might be more useful. It depends on the specific case, but if B,C,D and E use A rather than that they are an A composition is more appropriate.

A: If A implements I, then any user of A or any of A's subclasses should be able to expect that the methods of I are implemented.  It is part of A's "contract" with the rest of the classes in the program.
For D to inherit from A, it should be a "special case" of A, and all of the functionality defined by A should be implemented.  Inheritance is necessarily an "additive" tool; you get all of what is in the base class, and can alter or add things in the subclass.
You say you want to subtract some things -- that is contrary to object-oriented programming, and contrary to the way inheritance (and implements) is implemented in the language.
So I think the best answer is "Yes, there's a better way."  We can't tell what it is with only this much information

A: I would accomplish this as follows:
interface I
class superClassA
class A extends superClassA implements I
class B extends superClassA implements I
class C extends superClassA implements I
class D extends superClassA
class E extends superClassA implements I

which is the same as:
interface I
class superClassA
class A extends superClassA implements I
class B extends A
class C extends A
class D extends superClassA
class E extends A

A: You are probably looking to use something like the Adapter pattern., which can be used to hide or merge interfaces.

A: Working with java 8, you can just make the method in interface I a default method and override it in classes you want it implemented in but not overridden in class D, that should solve your issue.
And by the way the default method should not have anything in it's body for it to work properly


text:
Q: Predictions using a Keras Recurrent Neural Network - accuracy is always 1.0 TLDR: How do I use a Keras RNN to predict the next value in a sequence?

I have a list of sequential values. I want to feed them into a RNN to predict the next value in the sequence.
[ 0.43589744  0.44230769  0.49358974 ...,  0.71153846  0.70833333 0.69230769]

I'm using Keras to do this and can get a network with a decreasing loss but the accuracy is consistently 1.0. This is wrong. y_tests != model.predict(x_tests).
Epoch 0
1517/1517 [==============================] - 0s - loss: 0.0726 - acc: 1.0000 - val_loss: 0.0636 - val_acc: 1.0000
Epoch 1
1517/1517 [==============================] - 0s - loss: 0.0720 - acc: 1.0000 - val_loss: 0.0629 - val_acc: 1.0000
...

Here's my network.
model = Sequential()
model.add(SimpleRNN(1, 100))
model.add(Dense(100, 1, activation = "sigmoid"))
model.compile(loss="mean_squared_error", optimizer = "sgd")

I have tried a SimpleRNN, GRU and LSTM but have had no luck. Here is how the data is formatted.
# Current value
y_train = [[ 0.60576923] [ 0.64102564] [ 0.66025641] ..., [ 0.71153846] [ 0.70833333] [ 0.69230769]]

# Previous 10 values
x_train_10 = [
    [[ 0.65064103] [ 0.66346154] [ 0.66346154] ..., [ 0.72115385] [ 0.72435897] [ 0.71153846]] ...,
    [[ 0.66346154] [ 0.66346154] [ 0.67628205] ..., [ 0.72435897] [ 0.71153846] [ 0.70833333]]
]

# Previous value
x_train_1 = [[ 0.58333333] [ 0.60576923] [ 0.64102564] ...,  [ 0.72435897] [ 0.71153846] [ 0.70833333]]

# So here are the shapes...
y_train.shape    = (1895, 1)
x_train_10.shape = (1895, 10, 1)
x_train_1.shape  = (1895, 1)

Each element in x_train_10 is a list of the previous 10 values. I formatted it like this to follow Keras's documentation that recurrent layers take inputs of shape (nb_samples, timesteps, input_dim).
I have also tried using an Embedding layer with no luck. (This may be the wrong way to use it - I've only seen it used in classification not prediction).
model = Sequential()
model.add(Embedding(1, 30))
model.add(LSTM(30, 100))
...

pad_sequences also did not work.
x_train_1 = sequence.pad_sequences(x_train_1, maxlen = None, dtype = "float32")

I want to get the RNN working with this simple data/architecture so I can use it for more complex problems later.
Thanks :)

A: I posted a similar question on the Keras Github page and got a good answer.

lukedeo said that acc: 1.0000 means that both the true output and the predicted output are greater than 0.5 or vice versa. Instead, I should look at loss, or mse, to determine the accuracy of the model. This is because my network is a regression not a classifier/clusterer.
Root mean squared error is a good measure of accuracy. accuracy_percent = 1 - np.sqrt(mse)

fchollet (the Keras creator) elaborated by saying that "accuracy is not relevant at all for a regression problem."
When doing a classification problem, accuracy can be made relevant by setting class_mode to 'categorical' or 'binary' in model.comple(...) depending on the target (network output).

A: Try RMSProp as optimiser
model.compile(loss="mean_squared_error", optimizer = 'rmsprop')


text:
Q: In total.js is it possible to assign value to variables or save/use the index of a @{foreach...} inside a nested @{foreach...} inline in the HTML? for example is it possible to define/use an "item_index" in a similar example to this:

 @{foreach item in list}

@{item.title}:

  @{foreach content in item.contents}

@{content.name} is the @{index}th content of @{item.title}, and the @{item_index}th item in the list

  @{end}
 @{end}

is it possible to assign values like @{item_index = index} before going into the nested loop?

A: You can use R (short for repository) to store extra data.
This works:
@{foreach m in [1, 2, 3, 4]}
    @{R.index = index}
    @{foreach m2 in [10, 20, 30, 40]}

@{m2}, index: @{R.index}, index2: @{index}

    @{end}
@{end}

output:

10, index: 0, index2: 0

20, index: 0, index2: 1

30, index: 0, index2: 2

40, index: 0, index2: 3

10, index: 1, index2: 0

20, index: 1, index2: 1

30, index: 1, index2: 2

40, index: 1, index2: 3

10, index: 2, index2: 0

20, index: 2, index2: 1

30, index: 2, index2: 2

40, index: 2, index2: 3

10, index: 3, index2: 0

20, index: 3, index2: 1

30, index: 3, index2: 2

40, index: 3, index2: 3


text:
Q: How to convert IntPtr to InteropService.SafeHandle? From the answer provided here Can I choose a custom image for C# Windows Application Drag Drop functions?, why does the following line:
return new Cursor(CreateIconIndirect(ref tmp));

cause the compiler to emit this error:

The best overloaded method match for 'System.Windows.Input.Cursor.Cursor(string)' has some invalid arguments
      Argument 1: cannot convert from 'System.IntPtr' to 'System.Runtime.InteropService.SafeHandle'

and is there a way to fix it?

A: The basic issue here is that you are trying to use a code example meant for the Winforms API when you are actually using the WPF API. The Cursor class used in that code is System.Windows.Forms.Cursor, while the class you're using is actually System.Windows.Input.Cursor. They are completely different, including having completely different constructors.
The Winforms version will accept an IntPtr value, representing a handle to a native Windows cursor object. But the WPF class accepts only some existing .cur or .ani data, either via a Stream (the data itself) or a string instance (the name of a file…this can be a pack: scheme path, so you can use embedded resources if you like).
If you want to create a cursor from an image on the fly in WPF, you can either:

*

*Use the Winforms example but instead of trying to pass the cursor handle to the Cursor constructor, use additional native functions via interop to retrieve the cursor data, write it to an array, and then wrap the array in a MemoryStream that you can pass to the WPF Cursor constructor. Or,

*Use one of the WPF-specific solutions for creating a Cursor object from existing image data. For example, Custom cursor in WPF? (I particularly like this answer…there are several good ones there, though they all involve using GDI+ via the System.Drawing namespace at some point), or Rotating Cursor According to Rotated TextBox (again, uses GDI+).


text:
Q: SQL selection problems I am working with SQLite and I think I have a problem getting table ID, my table stores book categories, their images details here is a graphical representation of my table
| mSubCategory_id | mCategory_id_FK | mSubCategory_description | mSubCategory_image|
my problem is getting the ID field values, below is a query am using to match books in my sub Cateogory table with a certain Category, its working perfectly but I cannot seem to access value of id, I am getting the same value for id and mSubCateogory_id which in the actual sense is the value for mSubCateogory_id and not id below is the query am using:
    String sQuery = " SELECT "+mCategory_id+", "+mCategory_id_FK+", "+Constant.SUB_DESCRIPTION+
            ", "+mSubCategory_image+" FROM  "+CATEGORY_TABLE+
    " INNER JOIN "+SUB_CATEGORY_TABLE+" ON "+mCategory_id +" = " +mCategory_id_FK
   + " WHERE "+mCategory_id +" = ?";

    String[] args = new String[1];
    args[0] = String.valueOf(mtargetID);

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(sQuery, args);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            ExpandableCategoryItem mCateogory= new ExpandableCategoryItem();

            //I am getting the same value here whether I use
            //getString(0) or getString(1)
            mCateogory.setId(Integer.parseInt(cursor.getString(1)));
            mCateogory.setmDescription(cursor.getString(2));
            mCateogory.setmCategoryImgPath(cursor.getString(3));

            mCategoryImgPost.add(mCateogoryPost);
        } while (cursor.moveToNext());

A: String sQuery = " SELECT "+mCategory_id+", "+mCategory_id_FK+", "+Constant.SUB_DESCRIPTION+
 ", "+mSubCategory_image+" FROM  "+CATEGORY_TABLE+
        " INNER JOIN "+SUB_CATEGORY_TABLE+" ON "+mCategory_id +" = " +mCategory_id_FK
       + " WHERE "+mCategory_id +" = ?";

In the above query there are mCategory_id and mCategory_id_Fk columns which are probably the same. You need to replace either of them with with mSubCategory_id


text:
Q: AngularJS tabs acting weird I was wondering if some of you could lighten me and try to explain what I miss in this : http://plnkr.co/edit/opxB2Jfi0Xf0Tq1780vz?p=preview
Looks quite simple to me but does not work.
My code:

          {{item.name}}

        {{item.year}}

Thank you in advance!

A: modifications in script.js:
var app = angular.module('myApp', []);

app.controller('myCtrl', ['$scope', function ($scope) {
    $scope.data = [{
        name: "First",
        title: "oneTitle",
        description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
        year: "2013",
        img: "http://static.hdw.eweb4.com/media/wp_400/1/5/42735.jpg",
        thingy: 1
    }, {
        name: "third",
        title: "twoTitle",
        description: "Quisque pulvinar libero sed eros ornare",
        year: "2014",
        img: "http://static.hdw.eweb4.com/media/wp_400/1/1/8519.jpg",
        thingy: 2
    }, {
        name: "Second",
        title: "threeTitle",
        description: "Cras accumsan massa vitae tortor vehicula .",
        year: "2015",
        img: "http://static.hdw.eweb4.com/media/wp_400/1/5/43326.jpg",
        thingy: 3
    }, {
        name: "fourth",
        title: "FourTitle",
        description: "Suspendisse vitae mattis magna.",
        year: "2011",
        img: "http://static.hdw.eweb4.com/media/wp_400/1/5/42413.jpg",
        thingy: 4
    }];

  $scope.details = $scope.data[0];

  $scope.GetDetails = function(obj)
  {
    $scope.details = obj;
  }

}]
);

In HTML:

              {{item.name}}

          {{details.thingy}}

          {{details.name}}

          {{details.title}}

          {{details.description}}

          {{details.year}}

Basically second ng-repeat is not required


text:
Q: Get value from selected checkboxes (Checkbox array) I have a array of checkboxes, 33 in total.
Because the checkboxes are all over the page, it needs to be in an array (right?).
The code-behind looks like this:
CheckBox[] variableName = new CheckBox[33];

        variableName[0] = idCheckBox1;
        variableName[1] = idCheckBox1;
        variableName[2] = idCheckBox1;
        variableName[3] = idCheckBox1;

and so on...
ASP.NET:
<asp:CheckBox ID="idCheckBox1" runat="server" Value="1" />
<asp:CheckBox ID="idCheckBox2" runat="server" Value="2" />
...

The checkboxes are totally optional.
Now how do i get the value of the checked boxes only in a variable?

A: It does NOT need to be an array.
This is how you get all the CHECKED checkboxes in your form from the CodeBehind:
var names = formCollection.AllKeys.Where(c =>
                    c.StartsWith("idCheckBox") &&
                    formCollection.GetValue(c) != null &&
                    formCollection.GetValue(c).AttemptedValue == "1");


text:
Q: chrome command line flag for auto sharing system sound I am developing web automation of Zoom meeting (all the way from creation till joining and leaving thereon).
I have been able to complete the creation, joining and screen sharing automation.
I am using --auto-select-desktop-capture-source=MyTab flag to automatically share the desired tab. Up until here, its all working fine.
Where I am stuck is that the chrome tab gets shared without system sound.

I want to automatically share the screen/tab along with system sound / tab audio.
What is the appropriate chrome flag for sharing audio along with screen?


text:
Q: Magento 2 - Translations in custom module this is part of my

etc/adminhtml/system.xml

 <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
            <label>General Configuration</label>

this is part of my file translations dictionary

i18n/it_IT.csv

"General Configuration","Configurazioni generali"

Store > Configuration > Local language > Italiano

but i cannot translate admin string in system configuration

A: Simply user have english setting as local interface for admin. Change it to italiano and it works


text: Q: How to add pagination button dynamically using 3rd party API data? I am a new developer in web development and I am trying to create a simple game searcher web app using IGDB API. But I am not getting the point of how to dynamically add the page buttons. For example, If I search for Call of duty game there are many versions and the data that I get will be multiple, here how to implement the page number buttons. If the received data count is 40, how can I only display a certain amount on one page and remaining on the other and so on... Please help I'm stuck with this for a week now.


text:
Q: How to get three drop-down's data together in C# I would appreciate if anyone could help me here:
I had two dropdowns and added the third one (Category) in a C# report page, how to get the data of all dropdowns from sql server.
1st dropdown:   ddlReportType
2nd dropdown:   ddlGroup
3rd dropdown:   ddlcategory
below is my code:
  public void Reportquery()
    {
        switch (this.ddlReportType.SelectedValue)
        {
            case "1":
                //successfully Loaded
                switch (ddlGroup.SelectedValue)
                {
                    case "All":
                        Session["Select_Query"] = "Select ID, CONVERT(CHAR(10), SCAN_DATE, 111) SCAN_DATE,Substring(SUBSCRIBER,1,20) DEALER_ID," + " MSISDN,FILE_PATH,USERNAME, Category, 'File Uploaded' Report_Criteria  from UPLOAD where scan_date between'" + cldrFrom.SelectedValue + "' and '" + cldrTo.SelectedValue + "'";

                        Session["Count_Query"] = "Select Count(*) as Cnt from UPLOAD" + " where scan_date between'" + cldrFrom.SelectedValue + "' and '" + cldrTo.SelectedValue + "'";
                        break;
                    default:
                        Session["Select_Query"] = "Select ID, CONVERT(CHAR(10), SCAN_DATE, 111) SCAN_DATE,Substring(SUBSCRIBER,1,20) DEALER_ID," + " MSISDN,FILE_PATH,USERNAME,Category, 'File Uploaded' Report_Criteria  from UPLOAD  " + " where scan_date between'" + cldrFrom.SelectedValue + "' and '" + cldrTo.SelectedValue + "' and rtrim(ltrim(Subscriber)) ='" + ddlGroup.SelectedItem.Text.Trim() + "'";

                        Session["Count_Query"] = "Select Count(*) as Cnt from UPLOAD" + " where scan_date between'" + cldrFrom.SelectedValue + "' and '" + cldrTo.SelectedValue + "' and rtrim(ltrim(Subscriber)) ='" + ddlGroup.SelectedItem.Text.Trim() + "'";

                        break;
                }
                break;

            case "2":
                //Failed to laod
                switch (ddlGroup.SelectedValue)
                {
                    case "All":
                        Session["Select_Query"] = "Select Value as ID, CONVERT(CHAR(10), SCAN_DATE, 111) SCAN_DATE, SUBSCRIBER as Dealer_ID, " + " FileName as MSISDN,File_Path, username, Category, 'File Rejected' as Report_Criteria  from CRI_Rejected a, code_rejected b " + " where a.Rejection_Code=b.id  and scan_date between'" + cldrFrom.SelectedValue + "' and '" + cldrTo.SelectedValue + "'";

                        Session["Count_Query"] = "Select count(a.ID) as cnt  from CRI_Rejected a, code_rejected b " + " where a.Rejection_Code=b.id and scan_date between'" + cldrFrom.SelectedValue + "' and '" + cldrTo.SelectedValue + "'";
                        break;
                    default:
                        Session["Select_Query"] = "Select Value as ID, CONVERT(CHAR(10), SCAN_DATE, 111) SCAN_DATE, SUBSCRIBER as Dealer_ID, " + " FileName as MSISDN,File_Path, username,  Category, 'File Rejected' as Report_Criteria  from CRI_Rejected a, code_rejected b " + " where a.Rejection_Code=b.id  and scan_date between'" + cldrFrom.SelectedValue + "' and '" + cldrTo.SelectedValue + "'" + " and rtrim(ltrim(Subscriber)) ='" + ddlGroup.SelectedItem.Text.Trim() + "'";

                        Session["Count_Query"] = "select count(*) as cnt from CRI_Rejected where scan_date between'" + cldrFrom.SelectedValue + "' and '" + cldrTo.SelectedValue + "'" + " and rtrim(ltrim(Subscriber)) ='" + ddlGroup.SelectedItem.Text.Trim() + "'";

                        break;
                }
                break;
        }
    }

report page screenshot

A: Use a datasource and then bind it to the dropdownlist, be sure to set the datatext and dataavalue values. Its pretty simple, see here
https://www.aspsnippets.com/Articles/Bind-Fill-Populate-DropDownList-control-from-database-in-ASPNet-using-C-and-VBNet.aspx


text:
Q: Openfire server not saving chatroom to the ofMucRoom table I'm developing and iOS chat app and using openfire server. After successful research I managed to create a room. The room I'm creating is persistent and I can see that room listed in Group Chat tab in open fire and is also persistent. But when I open my mysql database I cant see any entry in the mucRoom table. Plus mucMember table is also empty.
Even using spark client I cant login to the room created as it always says Connecting... On the iOS side I get the response in xml as "Room Locked until configuration is confirmed".
In the openfire admin when I edit the newly created room and save it back again, it appears in db and I'm then able to send/receive msgs using Spark client.
What is the problem? Why openfire is not saving the room to db from its cache? Even there is no such setting in openfire. This is the major issue all where and I can't find a proper answer to it. Anybody with a solution?

A: Your iOS client response is telling you the issue.  A room's settings must be confirmed by the room creator.  Until that time, it is locked, and you will continue to see that message.  The process of room creation is outlined here.
My client application uses the iOS/OSX XMPPFramework, and my Openfire server is configured to create "Instant Rooms".  XMPPFramework makes room creation and confirmation extremely simple.  By adding XMPP Room delegate to a stream, you get a delegate callback when a user sends their presence to a room that does not exist yet.  At which point, you can confirm the room settings or modify them appropriately.
#pragma mark XMPPRoom Delegate

- (void)xmppRoomDidCreate:(XMPPRoom *)sender
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [self.xmppRoom configureRoomUsingOptions:nil]; //nil confirms the default settings
}

- (void)xmppRoomDidJoin:(XMPPRoom *)sender
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}

- (void)xmppRoomDidLeave:(XMPPRoom *)sender
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}

- (void)xmppRoom:(XMPPRoom *)sender occupantDidJoin:(XMPPJID *)occupantJID
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}

- (void)xmppRoom:(XMPPRoom *)sender occupantDidLeave:(XMPPJID *)occupantJID
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}

- (void)xmppRoom:(XMPPRoom *)sender didReceiveMessage:(XMPPMessage *)message fromOccupant:(XMPPJID *)occupantJID
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}

I have not looked into the details of when a room is persisted, but I have also noticed in my use case that there is a discrepancy in the rooms displayed in the admin page from what is in the database.


text:
Q: Does the electron spin interact with the gravitational field? I know that we can't envision the spin of an electron envision as something spinning (unless the electron has a non-stringlike spherical structure), but the spin does interact with an electric field because of its charge. Can't we say that it interacts with the gravitational field due to its mass?

A: Here is a simple minded answer: The electron is an elementary particle in the table of the standard model which is a quantum mechanical theory. A gravitational interaction where the spin could play a role would need the quantization of gravity, which is a matter under research and not finalized.
In effective quantization of gravity, the corresponding quantum mechanical particle, waiting a niche in a future standard model , is the graviton, hypothsized to have spin 2 and be zero mass.
An electron graviton interaction then  has the following Feynman diagram:

If the upper line one the left is an electron and the lower line descriptive of a charged mass, the electron interacts with a virtual photon with the electric field. The above is only the contribution from one type of diagram, a an exchange . Depending on the lower line's particulate structure more diagrams can contribute and also higher order ones. For a gravitational mass for the lower line on the right, the graviton would be the exchange particle.
The effect of spin comes in the matrix elements that describe the  wavefunctions to be integrated , so as to get the crossection.
In a similar way that one says that, given the appropriate boundary conditions, the electron's spin interacts with the electric field, one cans say that :given the appropriate constants and a quantization of gravity, the electron's spin interacts with the gravitational field.
Spin is part of the total mathematical description in calculating the wavefunction of the system, and enters through the conservation of angular momentum in allowing or forbidding some diagrams.
The basic numbers that should be kept in mind are the coupling constants at the vertices, where for photon the vertex is depressed by 1/137, but for a graviton by 6*10^-39, which makes any individual particle state interaction not accessible to experiment.


text:
Q: downloading a library in python3 env through conda I'm trying to download the spaCy library in a new python3 environment.
Here's what I have:
python3 -m venv .env
source .env/bin/activate
conda install -c conda-forge spacy
conda install -c conda-forge spacy-lookups-data
python3 -m spacy download en_core_web_sm

The error I got was: /Users/KerryChowChow/Dropbox/2019data_art/.env/bin/python3: No module named spacy
I have both python2.7 and python3 under the environment. Tried both python -m spacy download en_core_web_sm and python3 -m spacy download en_core_web_sm
Both resulted in the same error.
I think it's a location problem.
I have previously successfully downloaded spaCy via the command line conda install -c conda-forge spacy so spaCy must be SOMEWHERE.
Thanks!

A: Using Conda will not install things into the python virtual environment you created. If you'd like to make a conda virtual environment with a specific version of python and then install python packages into the conda environment you can do the following:
conda create -n .env python=x.x anaconda
source activate .env
conda install -n .env -c conda-forge spacy

If you'd like to just use your python virtual environment instead and install space there follow these steps (I will assume .env doesn't exist here for completeness).
python3 -m venv .env
source .env/bin/activate
pip3 install spacy

A: I used pip install and python3 instead and it worked!
python -m venv .env
source .env/bin/activate
pip install -U spacy
python -m spacy download en_core_web_sm

somehow, using conda install isn't working.


text:
Q: Using Generic Class Types in Generics I have the following code:
class Entity {
    id: number
}

class ChildEntity extends Entity {
    child_property: number;
}

class ChildEntity2 extends Entity {
    child_property_2: number;
}

class Data<T extends Entity> {
    protected entity: T
    static method() {
    }
}

class ChildData extends Data<ChildEntity> {
    childMethod() {
        this.entity.child_property = 1;
    }
}

class ChildData2 extends Data<ChildEntity2> {
    childMethod() {
        this.entity.child_property_2 = 1;
    }
}

function doStuffAndInstantiate(Input /* What should be the type here??? */ ) {
// function doStuffAndInstantiate<T extends Entity>(Input: new ()=> Data<T> ) { /* Error at Input.method() call: Property 'method' does not exist on type 'new () => Data '. */
// function doStuffAndInstantiate(Input: typeof Data ) { /* error at doStuffAndInstantiate(ChildData) call: 'ChildEntity' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Entity'. */
    Input.method();
    return new Data();
}

doStuffAndInstantiate(ChildData);
doStuffAndInstantiate(ChildData2);

What should be the type of Input argument of doStuffAndInstantiate? I've tried many ways with absolutely no success :(

A: What do the errors you got mean?
I think you're getting a little bit confused:

*

*function doStuffAndInstantiate<T extends Entity>(Input: new ()=> Data<T>)
Doesnt compile because it's misusing the keyword new. new in typescript is used to create instances of a class as you're doing in your function implementation. As far as my understanding goes, new doesn't make a lot of sense inside a type annotation (the type annotation of your parameter) (unless you can teach me something new :)!)

Error at Input.method() call: Property 'method' does not exist on type 'new () => Data '

() => Data it's a type dictating:
"A function with no parameters that returns an object from the class Data"
So since it's a function it doesn't have any properties named method that are invokable. (From what you've explicitly provided in your sample code)

*

*function doStuffAndInstantiate(Input: typeof Data )
What you've just declared with this line is:
"A function that takes one parameter named 'Input' which is a reference to the class Data and returns nothing"

error at doStuffAndInstantiate(ChildData) call: 'ChildEntity' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Entity'.

Which is true since ChildData nor ChildData2 are a reference to the class Data.
My attempt on providing a solution based on what's on the question on 26/07 at 10:46
I still have a hard time figuring out what you're trying to do. You're trying to call a static method from Data but you're passing in the class references from ChildData and ChildData2 which ARE NOT related what-so-ever with Data since they just extend Entity.
As per now, what I can provide you with is the following:
function doStuffAndInstantiate<T extends Entity>(): Data<T> {
  // Since it's a static method you don't need to pass a parameter to call it
  Entity.method()
  // We're getting the generic type from the function
  return new Data<T>();
}

Which you could just consume as:
const childEntity = doStuffAndInstantiate<ChildEntity>(); // returns Data<ChildEntity>
const childEntity2 = doStuffAndInstantiate<ChildEntity2>(); // returns Data<ChildEntity2>

What I've just declared is:
"A generic function that takes no parameters that returns an object of the class Data with the given generic type T"
And that is as far as the compiler may go without any annotation or preprocessor magic that would search for a valid candidate that has a suitable constructor.
If you like to get direct instances of your subclasses ChildData and ChildData2you'd need toswitchorif-elseif-elsethrough all the classes that you any be interested in returning. Since this would be done at runtime you can't properly type-annotate it because typescript won't let you useT` as a value because it refers to a type (which don't exist when transpiled to JavaScript).
It'd look something like:
function doStuffAndInstantiate(classOfSomething: unknown): any | null {

    switch(classOfSomething) {
        case ChildData2:
            return new ChildData2();
        case ChildData:
            return new ChildData();
        default:
            return null;
    }

}

or you can just declare it as instantiable?
export type Abstract<T = any> = Function & { prototype: T };
export type Instantiable<T = any> = new (...args: any[]) => T;
export type Class<T = any> = Abstract<T> & Instantiable<T>;

function  doStuffAndInstantiate<E extends Entity, T extends Data<E>>(classOfSomething: Class<T> & { method: () => void }): T {
    classOfSomething.method();
    return new classOfSomething();
}

It's a tad hard to guess what you're looking for hehe

A: You'll want to declare that you want an object that's callable with new and returns your Data<T> (new () => Data<T>), and also has a property called method that is a function that takes no arguments with an ignored return value (() => void).
Give this a try:
function doStuffAndInstantiate<T extends Entity>(Input: { method(): void; new(): Data<T> }): Data<T> {
  Input.method();
  return new Input(); // You'll also want to instantiate "Input", not "Data" directly
}

Edit: Or, if you want to get more generic, you can produce a more accurate return type:
function doStuffAndInstantiate<
  T extends Entity,
  U extends Data<T>,
  V extends { method(): void; new(): U },
  W = V extends { new(): infer W } ? W : never
>(Input: V): W {
  Input.method();
  return new Input() as unknown as W;
}

// TS is happy with this now
doStuffAndInstantiate(ChildData2).childMethod();

A: The new ()=> Data<T> type fails, as this type definition does not include the statics of your Data class. typeof Data fails, because the prototype properties differ between Data and ChildData.
One approach is to exclude the prototype property and then add back in the Data<T> constraints.
function doStuffAndInstantiate<
  T extends Entity,
  R extends (new () => Data<T>) & Omit<typeof Data, 'prototype'>
>(Input: R): Data<T> {
  Input.method();
  return new Data();
}

If your child classes do not override any static methods of the Data class, it would be cleaner to use Data's methods directly:
function doStuffAndInstantiate<T extends Entity>(Input: new () => Data<T>){
    Data.method();
    return new Input();
}


text:
Q: AES 128 decryption with ciphertext shorter than key We are developing an application that has to work with data that is enycrpted by LoraWan (https://www.lora-alliance.org)
We have already found the documentation of how they encrypt their data, and have been reading through it for the past few days (https://www.lora-alliance.org/sites/default/files/2018-04/lorawantm_specification_-v1.1.pdf) but currently still can't solve our problem.
We have to use AES 128-bit ECB decryption with zero-padding to decrypt the messages, but the problem is it's not working because the encrypted messages we are receiving are not long enough for AES 128 so the algorithm returns a "Data is not a complete block" exception on the last line.
An example key we receive is like this: D6740C0B8417FF1295D878B130784BC5 (not a real key). It is 32 characters long, so 32 bytes, but if treat it as hexadecimal, then it becomes 16 bytes long, which is what is needed for AES 128-bit. This is the code we use to convert the Hex from String:
public static string HextoString(string InputText)
{byte[] hex= Enumerable.Range(0, InputText.Length)
                 .Where(x => x % 2 == 0)
                 .Select(x => Convert.ToByte(InputText.Substring(x, 2), 16))
                 .ToArray();
return System.Text.Encoding.ASCII.GetString(hex);}

(A small thing to note for the above code is that we are not sure what Encoding to use, as we could not find it in the Lora documentation and they have not told us, but depending on this small setting we could be messing up our decryption (though we have tried all possible combinations, ascii, utf8, utf7, etc))
An example message we receive is: d3 73 4c which we are assuming is also in hexadecimal. This is only 6 bytes, and 3 bytes if we convert it from hexa to normal, compared to the 16 bytes we'd need minimum to match the key length.
This is the code for Aes 128 decrypt we are using:
private static string Aes128Decrypt(string cipherText, string key){

string decrypted = null;

var cipherPlainTextBytes = HexStringToByteArray(cipherText);
//var cipherPlainTextBytes = ForcedZeroPadding(HexStringToByteArray(cipherText));
var keyBytes = HexStringToByteArray(key);

using (var aes = new AesCryptoServiceProvider())
{
    aes.KeySize = 128;
    aes.Key = keyBytes;
    aes.Mode = CipherMode.ECB;
    aes.Padding = PaddingMode.Zeros;

    ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
    using (MemoryStream ms = new MemoryStream(cipherPlainTextBytes, 0, cipherPlainTextBytes.Length))
    {
        using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
        {
            using (StreamReader sr = new StreamReader(cs))
            {
                decrypted = sr.ReadToEnd();
            }
        }
    }
}
return decrypted;}

So obviously this is going to return "Data is an incomplete block" at sr.ReadToEnd().
As you can see from the example, in that one commented out line, we have also tried to "Pad" the text to the correct size with a full zero byte array of correct length (16 - cipherText), in which case the algorithm runs fine, but it returns complete gibberish and not the original text.
We already have tried all of the modes of operation and messed around with padding modes as well. They are not providing us with anything but a cipherText, and a key for that text. No Initialization vector either, so we are assuming we are supposed to be generating that every time (but for ECB it isn't even needed iirc)
What's more is, they are able to encrypt-decrypt their messages just fine. What is most puzzling about this is that I have been googling this for days now and I cannot find a SINGLE example on google where the CIPHERTEXT is shorter than the key during decryption.
Obviously I have found examples where the message they are Encrypting is shorter than what is needed, but that is what padding is for on the ENCRYPTION side (right?). So that when you then receive the padded message, you can tell the algorithm what padding mode was used to make it correct length, so then it can seperate the padding from the message. But in all of those cases the recieved message during decryption is of correct length.
So the question is - what are we doing wrong? is there some way to decrypt with ciphertexts that are shorter than the key? Or are they messing up somewhere by producing ciphers that are too short?
Thanks for any help.

A: In AES-ECB, the only valid ciphertext shorter than 16-byte is empty. That 16-byte limit is the block (not key) size of AES, which happens to match the key size for AES-128.
Therefore, the question's

An example message we receive is: d3 73 4c

does not show an ECB encrypted message (since a comment tells that's from a JSON, that can't be bytes that happen to show as hex). And that's way too short to be a FRMPayload (per this comment) for a Join-Accept, since the spec says of the later:

1625     The message is either 16 or 32 bytes long.

Could it be that whatever that JSON message contains is not a full FRMPayload, but a fragment of a packet, encoded as hexadecimal pair with space separator? As long as it is not figured out how to build a FRMPayload, there's not point in deciphering it.
Update: If that mystery message is always 3 bytes, and if it is always the same for a given key (or available a single time per key), then per Maarten Bodewes's comment it might be a Key Check Value. The KCV is often the first 3 bytes of the encryption of the all-zero value with the key per the raw block cipher (equivalently: per ECB). Herbert Hanewinkel's javascript AES can work fully offline (which is necessary to not expose the key), and be used to manually validate an hypothesis. It tells that for the 16-byte key given in the question, a KCV would be cd15e1 (or c076fc per the variant in the next section).

Also: it is used CreateDecryptor to craft a gizmo in charge of the ECB decryption. That's likely incorrect in the context of decryption of a LoraWan payload, which requires ECB encryption for decryption of some fields:

1626     Note: AES decrypt operation in ECB mode is used to encrypt the join-accept message so that the end-device can use an AES encrypt operation to decrypt the message. This way an end device only has to implement AES encrypt but not AES decrypt.

In the context of decryption of a LoraWan packets, you want to communicate with the AES engine using byte arrays, not strings. Strings have an encoding, when LoraWan ciphertext and corresponding plaintext does not. Others seems to have managed to coerce the nice .NET do-it-all crypto API to get a low-level job done.

In the HextoString code, I vaguely get that the intention and perhaps outcome is that hex becomes the originally hex input as a byte array (fully rid of hexadecimal and other encoding sin; in which case the variable hex should be renamed to something on the tune of pure_bytes). But then I'm at loss about System.Text.Encoding.ASCII.GetString(hex). I'd be surprised if it just created a byte string from a byte array, or turned the key back to hexadecimal for later feeding to HexStringToByteArray in Aes128Decrypt. Plus this makes me fear that any byte in [0x80..0xFF] might turn to 0x3F, which is not nice for key, ciphertext, and corresponding LoraWan payload. These have no character encoding when de-hexified.
My conclusion is that if HexStringToByteArray does what its name suggests, and given the current interface of Aes128Decrypt, HextoString should simply remove whitespace (or is unneeded if HexStringToByteArray removes whitespace on the fly). But my recommendation is to change the interface to use byte arrays, not strings (see previous section).

As an aside: creating an ICryptoTransform object from its key is supposed to be performed once for multiple uses of the object.


text:
Q: PHP variable in JavaScript is not getting updated I'm trying to pass a PHP variable (number) to JavaScript. It kind of works but as soon as the number changes, it's not getting updated. My code:
    $totalamount = $woocommerce->cart->get_total();
    $totalamount = preg_replace("/[^0-9\.]/", "", $totalamount);
    $totalamount = number_format($totalamount, 2, '.', '');
    var_dump($totalamount);
?>

<script type="text/javascript">
    var Amount = "<?php echo $totalamount; ?>"

In the var_dump($totalamount); the number get's updated every time. In JavaScript it gives 0 after a change.
What is the proper way to pass a variable to JavaScript so it gets updated?

A: PHP is a server side language which means it is only executed at the time the page is loading, and the code will not be re-run unless you refresh the page.
To get around this you can retrive the total using an AJAX call which would get the total in the background and then update the page.
To get started with Ajax here is a good tutorial: Ajax


text:
Q: Simple C matrix multiplication, multi thread I have a standard C base matrix multiplication code, where I create an individual thread for each row and column pair. I am getting a blank screen where the main gets stuck for ever and program never ends. Could you please have a look at it
I want to first create all threads and then join all threads respectively.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define size 10
#define M size
#define K size
#define N size

// int A [M][K] = { {1,4}, {2,5}, {3,6} };
// int B [K][N] = { {8,7,6}, {5,4,3} };

int A [M][K];
int B [K][N] ;
int C [M][N];

struct v {
   int i; /* row */
   int j; /* column */
};

void *runner(void *param); /* the thread */

void fill_matrix(int matrix[][N], int row, int column)
{
   // int (*matrix)[row] = malloc(sizeof(int[row][column]));
  for (int i = 0; i < row; i++)
  {
    for (int j = 0; j < column; j++)
    {
      matrix[i][j] = (rand() % (100-0+1)) + 1;
    }
  }
  return;
}

int main(int argc, char *argv[]) {

   int i,j, count = 0;
   // int (*A)[M] = malloc(sizeof(int[M][K]));
   // int (*B)[K] = malloc(sizeof(int[K][N]));
   // A = (int*)malloc(sizeof(A));

   fill_matrix(A,M,K);
   fill_matrix(B,K,N);
   clock_t start = clock();
  // pthread_t thread_array[M*N];
    pthread_t thread_array[M*N]; //malloc(M*N * sizeof(pthread_t));

    pthread_attr_t attr;
    pthread_attr_init(&attr);
   int idl[M*N];
   for(i = 0; i < M; i++) {
      for(j = 0; j < N; j++) {
         //Assign a row and column for each thread
         struct v *data = (struct v *) malloc(sizeof(struct v));
         data->i = i;
         data->j = j;
         /* Now create the thread passing it data as a parameter */
         //pthread_t tid;       //Thread ID
         //pthread_attr_t attr; //Set of thread attributes
         //Get the default attributes
         //pthread_attr_init(&attr);
         //Create the thread
        idl[i]=count;
         pthread_create(count,&thread_array[count],&attr,runner,data);
         //Make sure the parent waits for all thread to complete
         //pthread_join(tid, NULL);
         count++;
      }
   }
   for(int k =0;k<M*N;k++){
   pthread_join(&thread_array[k],NULL);
   }
  free(thread_array);
     clock_t end = clock();
     printf("%f\n",(float)(end-start)/CLOCKS_PER_SEC );

   //Print out the resulting matrix
   //for(i = 0; i < M; i++) {
   //   for(j = 0; j < N; j++) {
   //      printf("%d ", C[i][j]);
   //   }
   //   printf("\n");
  // }
}

//The thread will begin control in this function
void *runner(void *param) {
   struct v *data = param; // the structure that holds our data
   int n, sum = 0; //the counter and sum

   //Row multiplied by column
   for(n = 0; n< K; n++){
      sum += A[data->i][n] * B[n][data->j];
   }
   //assign the sum to its coordinate
   C[data->i][data->j] = sum;

   //Exit the thread
   pthread_exit(0);
}

Please ignore the comments in code, I know there are many.

A: Remove free(thread_array);, you did not malloc it, so you don't need to free it.
pthread_join(&thread_array[k],NULL); should be pthread_join(thread_array[k],NULL);, as it is taking the pthread_t and not a pointer to it.
The first parameter in pthread_create(count,&thread_array[count],&attr,runner,data); is wrong, remove it ==> pthread_create(&thread_array[count],&attr,runner,data);.
You do not use the isl array, so remove it.
After that it compiles, runs and gives an output, at least: https://ideone.com/1r0e2V


text:
Q: Adding clickHandler to row in CellTable in GWT? I have created a basic CellTable and filled it with some data. Now I want to add a clickHandler to each row but I'm not sure how to do this. I've created a clickEvent for the whole table but I want one for each row.
    table.sinkEvents(Event.ONCLICK);
    table.setTitle("Click me");
    table.setSize("600px", "600px");
    table.addDomHandler(new ClickHandler()
    {
        @Override
        public void onClick(ClickEvent event)
        {
            Window.alert("You clicked!" +);

        }
    }, ClickEvent.getType());

Can I do something similar to add clickEvent for each row?

A: A CellTable has built in support for handling click events. You can add a CellPreviewHandler that will be called among others when a row is clicked. It will receive a number of items in the event like the native event, cell, and data row value. Because it fires not only for click events you need to check if the click event was fired. Simply test the event passed: boolean isClick = "click".equals(event.getNativeEvent().getType()).
Another option is to extend the protected method doSelection, but it's deprecated and in you need to als make sure you have the right KeyboardSelectionPolicy set to make sure it's called when a click is done. See for the latter in the JavaDoc of the interface KeyboardSelectionPolicy.

A: Another way to have a cell selected can be made using a NoSelectionModel and add it to the table:
//EDIT: this is a field, not a local variable
TheCellObject clickedObject; //the object selected by selectionModel

final NoSelectionModel<TheCellObject> selectionModel = new NoSelectionModel<TheCellObject>();

    selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {

                @Override
                public void onSelectionChange(SelectionChangeEvent event) {
                    clickedObject = selectionModel.getLastSelectedObject();
                }
            });
cellTable.setSelectionModel(selectionModel); //add selection model to your celltable


text:
Q: 'UnityEngine.GameObject[]' does not contain a definition for `Transform' error i was making a script to generate the paths on which my player is to run just like an endless runner. i was trying to access my "own" transform (player's tranform) and put it in playertransform variable but getting this error. heres the full code:-
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class tilemanager : MonoBehaviour {

    public GameObject[] tileprefabs;

    private Transform playertransform;
    private float spawnz = 0.0f;
    private float tilelength = 16.0f;
    private int amountoftilesonscreen = 7;
    private List<GameObject> activetiles;
    private float safezone = 15.0f;

    void Start(){

        activetiles = new List<GameObject>();
        playertransform = GameObject.FindGameObjectsWithTag("Player").Transform;

        for(int i = 0; i < amountoftilesonscreen; i++){

            SpawnTile();
        }
    }

    void Update(){

        if(playertransform.position.z - safezone > (spawnz - amountoftilesonscreen * tilelength)){

            SpawnTile();
            DeleteTile();
        }
    }

    void SpawnTile(int prefabIndex = -1){

        GameObject go;

        go = Instantiate(tileprefabs[0]) as GameObject;
        go.transform.SetParent(transform);
        go.transform.position = Vector3.forward * spawnz;
        spawnz += tilelength;
        activetiles.Add(go);
    }

    void DeleteTile(){

        Destroy(activetiles[0]);
        activetiles.RemoveAt(0);
    }
}

A: Because GameObject.FindGameObjectsWithTag returns a gameobject array. Use GameObject.FindWithTag instead.

A: You are using FindGameObjectsWithTag() which returns array of gameObject. Change it to FindWithTag().
and correct code would be :
playertransform = GameObject.FindWithTag("Player").transform;

A: if your script is a component on the object you want to find can you just refer to it as
transform:
transform.position;

and if you want to have it in a variable just use:
Transform transform_off_object = transform;


text:
Q: Find copy-and-paste code - for bash / shell script I have a bash project, which consists a dozen files. There are some copy paste between the files (and inside one files also).
So, is there a copy paste detector for bash / shell scripts or at least for plain text?

Copy paste detector, like this, just for shell script: http://pmd.sourceforge.net/pmd-5.1.0/cpd.html
Similar question for java: Do tools exist which automatically find copy-and-paste code?

A: This is what comm is for:
comm -12 <(sort file1.txt) <(sort file2.txt)

A: I've been searching for this myself. Here are some of the results I've found that either claim they do plain text, or someone else claims they do plain text.
MOSS
Clone Dr
Simian
Near Dup
I've also run into some others, such as DuDe (exists several places) and CCfinder but I can't get either of them to compile.
I only post anonymously, so I don't have enough rep to post more than two links, sorry.
Edit: Atomiq worked for me on plain text, that will probably be my go to now


text:
Q: Proof that the Eulerian Numbers $A(n,m)$ are asymptotic to $(m+1)^n$ when $m$ is fixed and $n\rightarrow\infty$ This is stated in many places but seldom proved. The goal is to prove that, for fixed $m\geq 0$,
$$\lim_{n\rightarrow\infty}A(n,m)\sim (m+1)^n$$
where $A(n,m)$ are the Eulerian Numbers, namely, the number of permutations of $\{1,2,\ldots,n\}$ with exactly $k$ "ascents" (places where the element is greater than the previous one).

A: Let us prove that
$$\lim_{n\rightarrow\infty}\frac{A(n,m)}{(m+1)^n}=1.$$
We use the formula for the Eulerian Numbers provided in the book Concrete Mathematics:
$$A(n,m)=\sum_{k=0}^m\binom{n+1}{k}(m+1-k)^n(-1)^k.$$
Dividing the equation above by $(m+1)^n$ we have:
\begin{eqnarray}
\frac{A(n,m)}{(m+1)^n}&=&
\sum_{k=0}^m\binom{n+1}{k}\frac{(m+1-k)^n}{(m+1)^n}(-1)^k\\
&=&
\sum_{k=0}^m\binom{n+1}{k}\left(\frac{m+1-k}{m+1}\right)^n(-1)^k\\
&=&
\sum_{k=0}^m\binom{n+1}{k}\left(1-\frac{k}{m+1}\right)^n(-1)^k\\
%&=&
%1+\sum_{k=1}^m\binom{n+1}{k}\left(1-\frac{k}{m+1}\right)^n(-1)^k\\
\end{eqnarray}
Let $a_{n,k}:=\binom{n+1}{k}\left(1-\frac{k}{m+1}\right)^n(-1)^k$, thus $\frac{A(n,m)}{(m+1)^n}=\sum_{k=0}^ma_{n,k}$. If $k=0$ then $a_{n,k}=1$. We are going to prove that, when $k\neq 0$, $a_{n,k}\rightarrow 0$.
Consider the series $\sum_{n=0}^\infty a_{n,k}$. We will prove that this series converges if $k\neq 0$ using the ratio test:
$$\left|\frac{a_{n+1,k}}{a_{n,k}}\right|=
\frac{\binom{n+2}{k}\left(1-\frac{k}{m+1}\right)^{n+1}(-1)^k}
{\binom{n+1}{k}\left(1-\frac{k}{m+1}\right)^n(-1)^k}=
\frac{n+2}{n+2-k}\left(1-\frac{k}{m+1}\right)$$
Note that, when $n\rightarrow\infty$, $\frac{n+2}{n+2-k}\rightarrow 1$. So
$\left|\frac{a_{n+1,k}}{a_{n,k}}\right|\rightarrow 1-\frac{k}{m+1}$. If $k\neq 0$ then $1-\frac{k}{m+1}<1$. Therefore, by the ratio test, the series $\sum_{n=0}^\infty a_{n,k}$ converges. It follows that $a_{n,k}\rightarrow 0$ when $n\rightarrow\infty$.
So we have $\frac{A(n,m)}{(m+1)^n}=\sum_{k=0}^ma_{n,k}$ with $a_{n,0}=1$ and $a_{n,k}\rightarrow 0$ when $k\neq 0$ and $n\rightarrow\infty$. This means that
$$\lim_{n\rightarrow\infty}\frac{A(n,m)}{(m+1)^n}=
\lim_{n\rightarrow\infty}\sum_{k=0}^ma_{n,k}=1
%\lim_{n\rightarrow\infty}1+\sum_{k=1}^m\lim_{n\rightarrow\infty}a_{n,k}=
%1+\sum_{k=1}^ma_{n,k}=
$$


text:
Q: Can I create a really Universal USB Drive? I have looked and looked over this forum and multiple other forums about the correct way to do this and I have not found a solid answer yet. I am trying to create an all in one bootable tech USB drive.
I currently have 4 partitions on this 500 GB drive.

1 is Windows 8,
  2 is Ubuntu 13.04,
  3 is swap for Ubuntu, and
  4 I'm calling Bootable ISOs.

This is what I want to happen. When I boot to the USB it goes to grub2 then from there I can go to Win8 or Ubuntu. So far all this works fine, However what I can't seem to get to work is I'm wanting to add tons and I mean around 300 GBs worth of Bootable ISOs, including Hirens, Bitdefender, ERD, and anything else I can get my hands on. Now I've heard all that is possible, however I am also wanting to be able to put Win8,Win7,WinVista,WinXP, and pretty much anything else that I may possibly use at work, and be able to install them all from my USB.
Think PXE server, but from my USB. Is all this possible. My first step was to install win8 and Ubuntu side by side, and I got that done. My next step has been to get Grub2 to boot to the .iso files on the 4th partition.
Any ideas, I'm kinda new to all this Ubuntu stuff, but I'm always willing to learn. So break it down for me as best as possible so that I can actually learn for next time.


text:
Q: Escape a nested IF statement and evaluate the variable against parent condition I have a file parser that evaluates each line of a txt file against a condition. If the condition is met, the subsequent lines in the file are evaluated against a series of nested IF statements.
What I would like to do is break out of the nested IF statements once the parent condition is met again, then evaluate the line that broke against the parent and have it trigger the nested evaluations again. I am doing this because all of the nested IF statements pull data about the parent item. when i hit another parent item, escape child evaluations and start again.
is this an poor way of handling the situation?
here is  my pseudo code
if (line.Contains(":rule ("))
{
    bInRuleFlag = true;

    while (bInRuleFlag == true)
    {
        if (line.Contains(":rule ("))
        {
            bInRuleFlag = false;
            // I have hit a parent element.
            // escape the while loop here and evaluate line against  the parent IF
        }
        else if (line.contatins(""))
        {
            //gets child elements to the rule
        }
        else if (line.contatins(""))
        {
            //gets child elements to the rule
        }
    }

}
I would appreciate any advice about better ways to do it if this is incorrect.

A: You can probably just got rid of the outer if statement all together, and your code will work like what you described.
while (line.Contains(":rule ("))
{
    if (line.contatins(""))
    {
        //gets child elements to the rule
    }
    else if (line.contatins(""))
    {
        //gets child elements to the rule
    }
}

also, you can use the break command to break out of your while loop
    if (line.Contains(":rule ("))
    {
        break;
    }

If you just want to stop there, and go directly to the next iteration of the loop, then you can use the continue keyword
    if (line.Contains(":rule ("))
    {
        continue;
    }


text:
Q: How to resample and round every index into nearest seconds? My data looks like (the datatype is Pandas DataFrame) :
price =

time                bid
03:03:34.797000     116.02
03:03:34.797000     116.02
03:03:54.152000     116.02
03:03:54.169000     116.02
03:03:54.169000     116.02
03:07:36.899000     116.24
03:07:48.760000     116.24
03:07:48.760000     116.24
03:07:48.761000     116.24

I tried to resample the data into second level data and align every data into the nearest seconds no earlier than the original time. I expect the result to be:
03:04:00    116.02
03:05:00    NaN
03:06:00    NaN
03:07:00    NaN
03:08:00    116.24

and used
price.resample('Min').last()

However I got.
03:03:34.797000     116.02
03:04:34.797000     NaN
03:05:34.797000     NaN
03:06:34.797000     NaN
03:07:34.797000     116.24

Everything goes well except the alignment. Anyone could help me solve the problem? Thanks.

A: You need to use floor:
df.groupby(df.index.floor('Min')).last().resample('Min').asfreq()

Let's try for speed(need Pandas 0.21.0+):
df.set_axis(df.index.floor('Min'), axis=0, inplace=False)\
  .drop_duplicates().resample('Min').asfreq()

Output:
             bid
time
03:03:00  116.02
03:04:00     NaN
03:05:00     NaN
03:06:00     NaN
03:07:00  116.24

A: (df.groupby(df['time'].dt.round('1min') )['bid'].mean()).asfreq('Min')
Out[45]:
time
2017-12-06 03:04:00    116.02
2017-12-06 03:05:00       NaN
2017-12-06 03:06:00       NaN
2017-12-06 03:07:00       NaN
2017-12-06 03:08:00    116.24
Freq: T, Name: bid, dtype: float64

A: I tried with this solution and it runs faster.
df = df.resample('Min').last()
offset_mc = df.index[0].microseconds
offset_sec = df.index[0].seconds % 60
if not (offset_mc == 0 and offset_sec == 0): df.index +=  pd.tslib.Timedelta(str(59-offset_sec)+'seconds '+str(1000000-offset_mc)+'microseconds')


text:
Q: Take pictures of the whole activity sometimes crash the App When I press the "Share" button, my app takes a screenshot of all the activity(even no visible parts) and the share it via intent. I figured out that sometime it works and sometimes it doesn't. I can't understand the problem.
That's my code:
share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkPermission();

        }
    });
// Inside the checkPermission method, if the user allow them:
Bitmap bitmapScreen = takeScreenshot();
saveBitmap(bitmapScreen);
}

 public Bitmap takeScreenshot() {

    rechoose.setVisibility(View.GONE);
    share.setVisibility(View.GONE);
    View rootView = findViewById(android.R.id.content).getRootView();
    rootView.setDrawingCacheEnabled(true);
    rootView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    rootView.layout(0, 0, rootView.getMeasuredWidth(), rootView.getMeasuredHeight());
    rootView.buildDrawingCache(true);

    return rootView.getDrawingCache();
}

public void saveBitmap(Bitmap bitmap) {
    UUID uuid = UUID.randomUUID();
    String randomUUIDString = "/" + uuid.toString() + ".png";
    rechoose.setVisibility(View.VISIBLE);
    share.setVisibility(View.VISIBLE);
    imagePath = new File(Environment.getExternalStorageDirectory() + randomUUIDString);
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.v("errorFileNotFound", e.getMessage(), e);
    } catch (IOException e) {
        Log.v("Exception", e.getMessage(), e);
    }

    Uri uri = FileProvider.getUriForFile(RateActivity.this, BuildConfig.APPLICATION_ID + ".provider", imagePath);
    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType("image/*");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(sharingIntent, "Share via"));
}

I got this error:
 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
    at com.my.name.myapp.RateActivity.saveBitmap(RateActivity.java:211)

The line 211 is:
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

It's a little bit strange, because sometimes it works and sometimes it doesn't.
On my activity I load an image from my gallery. With some image that I pick from gallery, the app takes the screenshot, with others it doesn't.
Obviously, if the app didn't take the screenshot, then I got a nullPointerException on bitmap.compress. But I can't figured out why it doesn't take the screenshot.
If I write the takeScreenshot() method like this, it works anytime:
public Bitmap takeScreenshot() {

View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);

return rootView.getDrawingCache();
}

A: Your Bitmap is null here. Please debug the value of bitmap and cross check if it is null or not. Or you can use the below code to take a screenshot, put this function n general method and pass your view to it.
fun takeScreenshot(context: View?, activity: Activity) {
val now = Date()
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now)
try {
    val mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg"
    // create bitmap screen capture
    context?.isDrawingCacheEnabled = true
    val bitmap = Bitmap.createBitmap(context?.drawingCache)
    context?.isDrawingCacheEnabled = false
    val imageFile = File(mPath)
    val outputStream = FileOutputStream(imageFile)
    val values = ContentValues()
    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
    values.put(MediaStore.MediaColumns.DATA, mPath)
    activity.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
    val quality = 100
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
    outputStream.flush()
    outputStream.close()
    Toast.makeText(activity, activity.getString(R.string.saved_to_gallery), Toast.LENGTH_SHORT).show()
} catch (e: Throwable) {
    e.printStackTrace()
}


text:
Q: URL has too many redirects. Facebook won't be able to scrape this URL until the number of redirects are reduced I am running an FQL Query using the PHP Library. It is in an app seeing heavy use and works fine. However, with one user (A internal QA tester), it is throwing a weird FB Exception that I can't find any documentation on. The Exception message is:
"URL has too many redirects. Facebook won't be able to scrape this URL until the number of redirects are reduced."
This makes no sense given the query is:
$multiQuery = "info":"SELECT name, pic, sex, activities, interests, quotes, about_me, profile_blurb, music, tv, movies, books, games, sports, favorite_teams, favorite_athletes, timezone, locale, first_name FROM user WHERE uid = me()",
"likes":"SELECT user_id, object_id, object_type FROM like WHERE user_id = me() LIMIT 350",
"stream":"SELECT post_id, created_time, permalink, description, message, description_tags FROM stream WHERE source_id = me() AND filter_key = 'owner' AND created_time > 946684800 LIMIT 350",
"links":"SELECT link_id, created_time, owner_comment, picture FROM link WHERE owner = me() LIMIT 350",
"photos":"SELECT created, caption, src FROM photo WHERE aid IN (SELECT aid FROM album WHERE owner = me() LIMIT 100) LIMIT 350",
"myPhotosLiked":"SELECT object_id, user_id FROM like WHERE object_id in (SELECT object_id FROM photo WHERE aid IN (SELECT aid FROM album WHERE owner = me() LIMIT 50) LIMIT 100) LIMIT 350",
"questions":"SELECT question, created_time FROM question where owner = me() LIMIT 350"

$results = $facebook->api('fql/?q=' . urlencode($multiQuery));
// $facebook is the Facebook PHP library reference

Anyone run into this before?
UPDATE: Thanks all for the suggestions. Of course now the QA guy can no longer replicate. This is the second time it happened and both times it was only with his FB account (machine, browser didn't matter) and it persisted for about 24-48 hours, then just went away on its own. I will just have to wait for it to pop up again to test these suggestions.
UPDATE 2: Ok - the issue has recurred again. I had the tester try it on multiple networks and computers / devices. Same weird error every time. To clarify though, it is only happening with his FB account. If he tries any other account, it works fine.Maybe FB just has a personal beef with this guys account. Anyone had any similar type of error that was just tied to an individual account?

A: I had this exception thrown once. Though I was not using FQL. I went through a massive amount of crap and hacks, fixes without any joy. I just could not figure out what was causing it. Turned out that one part of my app (Second iframe for ads) was caught in a re-direct loop.
I don't know if this will help. But thought I would share anyway.


text:
Q: Resize image propotionally in PHP Bear with me, im new to PHP. I got this very nice tutorial from here:
Add watermark image PHP - developphp.com
The problem is, the cropping ratio is not proportionate. If I have wider image, it crop 500px width and the height is not proportion to the width the same as the height (tall image crop to 500px and width is lesser px.)
I want to make it proportional as 500px both width and height no matter how wide or tall the image is and should crop center.
Been searching and trying other method but failed. Hope someone can help. Thanks!
Here is the code:
<?php
// Access the $_FILES global variable for this specific file being uploaded
// and create local PHP variables from the $_FILES array of information
$fileName = $_FILES["uploaded_file"]["name"]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension

// START PHP Image Upload Error Handling -------------------------------
if (!$fileTmpLoc) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";
    exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
    echo "ERROR: Your file was larger than 5 Megabytes in size.";
    unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
    exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
     // This condition is only if you wish to allow uploading of specific file types
     echo "ERROR: Your image was not .gif, .jpg, or .png.";
     unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
     exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
    echo "ERROR: An error occured while processing the file. Try again.";
    exit();
}
// END PHP Image Upload Error Handling ---------------------------------
// Place it into your "uploads" folder mow using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
    echo "ERROR: File not uploaded. Try again.";
    exit();
}
// Include the file that houses all of our custom image functions
include_once("ak_php_img_lib_1.0.php");
// ---------- Start Universal Image Resizing Function --------
$target_file = "uploads/$fileName";
$resized_file = "uploads/resized_$fileName";
$wmax = 500;
$hmax = 500;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
// ----------- End Universal Image Resizing Function ----------
// ---------- Start Convert to JPG Function --------
if (strtolower($fileExt) != "jpg") {
    $target_file = "uploads/resized_$fileName";
    $new_jpg = "uploads/resized_".$kaboom[0].".jpg";
    ak_img_convert_to_jpg($target_file, $new_jpg, $fileExt);
}
// ----------- End Convert to JPG Function -----------
// ---------- Start Image Watermark Function --------
$target_file = "uploads/resized_".$kaboom[0].".jpg";
$wtrmrk_file = "watermark.png";
$new_file = "uploads/protected_".$kaboom[0].".jpg";
ak_img_watermark($target_file, $wtrmrk_file, $new_file);
// ----------- End Image Watermark Function -----------
// Display things to the page so you can see what is happening for testing purposes
echo "The file named $fileName uploaded successfuly.

";
echo "It is $fileSize bytes in size.

";
echo "It is an $fileType type of file.

";
echo "The file extension is $fileExt

";
echo "The Error Message output for this upload is: $fileErrorMsg
";
?>


text:
Q: VBA - If cell is empty, return empty cell for specific range I have this function in my code which gets values from a particular range in multiple files (a range from the last value in a column up to a designated header) and prints them to one worksheet, my masterfile. It does this for two columns.
My problem is that sometimes I will have 1 value in one column and 8 in another. They should always be equal to each other in length so I would need the first column to print the 1 value cell followed by 7 blank cells.
I think the best way to go about it would be to grab the very first column in an opened file and have both of those columns print to the length of that one since it will always be the correct length. Any idea how to go about setting this up? I have been playing with it but cannot get it to work.
I thought I could set the value of the "TOOL NUM" column to n, and have everything print to length n (denoted as section (3) and (4) of my code). I just do not know how to set the latter up.
Here is the area of code I am playing with, which goes right before section (3)
   If Not Range("A1:A24").Find(What:="TOOL NUM", LookAt:=xlWhole, LookIn:=xlValues) Is Nothing Then
        Set n = ws.Cells(Rows.count, 1).End(xlUp)

In this line, in my masterfile that everything is printed to, I have it print down to the length of whatever column "C" is so I was hoping this would be a good basis to go off of for printing down to the length of whatever column 1 in the open file would be. Hope that is helpful.
StartSht.Range(StartSht.Cells(i, 1), StartSht.Cells(GetLastRowInColumn(StartSht, "C"), 1)) = TDS

FULL CODE:
Option Explicit

Sub LoopThroughDirectory()

    Const ROW_HEADER As Long = 10

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim dict As Object
    Dim MyFolder As String
    Dim f As String
    Dim StartSht As Worksheet, ws As Worksheet
    Dim WB As Workbook
    Dim i As Integer
    Dim LastRow As Integer, erow As Integer
    Dim Height As Integer
    Dim FinalRow As Long
    Dim hc As Range, hc1 As Range, hc2 As Range, hc3 As Range, hc4 As Range, d As Range
    Dim TDS As Range

    Set StartSht = Workbooks("masterfile.xlsm").Sheets("Sheet1")

    'turn screen updating off - makes program faster
    Application.ScreenUpdating = False

    'location of the folder in which the desired TDS files are
    MyFolder = "C:\Users\trembos\Documents\TDS\progress\"

    'find the headers on the sheet
    Set hc1 = HeaderCell(StartSht.Range("B1"), "HOLDER")
    Set hc2 = HeaderCell(StartSht.Range("C1"), "CUTTING TOOL")
    Set hc4 = HeaderCell(StartSht.Range("A1"), "TOOLING DATA SHEET (TDS):")

    'create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'get the folder object
    Set objFolder = objFSO.GetFolder(MyFolder)
    i = 2

    'loop through directory file and print names
'(1)
    For Each objFile In objFolder.Files
        If LCase(Right(objFile.Name, 3)) = "xls" Or LCase(Left(Right(objFile.Name, 4), 3)) = "xls" Then
'(2)
            'Open folder and file name, do not update links
            Set WB = Workbooks.Open(fileName:=MyFolder & objFile.Name, UpdateLinks:=0)
            Set ws = WB.ActiveSheet

If Not Range("A1:A24").Find(What:="TOOL NUM", LookAt:=xlWhole, LookIn:=xlValues) Is Nothing Then
'(3)
                'find CUTTING TOOL on the source sheet
                Set hc = HeaderCell(ws.Cells(ROW_HEADER, 1), "CUTTING TOOL")
                If Not hc Is Nothing Then
                    Set dict = GetValues(hc.Offset(1, 0), "SplitMe")
                    If dict.count > 0 Then
                    'add the values to the master list, column 3
                        Set d = StartSht.Cells(Rows.count, hc2.Column).End(xlUp).Offset(1, 0)
                        d.Resize(dict.count, 1).Value = Application.Transpose(dict.items)
                    Else
                        StartSht.Cells(Rows.count, hc2.Column).End(xlUp).Offset(1, 0) = ""
                    End If
                Else
                    StartSht.Cells(Rows.count, hc2.Column).End(xlUp).Offset(1, 0) = "NO 'CUTTING TOOL' PRESENT!"
                End If
'(4)
                'find HOLDER on the source sheet
                Set hc3 = HeaderCell(ws.Cells(ROW_HEADER, 1), "HOLDER")
                If Not hc3 Is Nothing Then
                    Set dict = GetValues(hc3.Offset(1, 0))
                    'If InStr(ROW_HEADER, "HOLDER") <> "" Then
                    If dict.count > 0 Then
                        'add the values to the master list, column 2
                        Set d = StartSht.Cells(Rows.count, hc1.Column).End(xlUp).Offset(1, 0)
                        d.Resize(dict.count, 1).Value = Application.Transpose(dict.items)
                    Else
                        StartSht.Cells(Rows.count, hc1.Column).End(xlUp).Offset(1, 0) = ""
                    End If
                Else
                    StartSht.Cells(Rows.count, hc2.Column).End(xlUp).Offset(1, 0) = "NO 'CUTTING TOOL' PRESENT!"
                End If
End If
'(5)
            With WB
                    'print the file name to Column 4
                    StartSht.Cells(i, 4) = objFile.Name

                    With ws
                    'Print TDS name by searching for header
                        If Not Range("A1:K1").Find(What:="TOOLING DATA SHEET (TDS):", LookAt:=xlWhole, LookIn:=xlValues) Is Nothing Then
                            Set TDS = Range("A1:K1").Find(What:="TOOLING DATA SHEET (TDS):", LookAt:=xlWhole, LookIn:=xlValues).Offset(, 1)
                            StartSht.Range(StartSht.Cells(i, 1), StartSht.Cells(GetLastRowInColumn(StartSht, "C"), 1)) = TDS
                        Else
                            StartSht.Range(StartSht.Cells(i, 1), StartSht.Cells(GetLastRowInColumn(StartSht, "C"), 1)) = "NO TDS VALUE!"
                        End If
                        i = GetLastRowInSheet(StartSht) + 1
                    End With
'(6)
                'close, do not save any changes to the opened files
                .Close SaveChanges:=False
            End With
        End If
'(7)
    'move to next file
    Next objFile
    'turn screen updating back on
    Application.ScreenUpdating = True
    ActiveWindow.ScrollRow = 1 'brings the viewer to the top of the masterfile
End Sub

'(8)
'get all unique column values starting at cell c
Function GetValues(ch As Range, Optional vSplit As Variant) As Object
    Dim dict As Object
    Dim rng As Range, c As Range
    Dim v
    Dim spl As Variant

    Set dict = CreateObject("scripting.dictionary")

    For Each c In ch.Parent.Range(ch, ch.Parent.Cells(Rows.count, ch.Column).End(xlUp)).Cells
        v = Trim(c.Value)
        If Len(v) > 0 And Not dict.exists(v) Then

            'exclude any info after ";"
            If Not IsMissing(vSplit) Then
            spl = Split(v, ";")
            v = spl(0)
            End If

            'exclude any info after ","
            If Not IsMissing(vSplit) Then
            spl = Split(v, ",")
            v = spl(0)
            End If

            dict.Add c.Address, v
        End If

        If Len(v) = 0 Then
            v = ""
        End If

'        If Len(v) = "" Then
'            v = ""
'        End If

    Next c
    Set GetValues = dict
End Function

'(9)
'find a header on a row: returns Nothing if not found
Function HeaderCell(rng As Range, sHeader As String) As Range
    Dim rv As Range, c As Range
    For Each c In rng.Parent.Range(rng, rng.Parent.Cells(rng.Row, Columns.count).End(xlToLeft)).Cells
        'copy cell value if it contains some string "holder" or "cutting tool"
        If InStr(c.Value, sHeader) <> 0 Then
            Set rv = c
            Exit For
        End If
    Next c
    Set HeaderCell = rv
End Function

'(10)
Function GetLastRowInColumn(theWorksheet As Worksheet, col As String)
    With theWorksheet
        GetLastRowInColumn = .Range(col & .Rows.count).End(xlUp).Row
    End With
End Function

'(11)
Function GetLastRowInSheet(theWorksheet As Worksheet)
Dim ret
    With theWorksheet
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            ret = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          LookAt:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row
        Else
            ret = 1
        End If
    End With
    GetLastRowInSheet = ret
End Function

EDIT: Picture upload to clarify question in comments
This image is what the opened files look like and I am grabbing from 2 columns "HOLDER" and "CUTTING TOOL" which here are labeled number and cutting tool

A: Try getting the last row in the worksheet used range. Change
Function GetLastRowInColumn(theWorksheet As Worksheet, col As String)
    With theWorksheet
        GetLastRowInColumn = .Range(col & .Rows.count).End(xlUp).Row
    End With
End Function

To
Function GetLastRowInSheet(theWorksheet As Worksheet)
    GetLastRowInColumn = theWorksheet.UsedRange.Rows.count
End Function

I assume that your worksheets only contain necessary data and do not have a bunch of additional cells outside the desired range. For example, if everything is within A1:C10, and you have values below row 10, this will extend all the way to the bottom of the used range.
Edit: You'll also have to make sure you update references to the function. You could also probably move the single line of code to where it is being called and save yourself a few more lines.


text:
Q: Relate existing User and Post in Prisma to create a favorites feature I want a simple favorite feature. For that I need to connect an existing user with an existing post.
I cannot really find an explanation in the Prisma docs, they only show how to make relations when creating a new post.
Here is my schema:
model User {
  uid String @id @default(uuid())
  username String? @db.VarChar(24) @unique
  favorites FavoritesOnUsers[]

model Post {
  id             Int     @id @default(autoincrement())
  title           String  @db.VarChar(255)
  favoritedBy FavoritesOnUsers[]
}

model FavoritesOnUsers {
  user       User     @relation(fields: [userId], references: [uid])
  userId     String
  post       Post @relation(fields: [postId], references: [id])
  postId     Int

  @@id([userId, postId])
}

So when the user likes a post and adds it to his favorites, how would such a query look like to combine the userId with the postId in the FavoritesOnUsers table?

A: Creating a record in the junction table should relate both entities:
await prisma.favouritesOnUsers.create({
  data: { userId, postId },
});


text:
Q: Order table by two columns Imagine that I have a table with entities and some of them have forks; the column fork stores the id of the parent entry or 0, if that entry doesn't have a fork.
Table ents:
id  name        fork
1   Adidas      0
2   Betina      0
3   Shop Adidas 1
4   Shell       0
5   StoreAdidas 1
6   Shell 1     4

This is how I would like to get the results, i.e., sorted by name but with the forks next to its parent:
id  name
1   Adidas
3   Shop Adidas
5   StoreAdidas
2   Betina
4   Shell
6   Shell 1

Is this possible with a MySQL query?
Thank you for your help.

A: You can do:
SELECT t.*
FROM nameofTable AS t
ORDER BY CASE WHEN t.fork <> 0 THEN t.fork ELSE t.id END,
         CASE WHEN t.fork <> 0 THEN t.id ELSE 0 END

Explanation:
The Statement is simply sorting by two column:
fork and id. However, some conditioning has been added so that we only sort by fork if one exits for the given row otherwise the id is to be used. Meaning they are shown directly next to "parent" entry. Multiple forks (aka. "children") are then again ordered by their id.
See running example at DB Fiddle.

A: If you want to sort by name instead of by id, a self-join is needed:
select t1.id, t1.name
from table_name t1 left join table_name t2
on t1.fork = t2.id
order by coalesce(t2.name, t1.name)

Fiddle