text:
Q: Error after importing a project into eclipse This is the warning that I have been getting.
The file cannot be validated as the XML definition "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" that is specified as describing the syntax of the file cannot be located.
The jars for hibernate are present.
What am I missing?

A: Some times eclipse may failed to load that DTD file specified in the XML file.
In such cases you can download and set it manually.
Even though the below link specified as for log4j xml file.Follow the same procedure for hibernate.cfg.xml
Eclipse: Referencing log4j.dtd in log4j.xml

A: This occurs when eclipse cannot detect the hibernate libraries on the .classpath. Make sure that they are added to the correct project .classpath.
You might want to refresh the project in-order for the changes to take effect.


text:
Q: How do I run next export with custom filenames? I'm trying to export our site using Next. Prior to working with next we had a custom webpack build that would specify an output format so we can append a hash.
output: {
        filename: 'file-main.[chunkhash].js'
    },

I adjusted the next.config.js to have a customized webpack configuration like so:
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  experimental: {
    images: {
      unoptimized: true,
    },
  },
  webpack: (
    config,
    { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
  ) => {
    const newConfig = {
      ...config,
      output: {
        filename: '[main].[contenthash].js',
      },
    };
    return newConfig;
  },
};

module.exports = nextConfig;

When I try and next export I get this error

Build error occurred
[Error: ENOENT: no such file or directory, open 'C:\repos\storefront-admin\storefront-ui.next\server\pages-manifest.json'] {
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\repos\storefront-admin\storefront-ui\.next\server\pages-manifest.json'
}
info  - Collecting page data .

Has anyone changed the output filenames successfully?

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP : echo a href I have this php line which works fine:
echo "
" . $post['message']. "
";

But I want to change it so it will link to my page (not to a single post). So it should look like that.
echo "
" . $post['message']. "
";

I have tried a lot many proposition gathered on different website, but each time I am getting an error.
Any idea ?
Thanks a lot!

A: Using single and double quotes, you avoid escaping issues. Try this:
echo '
'. $post['message']. '
';

A: i see that you didn't escaped from double quote that closes href attribute:
echo "
"

A: I guess You have missed the back slash () before " after  www.facebook.com/rscmovement.
"https://www.facebook.com/rscmovement\" "\"target=\"_blank\">"  will


text:
Q: Azure Mobile App with MSAL JWT validation failed IDX10500 I am trying to authenticate a Xamarin.Forms app against my Azure Mobile App backend (which has been set up to use Azure AD authentication) using Microsoft Authentication Library (MSAL). This is so that the app can access tables API Controllers etc, but I am having issues authenticating fully.
In the app (client side) it kind of seems like I am able to successfully login because I got the Azure AD login screen in Safari web browser but straight after entering my credentials I get redirected to the app and I am presented with the following error from MSAL:

You do not have permission to view this directory or page.

I did some digging and attached a debugger to my Mobile App backend and that revealed the following:

Microsoft.Azure.AppService.Middleware Verbose: 0 : Received request:
  POST https://myapp.azurewebsites.net/.auth/login/aad
Exception thrown:
  'System.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException'
  in Microsoft.Azure.AppService.Middleware.Modules.dll
Microsoft.Azure.AppService.Middleware Warning: 0 : JWT validation
  failed: IDX10500: Signature validation failed. Unable to resolve
  SecurityKeyIdentifier: 'SecurityKeyIdentifier
      (
IsReadOnly = False,
Count = 1,
Clause[0] = System.IdentityModel.Tokens.NamedKeySecurityKeyIdentifierClause
) ',

RawData: eyJ0eXAiOiJ......
token:
  '{"typ":"JWT","alg":"RS256","kid":"-sxMJMLCIDWMTPvZyJ6tx-CDxw0"}.{"aud":"d03a8a86-2d38-4017-a8e6-d1813c7a8b99","iss":"https://login.microsoftonline.com/03afca2b-f47f-4d0b-9a25-d464aff5d399/v2.0","iat":1550228705,"nbf":1550228705,"exp":1550232605,"aio":"ATQAy/8KAAAAJ5N6SdnFdK7rYxWxvwbUKLAjZesFNkwaj2jR7tQg+E10FU5giL0DQM7SWbfwwYNG","name":"GFSSD
  TEST","oid":"ea10e59f-4466-451c-b7df-e9727ae5b899","preferred_username":"gfssd@mycompany.com","sub":"aPg-fkuZz4lwGIPSGbQ-nOoj7BPwT4_bBsb9UvATAdI","tid":"03afca2b-f47f-4d0b-9a25-d464aff5d399","uti":"tpY2tvyphUib1O2N4wIQAA","ver":"2.0"}
Microsoft.Azure.AppService.Middleware Information: 0 : Sending response: 401.83 Unauthorized

Any ideas why it doesn't seem to authorize properly?
EDIT:


text:
Q: The identity $(u\times v)\cdot(x\times y)=\begin{vmatrix}u\cdot x&v\cdot x\\ u\cdot y&v\cdot y\\\end{vmatrix}$ I know by brutal calculation this identity holds always:
$$(u × v) \cdot (x × y) = \begin{vmatrix}
u \cdot x & v \cdot x \\
u \cdot y & v \cdot y \\
 \end{vmatrix}$$
for arbitrary vectors $u$, $v$, $x$, $y$.
I'd like to know where it come from naturally.
Thank you.

A: I suppose you are talking about dot products and cross products in $\mathbb R^3$. The identity can be seen as a special case of Cauchy-Binet formula. Alternatively, note that
$$
\pmatrix{x^T\\ y^T\\ (u\times v)^T}\pmatrix{u&v&x\times y}
=\pmatrix{u\cdot x&v\cdot x&0\\ u\cdot y&v\cdot y&0\\ 0&0&(u\times v)\cdot(x\times y)}.\tag{1}
$$
Therefore the RHS has determinant
$$
\det\pmatrix{u\cdot x&v\cdot x\\ u\cdot y&v\cdot y}[(u\times v)\cdot(x\times y)].\tag{2}
$$
On the other hand, since $\det\pmatrix{p&q&r}\equiv(p\times q)\cdot r$ (this actually is the definition of cross product), the LHS of $(1)$ has determinant
$$
[(u\times v)\cdot(x\times y)]^2.\tag{3}
$$
The result now follows by equating $(2)$ and $(3)$ with the use of a continuity argument.

A: Since $\epsilon_{ijk}\epsilon_{ilm}=\delta_{jl}\delta_{km}-\delta_{jm}\delta_{kl}$, the dot product is$$\epsilon_{ijk}u_jv_k\epsilon_{ilm}x_ly_m=(\delta_{jl}\delta_{km}-\delta_{jm}\delta_{kl})u_jv_kx_ly_m=(u\cdot x)(v\cdot y)-(u\cdot y)(v\cdot x)=\begin{vmatrix}
u\cdot x & v\cdot x \\
u\cdot y & v\cdot y \\
\end{vmatrix}.$$This is also the only linear combination of the four vectors, with coefficient $1$ for $u_1v_2x_1y_2$, that's symmetric under simultaneously exchanging $u,\,x$ and $v,\,y$, but antisymmetric under exchanging $u$ with $v$, or $x$ with $y$.


text:
Q: How to load local data into js file variable? I am doing an IoT device simulator and I have a dataset of readings that I want to send to the IoT hub. The file I am working on is here. I change it to
var data = ???;
data.forEach(function(e){
    state.pressure = e;
    updateState(state);
    log("Pressure increased to " + state.pressure);
    sleep(1000);
})

I have a file with all the data I need. Is there any way I can load the data into the file as a variable (var data) of the current js file.
function getData() {
var data =
{
    "example": [999,999]
};

return data.example;
}

export function getEventData() {
 getData();
}

It give me an error : JS function failure, {"Message":"Line 14: Unexpected reserved word","FullName":"Jint.Parser.ParserException"}
and the 14 line : import { getEventData } from "./HavenEventData"

A: There are three different supported languages to upload data into IOT hub, this would also work for the simulation scenario, the current documentation shows .NET, JAVA, Node.js.

Once you associate an Azure storage account to the IoT Hub, IoT hub generates a SAS URI. A device can use this SAS URI to securely upload a file to a blob container. The IoT Hub service and the device SDKs coordinate the process that generates the SAS URI and makes it available to a device to use to upload a file.

Source is here, I'd recommend to check it out since it has examples.
an example of a Method using C# is as follow:
private static async void SendToBlobAsync()
{
    string fileName = "image.jpg";
    Console.WriteLine("Uploading file: {0}", fileName);
    var watch = System.Diagnostics.Stopwatch.StartNew();

    using (var sourceData = new FileStream(@"image.jpg", FileMode.Open))
    {
        await deviceClient.UploadToBlobAsync(fileName, sourceData);
    }

    watch.Stop();
    Console.WriteLine("Time to upload file: {0}ms\n", watch.ElapsedMilliseconds);
}

Let me know if this helps.

A: you need to do var data = require('path_to_you_file') (but i am assuming its a json file) is it ?


text:
Q: Why does MySQL only return 1 row when using the 'where in' clause with a prepared statement? I have some PHP code to extract pupils from a database who have been assigned to the current user.
The query for extracting the pupils is:
$pupilsql = $db->prepare("SELECT * FROM pupil where id in (?)");
$pupilsql->bind_param("s", $dbpupils);
$pupilsql->execute();
$pupilresult = $pupilsql->get_result();

Where $dbpupils is a comma seperated list of student ID's (1,2,3 for example.)
However, the database will only return the pupil which matches the first ID in the list.
I have run the query with hard coded values like so:
$pupilsql = $db->prepare("SELECT * FROM pupil where id in (1,2,3)");

And can verify that it returns the 3 expected pupils.
I have also tried changing the bind_param data type to d instead of s to no avail.
Why will the query not return all 3 pupils when the ID's are stored in a variable?
Edit: My $dbpupils variable is not an array and so cannot be treated as one.


text:
Q: Streaming a section of video to an external display I want to be able to connect an external display to my Windows PC (in addition to the existing one), and stream a selected portion of the screen to this display. For example, if I have a small terminal window open on my main monitor, then this smaller display will show only that terminal window, not the rest of my desktop. I guess it's like Picture In Picture (PIP) on a TV, but for a PC instead.
Can anyone recommend the easiest way to achieve this? I don't mind getting into the video programming side of it (maybe using DirectShow?), but if there is a hardware solution, eg on a DSP board,then that would be great.

A: This is probably off-topic, because the easiest way to achieve this is to use the tools already provided by your graphics card.
Mirror your display, adjust the resolution of your screen to that of the window, and pan the screen until the desired area is displayed.
If you want to be able to select an arbitrary window to be mirrored, you need to add this functionality to your window manager, which is impossible on Windows (but should be doable for most Linux window managers).  If you want to do this with an app you're developing (or an open-source terminal), just use a second display.

A: would a usb display work? http://www.mimomonitors.com/products/mimo-720-s  it may be easier then trying to stream part of the window and sending it to a display.
the other option i can see working is if you have a second vga or DVI port and adding a cheap LCD monitor to clone or extend your desktop
not trying to be discouraging but what you want to do would require you to create a PC program to send that part of the screen ( not sure how in SW) and a communication line like a serial port or usb to control your display.
Edit: after rethinking the whole issue, I would still use a prebuilt solution, but if you want something from scratch, you could get an ARM processor(cortex-Mx) add a LCD screen (your choice on resolution) and build an API so you can send straight data to draw the screen through the com port(rs232 serial) or use Ethernet connection.

A: Your graphics card driver can put windowed video played in a video player to some external monitor or TV in full screen. If we are not talking about video, but just a window of some software application running on your pc, then you can use UltraVNC and share just that single window for displaying on remote pc.


text:
Q: How to test ios11 promoted In-App Purchases Apple introduced Promoted In-App Purchases in iOS 11.  Though I have implemented the new required SKPaymentTransactionObserver method, paymentQueue:shouldAddStorePayment:for:, I have not been able to successfully test "buying" an item.  Should one be able to test and purchase in the Sandbox test environment?
Apple does discuss initiating testing through an URL of the form:
itms-services://?action=purchaseIntent&bundleId=com.example.app&productIdentifier=com.example.app.myIAP
I've put the URL in an email to myself. When I click on the URL, I get the following sequence:
1) Switches to MyApp, and shouldAddStorePayment is called with a product with my product identifier, com.example.app.myIAP  (encouraging start)
2) Have paymentQueue:shouldAddStorePayment:for: return true.
3) paymentQueue:updatedTransactions: is called, with a transaction in the "purchasing" (but not purchased) state. It has a nil transactionIdentifier.
4) An alert pops up saying to Sign In. I sign in with a sandbox Apple ID - hitting the "Buy" button on the sign in alert.
5) Another pop up saying to Sign In. I sign in with a sandbox Apple ID - hitting the "Buy" button on the sign in alert.
6) paymentQueue:updatedTransactions: is called, with a transaction in the "failed" state. It has a non-nil transactionIdentifier.
Should the shouldAddStorePayment routine be doing something extra?

A: I submitted the app with the limited testing as described above.  And I was able to do real purchases of promoted in-app-purchases.
But there is a chicken and egg scenario here.  Now that the items are in the store, I can run against a local/debug build and test from the App Store.  But I think I also burned through several Sandbox User IDs trying things out.
Following is a sequence that I can now do.
1) Go to App Store and log out.
2) Build/run your app and use Restore Purchases - logging in with your Sandbox User ID/password.
3) Verify that your Sandbox User is now logged into the App Store (do not log in directly to the App Store with Sandbox User or that user will no longer work.)
4) Find your app and then find the In-App Purchases section with the promoted features.  Select a promoted in-app purchase feature.
5) Your app is loaded.  After a bit, one gets an alert with: Confirm Your In-App Purchase ---- Do you want to buy XXXX for $0.99?    --- [Environment: Sandbox]   ----  Cancel / Buy
6) After purchase one gets the alert:  You're all set.  ----  Your purchase was successful.   ---- [Environment: Sandbox]   ----  OK
7) if you do this on an item your Sandbox User has already purchased, you get an alert with:  You've already purchased this.  Would you like to get it again for free?   ----  [Environment: Sandbox]  ----   Cancel / OK
The point of the above is that you get alert messages like what you saw before rather than the receipt type item popping up from the bottom that you get when you do a real purchase.
Hope this helps, but still not a good answer for first time through.


text:
Q: * is being replaced by current folders file list I am performing a grep on a file which is resulting in a single line output. This output has * as data in it. In the shell script I am trying to assign the value to a variable but * is being replaced with the file list in the current folder.
Eg:
My script name is script1.sh and I have another file script2.sh in the same directory.
The content of the script is
VAR1=`grep pattern search_file`
echo $VAR1

The intended output would be

The pattern is *

But the output I am getting is

The pattern is script1.sh script2.sh

Kindly let me know what is that I am doing wrong.

A: You simply need to quote the variable: echo "$VAR1"
If you look at the sequence of bash shell expansions, you'll notice that filename expansion occurs after parameter expansion. Unquoted variables will be subsequently subjected to word splitting and filename expansion.

A: You need to escape the * with \, otherwise it treats it as a wild-card that matches filenames in the current directory.
\*

A: use set -f shell option will disable globbing in sub-shells and interactive session.
use set +f to enable globbing again.


text:
Q: Correct SHA256 implementation with UTF-8 characters I'm running into issues comparing SHA256 hashes generated by different languages/functions.
For example, SHA256("í") either returns:
f3df1f9c358ae8eceb8fce7c00614288d113ad55315f4ebb909774a7daadfc84

-or-
127035a8ff26256ea0541b5add6dcc3ecdaeea603e606f84e0fd63492fbab2c5

Which of the above hash is correct for a string of one character, and what's the correct way of handling UTF-8 strings?

A:
Which of the above hash is correct for a string of one character

There is no "correct" answer. What's being hashed is the bytes, not the "character". What bytes are hashed exactly depends on the encoding of the string.
"í" in Windows-1252 is byte ED, which hashes as:
f3df1f9c358ae8eceb8fce7c00614288d113ad55315f4ebb909774a7daadfc84

"í" in UTF-8 is bytes C3 AD, which hashes as:
127035a8ff26256ea0541b5add6dcc3ecdaeea603e606f84e0fd63492fbab2c5

"í" in UTF-16LE is bytes ED 00, which hashes as:
430e2ca27910b5ee6e0ec56a12b81325c763376cb8e25a60362dce9444424f95

How exactly that works in various programming languages depends on the languages and the encodings they use for strings.


text:
Q: В windows 7 всё работает, а в  windoes 8 NullPointException Такая ситуация странная. Мой проект хорошо запускается и работает под windows 7 и в Ubuntu, а вот под windows 8 выдает ошибку NullPointException.
С чем это может быть связанно?
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{ru.ldpr.balashov.ldprbeta/ru.ldpr.balashov.ldpr.NewsActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
        at android.app.ActivityThread.access$600(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at ru.ldpr.balashov.ldpr.NewsActivity.onCreate(NewsActivity.java:56)
        at android.app.Activity.performCreate(Activity.java:5104)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)


text:
Q: How can list[n] point to list[0]? Getting items not in sequence I'm not sure about the term of this technique. I want to create a list where if I try to access an element outside the list range, the list would "loop itself". Example of the behaviour I want to achieve:
>>> musical_scale = ['C', 'D', 'E', 'F', 'G', 'A', 'B']
>>> musical_scale[2]
E
>>> musical_scale[7]
C
>>> musical_scale[-1]
B

I guess I could write a class which does this, but I thought there might be a more correct way of doing it.

A: Creating a subclass of List would be a pretty useful way of doing this. Something like this, perhaps:
class modList(list):

  def __getitem__(self, i):
    if len(self) == 0:
      raise IndexError   # Or do something else if you want, like return []
    i = i % len(self)   # self.__len__() works also
    return super(modList, self).__getitem__(i)   # In Python 3, super().__getitem__(i)

If you want to do slicing, it's a little more complicated, but similar. Found this while looking through StackOverflow:
  def __getitem__(self, i):
    if isinstance(i, int):
      if len(self) == 0:
        raise IndexError
      i = i % len(self)
      return super(modList, self).__getitem__(i)   # list.__getitem__(i) works too
    elif isinstance(i, slice):
      if len(self) == 0:
        return []
      start = i.start % len(self)
      stop = i.stop % len(self)
      step = i.step
      return super(modList, self).__getItem__(slice(start, stop, step))
    else:
      raise TypeError("invalid index")

Though this slice modding could give you a situation like [3:2], which will return an empty list. Basically slicing is hard and you'll need to decide how you want to implement it, but hopefully this is a start.
http://www.stackoverflow.com/questions/3911483/python-slice-how-to-i-know-the-python-slice-but-how-can-i-use-built-in-slice-ob
(Thanks @JonClements for all the suggestions in chat.)
EDIT: now we have some handlers for if you have an empty list. @wim suggests raising an error for single accesses, and returning [] for slices. Really it's up to you what you want to do but that seemed sensible to me, so that's what I've included in this answer.
EDIT EDIT: if you're using Python 2.x, I believe you also need to override __getslice__.

A: Use the modulus operator % to "loop back" after indexing past the end of the list
>>> musical_scale = ['C', 'D', 'E', 'F', 'G', 'A', 'B']

def getValue(x, l):
    return l[x % len(l)]

>>> getValue(0, musical_scale)
'C'
>>> getValue(9, musical_scale)
'E'

A: In case you'd like to extend the list class to handle getting and setting...
class UnsatList(list):
    def __getitem__(self, index):
        try:
            return list.__getitem__(self, index % len(self))
        except ZeroDivisionError:
            raise IndexError('list assignment index out of range')

    def __setitem__(self, index, value):
        try:
            return list.__setitem__(self, index % len(self), value)
        except ZeroDivisionError:
            raise IndexError('list assignment index out of range')

if __name__ == '__main__':
    test_list = UnsatList([1,2,3,4])
    assert test_list[0] == 1
    assert test_list[4] == 1
    assert test_list[8] == 1
    assert test_list[-8] == 1
    test_list[4] = 5
    assert test_list[0] == 5
    assert test_list[4] == 5
    assert test_list[8] == 5
    assert test_list[-8] == 5

A: Here is a solution, but remember The Zen of Python: Flat is better than nested.
You can write for example:
a = [1, [2]]
a[1].append(a)

Then your list a has "infinite depth", and you can loop on these two elements by repeatedly doing:
a[0]
a = a[1]

You can't do that without playing with depth, because unlike e.g. Lisp, Python lists are varying-length arrays, not linked-lists.
Here are little functions to do the whole stuff automatically:
def loopify(a):
    r = b = []
    for x in a:
        b.append(x)
        b.append([])
        c = b
        b = b[1]
    c[1] = r
    return r

def loopgen(a):
    while True:
        yield a[0]
        a = a[1]

Then with your example:
musical_scale = loopify(['C', 'D', 'E', 'F', 'G', 'A', 'B'])
g = loopgen(musical_scale)
[next(g) for i in range(20)]

This yields:
['C', 'D', 'E', 'F', 'G', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'A']
Of course, it's also possible to use mod or to keep track of the current index and reseting it to 0 when you overflow your list. Other answers show you how to do that.
Also notice that the linked-list approach does not permit random access, only sequential access (thus the generator above). If you need to access you list randomly, modular arithmetic is the most appropriate way.


text: Q: qtpropertybrowser height of a single line changeable? I'm working with qtpropertybrowser right now and I want to expend this with a new ability. When I click on the editor, it shows me a QLabel and a QToolButton, with the button I can choose a imagefile, the filename will be shown on the QLabel. When I left editor, it shows me the image.  I wrote my own manager and editorfactory, all is working.  But it shows me the image only in size of an icon ( I used the valueIcon methode for this). Is there a way to change the height of the line so the image shown is bigger?


text:
Q: AIR App Crashing with Adobe Scout I am trying to profile my mobile game with Adobe Scout. It is based on Starling, AIR 4.0 and currently it is live on Play Store. Since it gives poor performance on iPhone4, I decided to profile using Adobe Scout. I am getting a release build with -advanced-telemetry option and I have set up my .telemetry.cfg on my PC as described here. I have installed Adobe Scout app on the device I am testing. I managed to connect my device with the PC having Scout, however, after receiving some data (like 20-30 frames), application crashes on the phone.
What may be the cause of this?
Thanks.


text:
Q: Postgres query find UNique Latest entry I have a Postgres Table named ip_storage_table and it is storing three values ip_address , virtual_id and a time_stamp
The actual relation between this is initially all I/Ps are having a virtual_id associated with it for eg:
192.168.1.1 has 1000 at 2015-07-20 15:00:00
192.168.1.2 has 2000 at 2015-07-20 15:00:00
192.168.1.3 has 3000 at 2015-07-20 15:00:00

This table contains the virtual_id of each I/P address at a particular time stamp so it can have more entries like
192.168.1.1 has 3000 at 2015-07-20 16:00:00
192.168.1.2 has 1000 at 2015-07-20 16:00:00
192.168.1.3 has 2000 at 2015-07-20 16:00:00
192.168.1.2 has 4000 at 2015-07-20 17:00:00
192.168.1.1 has 2000 at 2015-07-20 18:00:00

I want to run a query such that:

*

*The virtual_id comes only once in the output

*The i/p associated with the virtual_id should come with it

*and the virtual_id should be latest i.e. in above example 2000 will be with 192.168.1.1 and at 18:00:00 timestamp and all its previous values wont be displayed

*If two virtual id's have the same i/p , only the latest one appears in the output

I could have uploaded an image of the database, but I am using Linux and unable to find image editing tools, if you can't get a view of database with above description let me know, I will try again

A: If I understand correctly, you can use distinct on:
select distinct on (virtual_id) t.*
from mytable t
order by virtual_id, time_stamp desc;

This will return each virtual_id with its more recent row.

A: You can simply try:-
SELECT i/p, MIN(virtual_id), MAX(timestamp)
FROM YOUR_TABLE
GROUP BY i/p;

Hope this helps.
See the fiddle. http://sqlfiddle.com/#!15/d7905/5


text:
Q: How to disable stack trace for release configuration in c# I have written specflow tests for HttpWebRequest. When I run them in teamcity server, for every failed assertion I get stack trace. I do not want stack trace to be reported in log. I use release configuartion for running the tests and run vstestconsole as test runner....Thanks for your solution in advance.
Assert.AreEqual failed. Expected:<404 Not Found>. Actual:<200 OK>. Status "200 OK" returned by request  does not match with expected status of "404 Not Found"
[15:22:39][Step 3/3] Stack Trace:
[15:22:39][Step 3/3]    at abc.API.xyz.Tests.Steps.GeneralSteps.CheckStatusCode(String statusCode)
[15:22:39][Step 3/3]    at lambda_method(Closure , IContextManager , String )
[15:22:39][Step 3/3]    at TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration)
[15:22:39][Step 3/3]    at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStepMatch(BindingMatch match, Object[] arguments)
[15:22:39][Step 3/3]    at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(IContextManager contextManager, StepInstance stepInstance)
[15:22:39][Step 3/3]    at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnAfterLastStep()```


text:
Q: Multidimensional array to CSV - while A) preserving keys AND B) different length of arrays Answers to "normal" flattening of MultidimArrays I have found galore - but I could not find a solution which works with these 2 caveats:
A) keep the keys and
B) different length of arrays
e.g. I´m trying to convert this:
array(2) {
  [0]=>
  array(5) {
    ["Name"]=>
    string(9) "Max Muster"
    ["phoneNumbers"]=>
    array(3) {
      [0]=>
      string(7) "1234567"
      [1]=>
      string(7) "2345678"
    }
    ["manager"]=>
    string(13) "None - is CEO"
  }
  [1]=>
  array(5) {
    ["Name"]=>
    string(9) "Ada Brown"
    ["phoneNumbers"]=>
    array(1) {
      [0]=>
      string(7) "AJP4564"
    }
    ["manager"]=>
    string(10) "Max Muster"
  }

to this:
Name, Max Muster, phoneNumbers, 1234567, 2345678, manager, None - is CEO, Name, Ada Brown, phoneNumbers, AJP4564, manager, Max Muster

...to use in a csv
But this (short, nice) solution loses the keys:
foreach ($arrayMultiDim as $onePerson) {
$arrayOneDim = [];
array_walk_recursive(
    $onePerson,
    function ($oneDim) use (&$arrayOneDim) {
        $arrayOneDim[] = $oneDim . ', ';
    }
);
}

Bonus: Where do I add '&nbsp' or ';' to create a new line before writing to CSV?
And how do I avoid the ',' after the last value on a line?
To ideally create sth. like this:
Name, Max Muster, phoneNumbers, 1234567, 2345678, manager, None - is CEO
Name, Ada Brown, phoneNumbers, AJP4564, manager, Max Muster

A: The function array_walk_recursive will ignore the parent keys. So i think the best method is to write a new recursive function, that will not ignore them. The function array_to_csv below iterates over the part of your array, adds the key to the output (if it is not numeric because: the tel numbers will have 0 and 1 etc as keys). Then it checks if the actual value is an array and calls the function recursive. If it is not an array, it adds the value to the output. After that it returns the result.
The function:
function array_to_csv( $array, &$out = array() ) {
  foreach( $array as $key => $value ) {
    if( !is_numeric( $key ) ) {
      $out[] = $key;
    }
    if( is_array( $value ) )  {
      array_to_csv( $value, $out );
    } else {
      $out[] = $value;
    }
  }
  return $out;
}

In this foreach it iterates over your array and calls the function with every item (or line) of your array. Then it implodes the return and adds the ; at the end.
The function call:
$csv_array = array();
foreach( $arrayMultiDim as $array ) {
  $csv_array[] = implode(', ', array_to_csv( $array ) ) . ';';
}

Your result is stored in $csv_array
Array
(
    [0] => Name, Max Muster, phoneNumbers, 1234567, 2345678, manager, None - is CEO;
    [1] => Name, Ada Brown, phoneNumbers, AJP4564, manager, Max Muster;
)


text:
Q: How to make components explicit in what props they accept? Is there any known practice to make a React component constructor explicit in what arguments it accepts?
Looking at a component like below, I cannot immediately tell what do I need to pass to the constructor to initialize the component.
Instead, I need to search for specific props in the component body or check how has the component been initialized previously (if it has).
class MenuItem extends React.Component {
     constructor(props) {
         super(props)
    }

    render() {
        return

    }
}

I would need something like:
class MenuItem extends React.Component {
         constructor(name) {...

A: There is several options to type your props.
The first one is React PropTypes, it works like this:
import PropTypes from 'prop-types';

class MenuItem extends React.Component {
     constructor(props) {
         super(props)
    }

    render() {
        return

    }
}

MenuItem.propTypes = {
  name: PropTypes.string.isRequired
}

You just have to write the name and types of your props inside an attribute "propTypes" of your component class.
React PropTypes is a good solution when you want to type your component props.
https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes
There is another solution, a Javascript Flavor like Typescript.
After setting up Typescript on your React app, you can use Typescript with your component like this:
interface IMenuItem {
  name: string;
}

class MenuItem extends React.Component<IMenuItem> {
     constructor(props) {
         super(props)
    }

    render() {
        return

    }
}

The advantage with Typescript is that you can type every variable, every state, every props, everything !
However, this solution is expensive in time because you have to learn well Typescript and you have to type correctly every piece of your app.
https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html
Finally, if you just want your IDE to tells you what props you can use without typing them, you can just use object destructuring on your props with a Functional Component like this:
const MenuItem = ({name}) => (

{name}

)

Hope this will help !

A: You can explicitly show what props your component accepts, including their types.
MenuItem.propTypes = {
  name: PropTypes.string // optional string
};

You can even define them as required:
MenuItem.propTypes = {
  name: PropTypes.string.isRequired // required string
};

Be sure to import the library:
import PropTypes from 'prop-types';

*

*More information in the react docs

A: If your concerns are mainly about visibility you may be better off only writing functional components which is possible since hooks do not require any class components anymore:
const MenuItem = ({name}) => (

{name}

)

Buy destructuring the props in the argument list you can easily see which props are being used immediately just by looking at the function definition. From my experience writing 100's of components, functional components are usually more concise, easier to grasp and reduce boilerplate code.
Apart from that javascript is still a scripting language which means anything can be passed at runtime. PropTypes or using typescript may help you with auto-completion and type checking.

A: Adding to Sinane's great answer, when using classes (without TypeScript), it is still not obvious what props are required when you read code with a large class, as the PropTypes definition has to go below the class in the code. Thus I like to add in-code comments as per below. Sure, the comments can fall out of date, so the coder has to be disciplined.
import PropTypes from 'prop-types';

class MenuItem extends React.Component {
    // -----
    // Props
    // -----
    // name: PropTypes.string.isRequired

    constructor(props) {
        super(props)
    }

    render() {
        return

    }
}

MenuItem.propTypes = {
    name: PropTypes.string.isRequired
}

I also use the same comments for functional components, as the typing is missing.
const MenuItem = ({name}) => (
    // -----
    // Props
    // -----
    // name: PropTypes.string.isRequired

{name}

)


text:
Q: How do I use completion handlers in Fire Base I have trouble understanding how to properly using completion handlers, especially in relation to firebase code. As I understand it, the completion handler executes when the Fire Base has done it's thing asynchronously, right. So just to get a feel on how it works, I just want to use completion handlers to print "DONE" when the data has been gathered with FB.
I have tried the following code, but I obviously don't understand it as it doesn't work.
//PUTTING THE FB CODE IN FUNCTION
func test(completion: @escaping (String) -> Void) {

   databaseRef.child(dataRecieverStringRecipeView!).observeSingleEvent(of: .value, with: {(snapshot) in
        for item in snapshot.children.allObjects as! [DataSnapshot] {
            let thisItem = item.value as! NSDictionary

            let tempRecipe = Recipe()
            tempRecipe.fbKey = item.key
            tempRecipe.recipeHeaderObject = (thisItem["recipeHeaderFirebase"] as! String)
            tempRecipe.recipeTextObject = (thisItem["recipeIngredientsTextFirebase"] as! String)
            tempRecipe.recipeImageObject = (thisItem["recipeImageFirebase"] as! String)

            self.recipeClassArray.append(tempRecipe) //ADD OBJECT TO ARRAY
        }

    }) //END LOOP
       completion("DONE")

 }//COMPLETION
test()//???Not sure what to do here...

A: Completion handlers are basically WHEN statements.
When an event happens (for example receiving result of an api call), trigger completion().You can also pass values with this completion.
func test(completion: @escaping (_ message: String) -> Void) {

   databaseRef.child(dataRecieverStringRecipeView!).observeSingleEvent(of: .value, with: {(snapshot) in
        //you are inside a completion handler. this code executes WHEN you've received a snapshot object

        // so you loop through and process the items
        for item in snapshot.children.allObjects as! [DataSnapshot] {
            let thisItem = item.value as! NSDictionary

            let tempRecipe = Recipe()
            tempRecipe.fbKey = item.key
            tempRecipe.recipeHeaderObject = (thisItem["recipeHeaderFirebase"] as! String)
            tempRecipe.recipeTextObject = (thisItem["recipeIngredientsTextFirebase"] as! String)
            tempRecipe.recipeImageObject = (thisItem["recipeImageFirebase"] as! String)

            self.recipeClassArray.append(tempRecipe) //ADD OBJECT TO ARRAY
        }

        // and its done here
        completion("DONE")

    })

 }

 // Now to use it...
 // You need to pass in a completion handler varaible to your test function when calling it
 test(completion: { message in
     // WHEN you get a callback from the completion handler,
        print(message)

 })

A: You need to pass a closure to your test() method, like this:
test(completion: (status: String) -> Void {
   print(status)
})
Or like this:
func completion(status: String) {
    print(status)
}
test(completion: completion)
You could also use trailing closure syntax, since your closure is the last parameter:
test() { (status) in
    print(status)
}


text:
Q: Cubic Jacobi sum If $\psi_\pi= \left( \frac{-}{\pi} \right)_3$ is the cubic residue character and $\pi$ is a prime with $\pi \not \equiv0 \text{ mod }3$, then is it true that $$J(\psi_\pi, \psi_\pi)=-\sum_{i=1}^{p-1}\psi_\pi(i)\psi_\pi(1-i)=\pi?$$
In Lemmermayer's book on reciprocity laws it's proven to be true if $\pi \equiv 1 \text{ mod }3$, but what about for other values of  $\pi$ with $\pi \overline{\pi} \equiv 1 \text{ mod }3$?

Background: in Lemmermayer's book, the proof for $\pi \equiv 1 \text{ mod }3$ proceeds thusly:
But then later in the proof of the cubic reciprocity law, of which the first page is as follows:
Lemmermayer suddenly seems to use the Gauss sum factorisation as $G(\psi)=\pi^2 \overline{\pi}$, which is equivalent to $J(\psi, \psi)=\pi $, for values of $\pi$ with $\pi \not \equiv 1 \text{ mod }3$. At this point I became confused and asked this question.


text:
Q: How To Get HTTP Status Codes From Qt QWebEngineView? I've been looking through the QT docs to find a way to return the http status codes from a QWebEngineView after loading a page, and making a request. I understand that QWebEngineView does not interact with QNetWorkAccessManager which would make this a breeze to accomplish. So is there any other way to get the HTTP status code from a request using QWebEngineView?? I tried multiple ways including RequestInterceptor. Below is a snippet of my attempt using RequestInterceptor, but its not giving me actual HTTP Status codes, just constant values, which is what I dont want.
 /*************requestinterceptor.h**************/
#ifndef REQUESTINTERCEPTOR_H
#define REQUESTINTERCEPTOR_H

#include <QWebEngineUrlRequestInterceptor>
#include <QWebEngineUrlRequestInfo>
#include <QDebug>
#include <QUrl>

class RequestInterceptor : public QWebEngineUrlRequestInterceptor
{
      public:
      explicit RequestInterceptor(QObject * parent = Q_NULLPTR);
       virtual void interceptRequest(QWebEngineUrlRequestInfo & info) Q_DECL_OVERRIDE;
};
  #endif // REQUESTINTERCEPTOR_H

/*************requestinterceptor.cpp***************/

  #include "requestinterceptor.h"

  RequestInterceptor::RequestInterceptor(QObject * parent)
 :QWebEngineUrlRequestInterceptor(parent){}

 void RequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo & info)
  {
  QString rsrct = "";
 switch(info.resourceType())
  {
      case 1:rsrct="ResourceTypeSubFrame, --> frame or iframe";break;
      case 2:rsrct="ResourceTypeStylesheet, --> a CSS stylesheet";break;
      case 3:rsrct="ResourceTypeScript, --> an external script";break;
      case 4:rsrct="ResourceTypeImage, --> an image (jpg/gif/png/etc)";break;
      case 5:rsrct="ResourceTypeFontResource, --> a font";break;
      case 6:rsrct="ResourceTypeSubResource, --> an other subresource.";break;
      case 7:rsrct="ResourceTypeObject, --> an object (or embed) tag for a plugin,";break;
      case 8:rsrct="ResourceTypeMedia, --> a media resource.";break;
      case 9:rsrct="ResourceTypeWorker, --> the main resource of a dedicated worker.";break;
      case 10:rsrct="ResourceTypeSharedWorker, --> the main resource of a shared worker.";break;
      case 11:rsrct="ResourceTypePrefetch, --> an explicitly requested prefetch";break;
      case 12:rsrct="ResourceTypeFavicon, --> a favicon";break;
      case 13:rsrct="ResourceTypeXhr, --> a XMLHttpRequest";break;
      case 14:rsrct="ResourceTypePing, --> a ping request for <a ping>";break;
      case 15:rsrct="ResourceTypeServiceWorker, --> the main resource of a service worker.";break;
  case 16:rsrct="ResourceTypeUnknown";break;

  default : rsrct="Unknown type";break;
}

qDebug()<<"\t"<<Q_FUNC_INFO<<":\n\t\t" <<
"WebUrlRequestInterceptor::interceptRequest    " <<info.requestMethod()
   <<"\r\n  "<<info.requestUrl()<<"   "<<rsrct      <<"\r\n";
}

  /*************mainwindow.cpp***************/
 const QUrl url("http://google.com");
 view = new WebView();
 view = new QWebEngineView();
 interceptor = new RequestInterceptor(view);
 profile = new QWebEngineProfile(view);
 profile->setRequestInterceptor(interceptor);
 page = new QWebEnginePage(profile,view);
 view->setPage(page);

A: after hours searching, I found it is impossible to get HTTP status code via QWebEngine at the moment. load completed event doesn't return any status code as well
then I found a solution
setting = webpage.settings()
setting.setAttribute(QWebEngineSettings.ErrorPageEnabled, False)


text:
Q: How can I use gulp concat with a mix of remote and local files? This is not working very well:
gulp.task('dev', function () {
    console.log('concatenating development libs...')

    var log = function (file, cb) {
        console.log(file.path);
        cb(null, file);
    };

    var zocialCss = 'zocial-flat.css';
    request('http://my.blob.core.windows.net/shared-styles-webfonts/zocial-flat.css')
        .pipe(fs2.createWriteStream(zocialCss));

    var cssFiles = [
        './' + zocialCss,
        '../bower_components/**/bootstrap.css',
    ];

    fs.src(cssFiles)
        .pipe(map(log))
        .pipe(concat('styles.css'))
        .pipe(gulp.dest(stylesPath));
});

My guess is fs2.createWriteStream(zocialCss) keeps the file locked (or open for writing) and it never closes, so concat ignores it (or silently fails). I can see zocial-flat.css being generated as expected (I would, by the way, like to delete the file after concatenation).
I have seen alternatives to this approach (like gulp-remote-src) and am open to any such suggestions.


text:
Q: Auto-renewable Subscriptions an unknown error occurred In my iPad application I used to use old model for subscriptions and I made it work just fine. Since last Tuesday (15th Feb. 2011) Apple introduced a new model for subscriptions: auto-renewable.
After creating a product in iTunes Connect for the new type of subscription and replacing it with old one, I am experiencing an unknown error. To be more specific the whole transaction goes well, the user can confirm buying product, but then the transaction is not processed at all and is failing with pop-up:

An unknown error occurred. Retry. Cancel

I've searched the web for some solutions, but all of them are about cases of using old model for subscription. Any suggestions?
Thanks in advance.

A: Try this article on Invalid Product IDs. While it doesn't specifically address your error. I would bet the steps it suggests you take are likely to clear up your problem.


text:
Q: Laravel Eloquent concat and groupBy() AND return one title of each group I have a table that contains, amongst other columns, a column of browser versions. And I simply want to know from the record-set, how many of each type of browser there are.
my code is :
$whereBrowser = [['owner', '=', 12]];
        $browser = ProfileTracker::where($whereBrowser)->whereBetween('created_at', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()])->select([
            DB::raw('browser'),
            DB::raw('COUNT(browser) as value')
        ])->groupBy("browser")->orderBy("value", "desc")->take(10)->get();

output :
          "browser": [
              {
                  "browser": "Chrome Mobile 84",
                  "value": 144
              },
              {
                  "browser": "Chrome Mobile 80",
                  "value": 84
              },
              {
                  "browser": "Chrome 84",
                  "value": 27
              },
              {
                  "browser": "Chrome 30",
                  "value": 22
              },
              {
                  "browser": "Chrome Mobile 83",
                  "value": 19
              },
              {
                  "browser": "Chrome Mobile 47",
                  "value": 10
              },
              {
                  "browser": "Firefox 79",
                  "value": 8
              },
              {
                  "browser": "Mobile Safari",
                  "value": 8
              },
              {
                  "browser": "Mobile Safari 13.1.2",
                  "value": 6
              }
          ],

      }

I want to group all browsers, without the browser version like this:
            "browser": [
                {
                    "browser": "Chrome",
                    "value": 306
                },
                {
                    "browser": "Safari",
                    "value": 14
                },
                {
                    "browser": "Firefox",
                    "value": 8
                },
            ],

        }

A: One way you can pull this off is to look for browser names in strings and parse them to just the browser name in the query. So something like Mobile Safari 15.1.2 will be parsed to Safari:
ProfileTracker::selectRaw('
    CASE
        WHEN browser LIKE '%firefox%' THEN 'Firefox'
        WHEN browser LIKE '%chrome%' THEN 'Chrome'
        WHEN browser LIKE '%safari%' THEN 'Safari'
    END AS browser_name,
    count(1) AS count
')->groupBy('browser_name')->get();

Please note that I have removed parts of the query builder, to make this example a little more readable. You can add back whatever you need yourself.
This will give you:
Chrome  1
Firefox 1
Safari  2

My test data is:
"Chrome Mobile"
"Firefox 79"
"Mobile Safari 13.1.2"
"Mobile Safari 15.1.2"

A: you can substr browser name by using SUBSTRING_INDEX function to extract first string  :
      $browser = ProfileTracker::where($whereBrowser)
      ->selectRaw("browser,SUBSTRING_INDEX(browser, ' ', 1) AS BrowserName,COUNT(browser) as value")
      ->whereBetween('created_at', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()])
      ->groupBy("BrowserName")->orderBy("value", "desc")->take(10)->get();


text:
Q: Constraints options don't appear in some .xib files Does anyone know why in some .xib files in my Xcode project the icons to add constraints don't show up??
With add constraints icons:

Without add constraints icons:

A: Can you try clicking on one off the inner views like button or label.


text:
Q: How do I reduce this code to one line? I'm very new to javascript, node.js and express.  My question is, how do I refactor the following code to make it one line inside the function?
exports.about = function(req, res){
 var mytime = new Date();
 res.render('about', {title: 'about page', time: mytime.toLocaleDateString() });
};

In other words, is there a way I can compress the var mytime = new Date(); and time: mytime.toLocalDateString() into one statement?

A: See Frits' answer: You can, but is there really any need? It's nice and readable the way you've done it.
But if you really, really want to, this is how:
exports.about = function(req, res){
 res.render('about', {title: 'about page', time: new Date().toLocaleDateString() });
};

It looks a bit odd, but the new Date() part takes precedence, so you don't even needs parens around it (e.g., you don't need time: (new Date()).toLocaleDateString()). You could have them if you want, but they're not necessary.

A: You don't. Readability over brevity. Let the machine do the minifying.

You could write mytime.toLocaleDateString() as (new Date()).toLocaleDateString(), but I wouldn't recommend it.
My prefered styling:
exports.about = function(req, res){
  var mytime = new Date();
  res.render('about', {
    title: 'about page',
    time: mytime.toLocaleDateString()
  });
};

A: ONE LINE
exports.about = function(req, res){ res.render('about', {title: 'about page', time: new Date().toLocaleDateString() }); };

This quite dumb though. There's nothing wrong with your original code.

A: Making this piece of code any shorter won't make it any better. I'd personally make it a little larger, like so:
exports.about = function (req, res) {
    var mytime = new Date();
    res.render('about', {
        title: 'about page',
        time: mytime.toLocaleDateString()
    });
};

*

*I added a space after function since that's what JSLint wants.

*I added a space before the { because that makes it more readable.

*I placed all the object properties on different lines so I don't have to scroll horizontally all day (plus now I can add comments at the end of each property, yay!).

*Finally I replaced the spaces-indentation with tabs because that makes everything align perfectly while only requiring one key-press to remove or go over them (if your caret is at the beginning of the line 4 spaces would require 4 keypresses to move to your code, while a single tab requires just one keypress).

A: You could do,
exports.about = function(req, res){
  res.render('about', {title: 'about page', time: new Date().toLocaleDateString() });
};

But that's about it. I do agree with Frits van Campen.

A: My opinion is that it is better style to remove the mytime var because you are merely getting the current system time, and new Date() makes the intent perfectly clear.
exports.about = function (req, res) {
    res.render('about', {
        title: 'about page',
        time: new Date().toLocaleDateString()
    });
};


text:
Q: How do I Pull in errors when attempting to tweet from an iOS app using the Twitter+OAuth API? How do I properly setup the callback method for a status update using the Twitter+OAuth API? (http://github.com/bengottlieb/Twitter-OAuth-iPhone)
Right now I'm using the following to determine if a request succeeded:
- (void)requestSucceeded:(NSString *)connectionIdentifier {
NSLog(@"Statuses Sent");
//[loadingActionSheet dismissWithClickedButtonIndex:0 animated:YES];
//[loadingActionSheet release];

}
What would I use to determine if a request failed?

A: Reading docs helps, implemented the following to solve my problem:
- (void) requestFailed:(NSString *)connectionIdentifier withError: (NSError *) error; {
NSLog(@"Status Update Failed");
NSLog(@"Error: %@", error);
[loadingActionSheet dismissWithClickedButtonIndex:0 animated:YES];
[loadingActionSheet release];
alert = [[UIAlertView alloc]
         initWithTitle:@"Error" message:@"Twitter did not receive your update, please try again later." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}


text:
Q: why is pyenv still prioritizing the system's python version when I run `python3.x`? I have pyenv installed and everything works pretty well except for one aspect: when I run the command python3.9, my system still points to my system's version of python (3.9.13). However, I would like to make it point to my pyenv installed version when running python3.9:
❯ pyenv versions
  system
  3.7.10
  3.8.10
* 3.9.5 (set by /Users/username/.python-version)
❯ python3
Python 3.9.5 (default, Jul  7 2022, 20:35:58)
[Clang 13.1.6 (clang-1316.0.21.2.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
❯ python3.9
Python 3.9.13 (main, May 24 2022, 21:13:51)
[Clang 13.1.6 (clang-1316.0.21.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

❯ python3.9 --version
Python 3.9.13
❯ python3 --version
Python 3.9.5

Note that the issue occurs just when running python3.9, not python3.
What's wrong in my configuration?


text:
Q: Issue with LinkedIn API call after OAuth authentication I've successfully made my way through the LinkedIn OAuth process (using the REST API - OAuth 1.0a). However I'm having trouble with my first API call after the callback. I set the UserToken, UserTokenSecret and UserVerfier in the library I am writing, and this call this function to get my profile information:
public function getUserProfile()
{
    $consumer = new OAuthConsumer($this->consumer_key, $this->consumer_secret, NULL);
    $auth_token = new OAuthConsumer($this->getUserToken(), $this->getUserTokenSecret());
    $access_token_req = new OAuthRequest("GET", $this->access_token_endpoint);
    $params['oauth_verifier'] = $this->getUserVerifier();
    $access_token_req = $access_token_req->from_consumer_and_token($this->consumer,
            $auth_token, "GET", $this->access_token_endpoint, $params);

    $access_token_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,
            $auth_token);

    $after_access_request = $this->doHttpRequest($access_token_req->to_url());
    $access_tokens = array();
    parse_str($after_access_request,$access_tokens);

    # line 234 below
    $access_token = new OAuthConsumer($access_tokens['oauth_token'], $access_tokens['oauth_token_secret']);

    // prepare for get profile call
    $profile_req = $access_token_req->from_consumer_and_token($consumer,
            $access_token, "GET", $this->api_url.'/v1/people/~');

    $profile_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);

    $after_request = $this->doHttpRequest($profile_req->to_url());

    var_dump($after_request);
}

The function var_dumps a string, which is the basic synopsis of my profile:
string(402) " User Name etc. etc. http://www.linkedin.com/profile?viewProfile=&key=28141694&authToken=HWBC&authType=name&trk=api*a137731*s146100* "

That's good. However, the minute I refresh the page, the same function call fails with:
Undefined index: oauth_token, line number: 234

(this line marked with comment in above code block).
Then, of course, the var_dump reports this error from LinkedIn:
string(290) " 401 1310652477038 R8MHA2787T 0 [unauthorized]. The token used in the OAuth request is not valid. "

something to note:

*

*the user token, secret, and verifier are persisted during the initial authorization callback (right before this function is called). So, they are the same during the first call (when it works, right after coming back from linkedin) and during a page reload (when it fails on line 234).

Also, I must admit I'm not 100% sure I understand everything that's going on in this function. I actually took examples from this tutorial (about a different service, not linkedin) http://apiwiki.justin.tv/mediawiki/index.php/OAuth_PHP_Tutorial  and combined it with the information I gathered from the LinkedIn API documentation, spread throughout their developer site. Most notable was the addition of the 'verifier' which the tutorial did not use.
Any insight into this problem would be greatly appreciated. Thanks in advance.
-Nick
UPDATE
The only way I've been able to get this going is to do a new OAuth handshake every single time. Is this the way it's supposed to happen? I was under the impression that once I got my user token/secret and verifier, that I could then use these for continuous API calls until the token expired or was revoked.
As it is now, every time the page reloads I'm requesting a new user token, secret and verifier, then immediately calling to get the user profile (which succeeds). Next reload, I get a whole new key/secret and verifier. Seems like quite a lot of work for each call, and as I understood it, you should be able to perform offline operations with this method - and if I need new authorization each time, then I guess I can't do that?

A: Well. I've finally figured out what was going on so thought I'd post the answer here, just in case someone else runs into this.
The example that I was using as a guide was flawed. After the access token is retrieved, you should then create a new OAuthRequest object, instead of using the existing $access_token_req instance.
So this:
// prepare for get profile call
$profile_req = $access_token_req->from_consumer_and_token($consumer,
        $access_token, "GET", $this->api_url.'/v1/people/~');

$profile_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);

$after_request = $this->doHttpRequest($profile_req->to_url());

Should be changed to this:
$api_req = new OAuthRequest("GET", $this->api_url.$api_call);

// prepare for get profile call
$api_req = $api_req->from_consumer_and_token($consumer,
        $access_token, "GET", $this->api_url.'/v1/people/~');

$api_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);

$after_request = $this->doHttpRequest($api_req->to_url());


text:
Q: set css on ul li for hover this is my html:-

Activities

Physical1

Cricket

One Day

Test1

Test At Abc

Test2

Test At Xyz

this is my csss:-
ul > li > ul {
    display: none;

}

li:hover > ul {
    display: block;
    }

i want to hover on Activties then Display Physical1 and Test1 and Test2.
i am try to above css but not success with them.
thanks.

A: To do a nested list you should put a
 element inside a
 like that:

Blah blah

Nested blah blah

Then your CSS rule:
li:hover > ul {
  display: block;
}

will work.


text:
Q: Small, unequal, sample size significance using MANOVA I am testing the hypothesis, "there is no difference between 3 materials", with a small sample size. I have 3 materials and 2 DVs (test 1-2). They also have a different number of replications as seen below. Six material-1, two material-2, and two material-3. Unfortunately this is all of the data that I will get due to the difficulty of the tests.
Material    Test1    Test2
________    _____    _____

 'mat1'       5        3
 'mat1'       4        7
 'mat1'       8        7
 'mat1'       8        2
 'mat1'       2        2
 'mat1'       5        5
 'mat2'       5       10
 'mat2'       7        4
 'mat3'       8        6
 'mat3'       8        3

I am using Matlab to run a MANOVA analysis using the repeated measures function with 95% confidence. The output from the analysis is shown below;
Within       Between      Statistic     Value        F       RSquare    df1    df2    pValue
________    ___________    _________    _______    _______    _______    ___    ___    _______

Constant    (Intercept)    Pillai       0.11538    0.91304    0.11538     1      7     0.37113
Constant    (Intercept)    Wilks        0.88462    0.91304    0.11538     1      7     0.37113
Constant    (Intercept)    Hotelling    0.13043    0.91304    0.11538     1      7     0.37113
Constant    (Intercept)    Roy          0.13043    0.91304    0.11538     1      7     0.37113
Constant    Material       Pillai       0.20218    0.88696    0.20218     2      7     0.45359
Constant    Material       Wilks        0.79782    0.88696    0.20218     2      7     0.45359
Constant    Material       Hotelling    0.25342    0.88696    0.20218     2      7     0.45359
Constant    Material       Roy          0.25342    0.88696    0.20218     2      7     0.45359

It seems to clearly show that the null hypothesis holds true. I want to make sure that I went through the process correctly and I used the "best" method for the data I have. Should I do separate t-tests for the materials because of the small sample size? Is there some post-hoc analysis I should be doing? I am giving myself a crash course in statistics over the last few weeks, so any help is greatly appreciated.


text:
Q: Vertical Arrowed Process just with 'div' element and css? I have to do something similar to the capture (see below) in my website.
I use to do this with Photoshop. But this time I would like to know if this can be done with 3 'div' elements and css.
Update: this one is similar How to make this arrow in CSS only? but mine is vertical.
With this I get the FIRS arrow div:
.arrow_box {
    position: relative;
    background: #88b7d5;
    border: 4px solid #c2e1f5;
}
.arrow_box:after, .arrow_box:before {
    top: 100%;
    left: 50%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}

.arrow_box:after {
    border-color: rgba(136, 183, 213, 0);
    border-top-color: #88b7d5;
    border-width: 30px;
    margin-left: -30px;
}
.arrow_box:before {
    border-color: rgba(194, 225, 245, 0);
    border-top-color: #c2e1f5;
    border-width: 36px;
    margin-left: -36px;
}


text:
Q: WINAPI/DWMAPI Blur-behind window with irregular shape NB: THIS IS NOT A QUESTION ABOUT A BORDERLESS WINDOW.
So, I stumbled upon this program while I was exploring my Start menu the other day on Windows 7:

It's a native Windows program, called "Math Input Panel."  Now, I'm curious about the window shape.  I know that it's not completely drawn by DWM, because the borders and Close button look fishy and the window has no drop shadow (I have drop shadows enabled).  My first guess as to how this was made would be using DwmEnableBlurBehindWindow, but I can't imagine that works on irregular window shapes, does it?  (Or is there another way to do this, or is it just completely Microsoft sorcery?)

A: Here's a quickly hacked together WPF solution. It uses the hRgnBlur of the DWM_BLURBEHIND structure, and some interop.
This example will apply an ellipse-shaped background blur on the window.
You can easily convert this to an attached property or behavior for MVVM-friendliness. It's also a good idea to listen to the WM_DWMCOMPOSITIONCHANGED message and reapply the blur if needed.
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        WindowStyle = WindowStyle.None;
        AllowsTransparency = true;

        SourceInitialized += OnSourceInitialized;
    }

    private void OnSourceInitialized(object sender, EventArgs eventArgs)
    {
        if (!NativeMethods.DwmIsCompositionEnabled())
            return;

        var hwnd = new WindowInteropHelper(this).Handle;

        var hwndSource = HwndSource.FromHwnd(hwnd);
        var sizeFactor = hwndSource.CompositionTarget.TransformToDevice.Transform(new Vector(1.0, 1.0));

        Background = System.Windows.Media.Brushes.Transparent;
        hwndSource.CompositionTarget.BackgroundColor = Colors.Transparent;

        using (var path = new GraphicsPath())
        {
            path.AddEllipse(0, 0, (int)(ActualWidth * sizeFactor.X), (int)(ActualHeight * sizeFactor.Y));

            using (var region = new Region(path))
            using (var graphics = Graphics.FromHwnd(hwnd))
            {
                var hRgn = region.GetHrgn(graphics);

                var blur = new NativeMethods.DWM_BLURBEHIND
                {
                    dwFlags = NativeMethods.DWM_BB.DWM_BB_ENABLE | NativeMethods.DWM_BB.DWM_BB_BLURREGION | NativeMethods.DWM_BB.DWM_BB_TRANSITIONONMAXIMIZED,
                    fEnable = true,
                    hRgnBlur = hRgn,
                    fTransitionOnMaximized = true
                };

                NativeMethods.DwmEnableBlurBehindWindow(hwnd, ref blur);

                region.ReleaseHrgn(hRgn);
            }
        }
    }

    [SuppressUnmanagedCodeSecurity]
    private static class NativeMethods
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct DWM_BLURBEHIND
        {
            public DWM_BB dwFlags;
            public bool fEnable;
            public IntPtr hRgnBlur;
            public bool fTransitionOnMaximized;
        }

        [Flags]
        public enum DWM_BB
        {
            DWM_BB_ENABLE = 1,
            DWM_BB_BLURREGION = 2,
            DWM_BB_TRANSITIONONMAXIMIZED = 4
        }

        [DllImport("dwmapi.dll", PreserveSig = false)]
        public static extern bool DwmIsCompositionEnabled();

        [DllImport("dwmapi.dll", PreserveSig = false)]
        public static extern void DwmEnableBlurBehindWindow(IntPtr hwnd, ref DWM_BLURBEHIND blurBehind);
    }
}

Used with the following XAML:
<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="300" WindowStartupLocation="CenterScreen">

    <Border Background="#800000FF" Margin="30">
        <TextBlock Text="Hello, world!" VerticalAlignment="Center" HorizontalAlignment="Center" />
    </Border>
</Window>

The result is:

A: So, unbeknownst to me, hRgn can take an irregular shape (and DwmEnableBlurBehindWindow takes an hRgn, but I knew that).  So, here's my solution that's (more or less) compatible with WPF:

...and source code:
MainWindow.xaml:
<Window x:Class="IrregularGlassWindow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="500"
        Width="500"
        Background="#01FFFFFF"
        AllowsTransparency="True"
        WindowStyle="None"
        ResizeMode="NoResize">
  <Window.Clip>
    <PathGeometry>
      <PathFigure StartPoint="250,0">
        <ArcSegment Point="250,500"
                    RotationAngle="180"
                    Size="250,250"
                    SweepDirection="Clockwise" />
        <ArcSegment Point="250,0"
                    RotationAngle="180"
                    Size="250,250"
                    SweepDirection="Clockwise" />
      </PathFigure>
    </PathGeometry>
  </Window.Clip>
  <Grid>
    <Ellipse Margin="1"
             Width="498"
             Height="498"
             Stroke="#8FFF"
             StrokeThickness="1.25" />
    <Ellipse Width="500"
             Height="500"
             Stroke="#C000"
             StrokeThickness="1"/>
  </Grid>
</Window>

MainWindow.xaml.cs:
public partial class MainWindow : Window {
  public MainWindow() {
    InitializeComponent();

    this.SourceInitialized += MainWindow_SourceInitialized;
    this.KeyDown += MainWindow_KeyDown;
  }

  void MainWindow_KeyDown(object sender, KeyEventArgs e) {
    if (e.Key == Key.Escape) this.Close();
  }

  void MainWindow_SourceInitialized(object sender, EventArgs e) {
    var helper = new WindowInteropHelper(this);
    var hwnd = helper.Handle;
    var src = HwndSource.FromHwnd(hwnd);

    src.CompositionTarget.BackgroundColor = Colors.Transparent;

    WindowChrome.SetWindowChrome(this, new WindowChrome {
      CaptionHeight = 500,
      CornerRadius = new CornerRadius(0),
      GlassFrameThickness = new Thickness(0),
      NonClientFrameEdges = NonClientFrameEdges.None,
      ResizeBorderThickness = new Thickness(0),
      UseAeroCaptionButtons = false
    });

    GraphicsPath path = new GraphicsPath(FillMode.Alternate);
    path.StartFigure();
    path.AddArc(new RectangleF(0, 0, 500, 500), 0, 360);
    path.CloseFigure();

    var dbb = new DwmBlurBehind(true);
    dbb.SetRegion(Graphics.FromHwnd(hwnd), new Region(path));
    DwmApi.DwmEnableBlurBehindWindow(hwnd, ref dbb);
  }
}

I think somebody else beat me to it, but here's how my solution works:
When the window's SourceInitialized event is fired, that means that we have a handle for our window.  So in the handler of this function, I get the window handle.  Then I make a call to a function I imported from dwmapi.dll called DwmEnableBlurBehindWindow.  This basically turns transparent areas of the window into glass for a certain region.  The DwmBlurBehind struct I got from pinvoke.net, and it converts a GDI+ System.Drawing.Region into an hRgn.  The hRgn is passed to DwmEnableBlurBehindWindow, and it clips the transparent parts to the Region.  In this case, I used a circle.  Then the XAML is just the accent borders.  It's worth noting that, for some reason, setting Window.Background to Transparent doesn't enable hit-testing when AllowsTransparency is true here.  No idea why, but it probably has something to do with the code-behind.

A: This is simply two borderless windows attempting to emulate the DWM.  This is evidenced with the inconsistencies in the theme with shadows and the "fishy" close button and the break in the gradient of the right "subwindow." A simple query of the DWM would have given the proper hints to render the windows correctly.
There is no "sorcery involved," since both of the windows are perfectly square.
The main window has a shape associated with it, causing the insert button to appear while the rest of the bottom appears translucent.
The same effect could be achieved using either GDI+ or WPF.
I am purposing a clarification of how the original effect was created, and not a way to duplicate it. That has been successfully demonstrated by previous answers.


text:
Q: Unity tweak tool does no change on 14.04 I've done a clean installation of Ubuntu 14.04 and tried to install Unity Tweak Tool right after updating my packages. At the first run, I've managed to change my theme and my icons, but after rebooting my machine, all the configurations that I changed were ignored and the default theme and icons of Ubuntu were loaded. After that, I can only see my modified themes and icons if I run nautilus on super user mode or running the following commands:
dconf reset -f /org/compiz/
setsid unity

But as soon as I restart my machine, these settings are gone.
I tried to find a solution to this and found many topics related to configurations that could be done with the dconf editor, but none of them did me any good. I also tried purging Unity Tweak Tool, cleaning the cache and  reinstalling it from the software center, but at the end it didn't change a thing. The gnome tweak tool also cannot change my theme or icons.
Can someone give me a light on what is happening here ?

A: I've managed to find a workaround myself (It is not the way I wanted, but is the way it works).
I manually moved the default theme (Ambiance) folder from /usr/share/themes to another folder in order to have a backup, and made a copy of the folder of my desired theme (which is supposed to be in /usr/share/themes, as long as you installed it) with the same name of the default.
For example, assuming that my default theme right now is the Ambiance theme (Default ubuntu 14.04 theme) and I want to use the Ambiance-Flat-Blue-Pro theme, I execute the following commands:
cd /usr/share/themes
sudo mv Ambiance ~/Documents/
sudo cp -R Ambiance-Flat-Blue-Pro/ Ambiance
sudo reboot

The same works for icons, but instead of making modifications in the /usr/share/themes/, you just need to do it on the /usr/share/icons/ folder.


text:
Q: python file is incomplete, how to wait till it is complete before handling back to parent process I want to be able to set off a subprocess which writes a file to the server and then wait till it is completely finished before handling back to the parent process.
I recieve a image file from a post request. I parse it and I write it to the server with the following code... which is fine.
path="/var/bla/bla/bla/"
original_fname = file1['filename']
output_file = open(os.path.join(path,original_fname), 'w')
output_file.write(file1['body'])

The problem is I then have to access this file using imagemagick command line tool after it is created to get certain data. But with the above code it is too early and the process is not finished creating the file.
I want to do this after the above code...
subprocess.Popen(stdout=output_file)
Popen.communicate()

but  getting the following error....

'Popen' object has no attribute '_child_created'

How can I fix this?

A: You did not close the file after writing it. You can do it this way:
output_file = open(os.path.join(path,original_fname), 'w')
output_file.write(file1['body'])
output_file.close()

But I recommend using the with keyword, which takes care of closing the file descriptor even if an error happens in the block:
with open(os.path.join(path,original_fname), 'w') as output_file:
    output_file.write(file1['body'])


text:
Q: dynamically add variables to mysql:bind_param I wanna add dynamically variables to mysqli:bind_param ...
I saw a lot of tutorials and examples but the code I made isn't working for hours now.
$params = array('');
$params[0] = $variableType; //variableType contains e.g. sssi

foreach ( $data as $key => $value ) {
    array_push($params, $data[$key]); // I also tried $params[] = $value;
}

call_user_func_array(array($stmt, 'bind_param'), $this->refValues($params));

The refValues function looks like this ...
private function refValues(Array &$arr)
{
    $refs = array();
    foreach($arr as $key => $value)
        $refs[$key] = &$arr[$key];
    return $refs;
}

Error given every time I try it ...
Warning:  mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables in C:\Users...xxx.php on line 54

A: The problem here is that you are missing the first parameter to mysqli_stmt::bind_param, from: http://php.net/manual/en/mysqli-stmt.bind-param.php

bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

So you need to assemble the $types string and pass it as the first parameter.
EDIT
I suggest that instead of trying force mysqli to do something its not design for, you should use PDO which simply takes an array of parameters in the execute method: http://php.net/pdostatement-execute


text:
Q: selenium python can't scrape video url I am trying to scrape vidro url from this page. see the picture below

but the video element div are not showing on selenium chrome browser and I also tried Firefox.
here is my code:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.chrome.service import Service as ChromiumService
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.core.utils import ChromeType

from selenium_stealth import stealth
import requests, csv, time

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options,service=ChromiumService(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()))
url = "https://grabagun.com/firearms/handguns/semi-automatic-handguns/glock-19-gen-5-polished-nickel-9mm-4-02-inch-barrel-15-rounds-exclusive.html"
driver.get(url)

I also tried chrome default profile but didn't work.
options.add_argument("user-data-dir=C:\\Users\\JHONE\\AppData\\Local\\Google\\Chrome\\User Data")
driver = webdriver.Chrome(options=options,executable_path="C:\\Users\\chromedriver.exe")

why the product video section not showing ?what is prevention to show the video section when using selenium?


text:
Q: One Test-Class per method? since today I have used the pattern to create one test class per class.
For example the class "Foo" with the methods "DoSomething" and "DoNothing" had one test class called "FooTests".
Now I have heard about creating one test class for every method. For the previous example this would mean I create two new classes called "DoSomethingTests" and "DoNothingTests" instead of the class "FooTests".
Is this a commonly used pattern and should I switch to this one, or is this furthermore an anti pattern?
Thanks for you help.

A: My personal opinion is this: you'll create test classes in such a way that's logical and easy to maintain. Now if you have two methods very closely related I don't see why you'll create two classes. One more thing to consider how many test methods you have. You don't want to have a huge test class. Eventually you'll also have to maintain the test classes, so treat them like your regular code base.

A: The main advantage of creating one test class per production class is that it's simple and understandable.  If you have Foo, you know for certain that all the unit tests for Foo can always be found in FooTest (or whatever your naming convention calls it.  You are following a naming convention for the unit test class names, aren't you?)
For readability purposes, I recommend your team define a naming convention that helps identify the tests.  For example, I might name one of the tests FooTest::DoSomething_ensureNullPointerThrowsException().  That way the reader knows not only it's a test for Foo::DoSomething(), but they also know it's testing for a null pointer exception.
In general, if something seems "wrong" or "hard to do"; if you think it would be easier to do something differently because your project just doesn't seem to mesh with the way everyone else does it; it's often due to violations of one or more of the OO design principles.  Look deeply for the root cause: why am I struggling with issue X?  Why does someone want want one test class per production method?  Are there a hundred tests for each method and the developer thinks a change would keep them grouped together better?  The real cause is likely  that his methods have too much responsibility, or are overly complex.  If his methods were simpler, he may find he needs perhaps only five or ten tests for each method.

A: I can not see the reason of introducing test classes for each and every methods. Honestly, I've never seen this kind of test strategy.
Of course, you can break apart your test classes if you have reason for it. You can extract common parts of your tests in separated helper classes. In some cases inheritance between test classes is also reasonable.
There is no difference between the test code and production code. Your test code should be clear, readable and maintainable. I think the "One Test-Class per method" ideology can ruin it.

A: I think it is all about when to apply such a thing. I'd say that in general you should not be creating a test class per test method. I would recommend grouping methods with the same functionality (e.g. the methods in a single class) in a single test class. However, an exception might be an extremely complex method that requires dozens of tests to verify its behavior. In such a case a single test class might be useful. You have to be careful creating exceptions though, as this makes the way the code is structured less obvious.


text:
Q: How can I check if a word is present or not in an array in php? I am using curl for web page scraping and I can display a result of interest.
Normally the script below outputs me the WEB SCRAPER TESTING GROUND text which is scraped and regex'ed by "title" id from the page.
Now I would like to check if the word "TESTING" is present in the $list array. If yes - just echo "present", if not - echo "not present". What is the best way to do this?
I know how to search a web page and extract text parts from it.
 $curl = curl_init('http://testing-ground.scraping.pro/textlist'); // cURL
 setup

curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); //  return the transfer
page as a string
curl_setopt($curl, CURLOPT_HEADER, TRUE);

$page = curl_exec($curl); // executing the request

if(curl_errno($curl)) // check for execution errors
{
    echo 'Scraper error: ' . curl_error($curl);
    exit;
}

curl_close($curl); // closing the connection

$regex = '/<div id="title">(.*?)<\/div>/s'; // extracting the needed part

if ( preg_match($regex, $page, $list) ) // search matches of $page with
$regex
    echo $list[0];
else
    print "Not found";

A:
I know how to search a web page and extract text parts from it.

actually, you're doing it very wrong.
    the code should actually look something like
$list[]=(@DOMDocument::loadHTML($page))->getElementById("title")->textContent;

if you want to learn how to properly parse HTML in PHP, read the thread > How do you parse and process HTML/XML in PHP?

Now I would like to check if the word "TESTING" is present in the $list array. If yes - just echo "present", if not - echo "not present". What is the best way to do this?

make a bool found, iterate it with foreach, check each entry in the list with strpos(), make sure to break of the loop out early if you find it (because continuing the loop would be a waste of cpu and time after a match is found), and finally print the result, eg
$found=false;
foreach($list as $foo){
    if(false!==strpos("TESTING",$foo)){
        $found=true;
        break;
    }
}
if($found){
    echo "present";
}else{
    echo "not present";
}


text:
Q: instrument dalvik in android occur register limitation within v0~v15 recently ,i am try to profiling android application path, and while i using path profiling algorithm i need to instrument the dalvik instruction for satisfying more scalable application analysis .
but now i am encounter an  inevitable problem in register limitation.
during my instrumentation work , i need at least 8 register addition, but in a method ,there is typically limit the number of register within v0~v15, and i will trigger recompilation error if I direct modify the '.locals x'block.
typically like this.
.method public static mixCir(I)Ljava/lang/String;
.locals 10
.parameter "max"

and if we just modify 10 --> 18 , the apktool compilation will trigger error:
Exception in thread "main" java.lang.NullPointerException
    at org.jf.util.PathUtil.getRelativeFile(PathUtil.java:44)
    at org.jf.smali.smaliFlexLexer.getSourceName(smaliFlexLexer.java:292
    at org.antlr.runtime.CommonTokenStream.getSourceName(CommonTokenStre
ava:345)
    at org.antlr.runtime.Parser.getSourceName(Parser.java:88)
    at org.jf.smali.smaliParser.getErrorHeader(smaliParser.java:358)
    at org.antlr.runtime.BaseRecognizer.displayRecognitionError(BaseReco
er.java:192)
    at org.antlr.runtime.BaseRecognizer.reportError(BaseRecognizer.java:

    at org.jf.smali.smaliParser.smali_file(smaliParser.java:736)
    at brut.androlib.mod.SmaliMod.assembleSmaliFile(SmaliMod.java:71)
    at brut.androlib.src.DexFileBuilder.addSmaliFile(DexFileBuilder.java

    at brut.androlib.src.DexFileBuilder.addSmaliFile(DexFileBuilder.java

    at brut.androlib.src.SmaliBuilder.buildFile(SmaliBuilder.java:64)
    at brut.androlib.src.SmaliBuilder.build(SmaliBuilder.java:48)
    at brut.androlib.src.SmaliBuilder.build(SmaliBuilder.java:35)
    at brut.androlib.Androlib.buildSourcesSmali(Androlib.java:222)
    at brut.androlib.Androlib.buildSources(Androlib.java:179)
    at brut.androlib.Androlib.build(Androlib.java:170)
    at brut.androlib.Androlib.build(Androlib.java:154)
    at brut.apktool.Main.cmdBuild(Main.java:182)
    at brut.apktool.Main.main(Main.java:67)

so, is there any approach to satisfy my requirement ?
thanks a lot!


text:
Q: VBA vlookup code in different sheet I am new to VBA.
I have 2 sheets under my excel: "Data", "Sheet1".Data sheet is amended every day.
I would like to use vlookup VBA macro to rows added to column A in Sheet1. However my code doesn't give me any results (it works if I run macro under same sheet where data are). Thank you
Private Sub CommandButton21_Click()
On Error Resume Next
Sheet1.Range("B3:D500").Clear
Dim Dept_Row As Long
Dim Dept_Clm As Long
Table1 = Sheet1.Range("A3:A50")
Table2 = Data.Range("A3:H24")
Dept_Row = Sheet1.Range("B3").Row
Dept_Clm1 = Sheet1.Range("B3").Column
Dept_Clm2 = Sheet1.Range("C3").Column
Dept_Clm3 = Sheet1.Range("D3").Column
For Each cl In Table1
  Sheet1.Cells(Dept_Row, Dept_Clm1) = Application.WorksheetFunction.VLookup(cl, Table2, 6, False)
  Sheet1.Cells(Dept_Row, Dept_Clm2) = Application.WorksheetFunction.VLookup(cl, Table2, 7, False)
  Sheet1.Cells(Dept_Row, Dept_Clm3) = Application.WorksheetFunction.VLookup(cl, Table2, 8, False)
  Dept_Row = Dept_Row + 1
Next cl
MsgBox "Done"
End Sub

A: If you are going to code the solution it would be better if you dimension the worksheets as such:
Dim sWS as worksheet   'Source worksheet
dim tWS as worksheet   'Target worksheet
dim aCell as range

with thisworkbook
  set sws = .sheets("Data")
  set tws = .sheets("Sheet1")
end with

for each acell in sws.range("A3:A50")
  with tws
     .cells(Dept_Row, Dept_Clm1).value = application....
     'also check out the offset function for fetching values in cells to the left or right of the cell you are looping down through.
  end with
next acell

Alternatively, check out the Match, Index and Indirect formulas on how to transfer data from one worksheet to another. The three functions are more efficient and accurate than vLookup, especially if you are transferring three cells from one worksheet to another.


text:
Q: Not understanding Ocaml type signatures I have been working on trying to understand this, and working any harder on it is going to hurt my relationship with OCaml, so I figured I would ask for help.
I have a simple function from this site
let line_stream_of_channel channel =
Stream.from
  (fun _ ->
     try Some (input_line channel) with End_of_file -> None);;

Okay cool, clearly from the signature below it:
val line_stream_of_channel : in_channel -> string Stream.t = <fun>

in_channel is the argument and Stream.t is the return value.
Now why is it in OCaml that I can't do:
Stream string

and instead I have to do
string Stream.t

Looking at the type signature of Stream didn't really get me anywhere either. I've noticed this same syntax weirdness with stuff like lists where you have to do the unnatural
string list

rather than the natural
list string

But what is especially weird is the ".t" portion of the Stream type above.
Can anyone kinda explain what is going on here and why things are done this way? I've googled tutorials on explicit type signatures, types, etc in OCaml and in general they lead back here to very specific questions that don't really help me.
Thank you!

A: In OCaml's parameterized types, the type constructor name comes after the parameter name(s). That's just the way it works. There are languages (such as Haskell) that use the other order.
I like the OCaml order, I have no problem with it. I also have no problem with the other order.
The name t is defined as a parameterized type in the Stream module. There's nothing trickier than this going on.
However, note that the return type of line_stream_of_channel is string Stream.t, not just Stream.t. Stream.t by itself isn't a type. (It's a function at the type level, or a type constructor.)
$ ocaml
        OCaml version 4.01.0

# Some 3;;
- : int option = Some 3
# ^D

$ ghci
GHCi, version 7.4.2: http://www.haskell.org/ghc/  :? for help
Prelude> :t Just (3 :: Integer)
Just (3 :: Integer) :: Maybe Integer

A: Types can be parametric in OCaml. For example, int list is a list parametrized with type int, and basically corresponds to list<int> in some other languages. Is it weird? It depends on your background. I personally, find string list more natural, then list string
The syntax for parametrized type is <parameter-type> <parametrized-type>. So both components should be types. Stream is not a type, it is a module name. The notation <module-name> . <name> allows you to address definitions defined in module. For example, you may define a type alias:
 type 'a stream = 'a Stream.t

and then use it
 type string_stream = string stream

Note, stream_string sounds weird, isn't it?


text:
Q: Can't ssh or console to the guest using ubuntu-vm-builder I'm running Oneric as the host, would like to create several virtual machines. Both the host and the guests will be headless - there is no display connected, and I'd like to connect to them via ssh.
Looks like kvm is the official ubuntu recommended way, so I'm following the documentation: http://help.ubuntu.com/community/KVM/CreateGuests
Here's my ubuntu-vm-builder command:
sudo ubuntu-vm-builder kvm oneiric \
              --domain xpstage --dest xpstage --hostname xpstage \
              --arch i386 --mem 1024 \
              --user myusername --pass mypassword \
              --bridge virbr0 --ip 192.168.122.2 --dns 8.8.8.8 \
              --components main,universe,restricted \
              --addpkg acpid --addpkg vim --addpkg openssh-server --addpkg avahi-daemon \
              --libvirt qemu:///system ;

The guest appears to build just fine, but I can't reach it.
ssh myusername@192.168.122.2

times out. My bridge network is setup:
virbr0    Link encap:Ethernet  HWaddr 00:00:00:00:00:00
      inet addr:192.168.122.1  Bcast:192.168.122.255  Mask:255.255.255.0
      UP BROADCAST MULTICAST  MTU:1500  Metric:1
      RX packets:673 errors:0 dropped:0 overruns:0 frame:0
      TX packets:21 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:0
      RX bytes:60839 (60.8 KB)  TX bytes:882 (882.0 B)

So I'm not sure what I'm doing wrong there.
Having failed with ssh I tried to console into it, but
virsh console xpstage

returns immediately, so I added a pty section to the configuration:
virsh edit xpstage

After adding the pty virsh console xpstage connects, but doesn't display anything and key presses don't do anything.
I then tried setting up a Serial Console, but upstart doesn't like that: start: Unknown job: ttyS0 .
Can some kind soul please guide me to how to setup a headless KVM guest on Oneric that I can connect to?

A: Though I still need to learn to do it via console, If you have a Workstation I would suggest installing virt-manager and connecting it to you KVM server and installing your guest through it, This is what i did and it was near painless, you will need the ISO of whichever your trying to install on the Server.
I did this on a Intel Dual core 2.0ghz with 4gb ram
To this day that VM is running my Website