text:
Q: Ambiguous connotation of "just" - How do natives interpret these? First of all, these questions are a bit related but not what I'm actually asking about:

*

*Is "I just spent all my money" grammatically incorrect?

*"I just ate them" and "I've just eaten them" - What's the difference in American and in British?

*When is the present perfect tense used instead of the past tense?
And this answer to the second question as well as its comment does indicate the problem I'm continually encountering.
I tend to overuse the word just. Sometimes I don't even recognize it but if I carefully re-read my English I often find sentences like:

*

*I've just implemented the method.

*I've just eaten an apple.

*I've just closed my eyes for a few seconds.

The problem is, that in all these sentences I don't want to emphasize that I did that recently, just a couple of seconds/minutes ago, or that it might have any connection to the present, i.e. my present actions, although the action indeed just happened of late (and that's why I use the perfect).
In these cases just is meant to be simply or only:

A: Are you gonna eat with us to lunch now?
B: Sure, I only ate an apple and now I'm really hungry.

A: Are you tired?
B: No, I simply closed my eyes for a few seconds trying to focusing on the issues.

While these two sentences are just examples I invented for this question, the first sentence I introduced above is one of those I actually wrote. Regarding this first example, I consulted an American colleague and asked him how would he interpret the sentence

*

*I just implemented the method.

and he answered:

When a native English speaker reads that, they do not understand the 'just' to mean that you recently performed the action - they understand it to me that you 'simply' performed the action.  It gives the connotation that you could have done more if you had spent more time on it, but getting it done quickly and easily was more important to you.

So far I'm happy with this answer, but I still have some further questions:

*

*How do British natives interpret that, especially when using the perfect?

*How do you (Briton or American) emphasize the other meaning, i.e.

*

*if you understand just as recently do you use only (which sounds somehow awkward to me in sentences in perfect tense) or do you rephrase the sentence as I did with the invented examples, or

*if you understand just as only how do you then emphasize recently?

The main purpose of this question is to find out if I should put more focus on phrasing these kind of sentences, i.e. using simple past even for an action happened just now when I want to emphasize only, or if I can go ahead using this sentence structure.

A: Context is very important, as are placement and stress. I am a native Canadian-English speaker, so I don't really know whether there is more of an American or British influence in this case.
Your first three examples, out of context, are ambiguous, but context can be used to suggest a meaning to the reader.
More effective, perhaps, would be to adjust your placement of the word just, as its ambiguity is usually caused by the relationship to the verb or noun of the phrase. This is not specific to the word just, but also occurs in one of your examples using only.

*

*I've just eaten an apple.

The intended meaning, I presume, was that you've eaten an apple, and have not eaten anything else. Aside from the 'recently' connotation, this could also mean that the only thing that you have done is to eat an apple, and you have not, for example, gone fishing. An alternative wording could be,

*

*I've eaten just an apple.

When a noun follows just (not a verb), it cannot be used to mean recently.
In your example,

B: Sure, I only ate an apple and now I'm really hungry.

the word only is referring to ate an apple but (out of context) could be construed as referring to ate, as in,

I only ate an apple, and did nothing else with it.

The placement could be rearranged to,

I ate only an apple.

Which is still clear out of context.
In another part of your question, you said,

While these two sentences are just examples I invented for this question [...]

The intended meaning was only or simply, but upon first reading it, I thought that the implication was fairness or justice. This is another unintended ambiguity which is solved by context, but brings up stress.
It was the italics that put the stress on just into my head, effectively changing the way that I interpreted the written intonation of the sentence. When speaking aloud, it is easy to emphasize examples or an apple and often this is enough for the listener to understand since the alternative meanings would stress just. In casual or creative writing, italics can be used to create this effect, but for formal use, another method of disambiguation would have to be used.

A: I disagree with your colleague, I interpreted all three of your example sentences as meaning "just now" when I first read them. I think all three should be replaced with the word "only" to remove ambiguity. Of course, as Rachel says, often context will remove the ambiguity.

A: I use just very often in speech and casual writing. I tend to edit it out of more formal writing. I am a native American English speaker from Tampa and Boston.
To me, it can have both meanings, and I don't think that I have a preference. Your examples are all ambiguous to me. I think that the meaning is often clear from context (don't underestimate the power of context!), as in:

1) I'll be there soon. I just woke up. (recently)
2) I didn't call her. I just sent her an email. (merely)
3) I tried, but I just don't understand. (simply)

I don't see how changing tenses or aspects can help you, except that the future and simple present (always?) rule out the recently interpretation. But all of the following are equally ambiguous to me (sans disambiguating context).

4) I [just ate/am just eating/was just eating/have just eaten/etc.] an apple.

When I want to be crystal clear, I just replace just with merely, only, simply, or suchlike. I think that I less often change just to recently. I think I more often say just now to indicate that I mean recently.

A: I've studied the various senses of these tricky modifiers like only, just, merely, nearly, and even. They can appear before noun groups, quantifiers, prepositional phrases and adjectives, when I hate their classification as 'adverbs'. For the non-adjectival senses in which just is used:
just
3.adv.

*

*Precisely; exactly: just enough salt; that's just what I was about to say.

*Only a moment ago: He(/s) just arrived.

*By a narrow margin; barely: just missed being hit; just caught the bus before it pulled away.

*At a little distance: just down the road.

*Merely; only: just a scratch.

*Simply; certainly: It's just beautiful!

*Perhaps; possibly (connotes wryly and with deliberation coming to a decision): I just may go.
The American Heritage® Dictionary of the English Language, Fourth Edition [augmented]
just
adv

*

*used with forms of have to indicate an action performed in the very recent past: I have just closed the door

*at this very instant: he's just coming in to land

*no more than; merely; only: just an ordinary car

*exactly; precisely: that's just what I mean

*by a small margin; barely: he just got there in time
6a. (discourse marker - intensifier) simply; really: it's just wonderful to see you
6b. (discourse marker – intensifier and conveyor of surprise, shock) believe it or not: she just upped (sticks) and left/walked out; he just upped and died  (cf he's only gone and dropped dead!)
(7.) (Informal) indeed; with a vengeance: isn't it just
(Collins English Dictionary) [augmented]
As Rachel says, context is very important in deciding which sense is intended. Intonation with spoken occurrences can help. Positioning within the sentence is critical - the 'misplaced modifier' is infamous. And if none of these removes the ambiguity, a rephrasing is necessary. Of course, ambiguity is sometimes in the ear of the listener.


text:
Q: KWallet Error when attempting to decrypt the wallet ... Inappropriate ioctl for device Whenever I try to open something that needs access to KWallet (e.g. Browser), this dialog box pops up:

I've read elsewhere that to fix this you need to set the GPG_TTY environment variable to $(tty), and I've tried to put it in my ~/.profile, but it still doesn't work. Any ideas as to how I can fix this?
Edit: Also, I'm running Manjaro 22.0, if that helps.

A: Disabling KWallet entirely in the settings fixed the problem entirely, and all the programs that previously required KWallet still work fine...? I guess I'll take it lol
Edit: I ended up just using gnome-keyring.

redpajama_set_name: RedPajamaStackExchange


text:
Q: android: ScrollView in 1.5 doesn't work My one layout works perfect on 1.6+ but throws error on 1.5 and results in shutting down the app with "Force Close". The layout contains RelativeLayout as parent, ScrollView which contains RelativeLayout as child and imagevite, textview, edittext, buttons in child relativeLayout. Here's the xml file :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"  android:layout_height="fill_parent"
  android:id="@+id/user_pswd_new_root" android:scrollbars="vertical" android:soundEffectsEnabled="true">

 <ScrollView android:id="@+id/ScrollViewLogin" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scrollbarStyle="outsideInset" android:scrollbars="vertical" android:visibility="visible">
   <RelativeLayout android:layout_width="fill_parent" android:id="@+id/relativeLayout1" android:layout_height="fill_parent">

    <ImageView android:background="@drawable/logo_login_new" android:layout_height="wrap_content" android:id="@+id/imageView1"
    android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="40dp"></ImageView>
    <TextView android:layout_height="wrap_content" android:textStyle="bold"
    android:layout_width="wrap_content" android:text="@string/login_text" android:layout_marginRight="40dp"
    android:textSize="25dp" android:id="@+id/textView1" android:layout_alignParentRight="true" android:layout_marginTop="20dp"></TextView>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/imageView1" android:layout_margin="10dp" android:text="@string/username" android:id="@+id/textView2_usr" android:layout_marginTop="10dp"></TextView>
    <EditText android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:text="" android:layout_toRightOf="@+id/textView2_usr" android:layout_alignTop="@+id/textView2_usr" android:layout_marginRight="10dp" android:id="@+id/user_pwd_username"></EditText>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="10dp" android:layout_below="@+id/user_pwd_username" android:id="@+id/textView3_usr" android:text="@string/password"></TextView>
    <EditText android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:text="" android:layout_toRightOf="@+id/textView3_usr" android:layout_below="@+id/user_pwd_username" android:layout_marginRight="10dp" android:layout_alignLeft="@+id/user_pwd_username" android:id="@+id/user_pwd_password" android:password="true"></EditText>
    <CheckBox android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/user_pwd_password" android:text="@string/remMe" android:layout_marginLeft="10dp" android:id="@+id/user_pwd_remMeChk"></CheckBox>
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/user_pwd_remMeChk" android:text="@string/loginBtn" android:id="@+id/user_pwd_btn_ok" android:layout_marginLeft="40dp" android:width="100dp"></Button>
    <Button android:layout_height="wrap_content" android:id="@+id/user_pwd_btn_cancel" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_marginRight="40dp" android:layout_alignTop="@+id/user_pwd_btn_ok" android:text="@string/cancelBtn" android:width="100dp"></Button>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Version" android:layout_alignParentRight="true" android:layout_below="@+id/user_pwd_btn_cancel" android:layout_marginRight="10dp" android:id="@+id/versionText" android:textSize="6dp"></TextView>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="" android:layout_alignParentLeft="true" android:layout_below="@+id/versionText" android:layout_marginLeft="10dp" android:id="@+id/messageText" android:scrollbars="vertical"></TextView>

    </RelativeLayout>
 </ScrollView>

</RelativeLayout>

The errors I get in LogCat is :
05-17 17:07:02.110: ERROR/AndroidRuntime(1215): Uncaught handler: thread main exiting due to uncaught exception
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): java.lang.RuntimeException: Unable to start activity ComponentInfo{orange.android.vpn/orange.android.vpn.StartUltimate}: android.view.InflateException: Binary XML file line #11: Error inflating class java.lang.reflect.Constructor
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2268)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2284)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.access$1800(ActivityThread.java:112)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.os.Looper.loop(Looper.java:123)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.main(ActivityThread.java:3948)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at dalvik.system.NativeStart.main(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class java.lang.reflect.Constructor
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.createView(LayoutInflater.java:512)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:562)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:617)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:620)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:309)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.Dialog.setContentView(Dialog.java:400)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at orange.android.myw.LoginDialog.init(LoginDialog.java:78)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at orange.android.myw.LoginDialog.<init>(LoginDialog.java:72)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at orange.android.vpn.StartUltimate.onCreate(StartUltimate.java:129)
 05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
 05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 11 more
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: java.lang.reflect.InvocationTargetException
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.widget.ImageView.<init>(ImageView.java:103)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Constructor.constructNative(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.createView(LayoutInflater.java:499)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 25 more
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: android.content.res.Resources$NotFoundException: File res/drawable/scrollbar_handle_vertical.9.png from drawable resource ID #0x7f020005
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.Resources.loadDrawable(Resources.java:1641)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.TypedArray.getDrawable(TypedArray.java:548)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.View.<init>(View.java:1725)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.widget.ImageView.<init>(ImageView.java:107)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 29 more
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: java.io.FileNotFoundException: res/drawable/scrollbar_handle_vertical.9.png
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.AssetManager.openNonAssetNative(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.AssetManager.openNonAsset(AssetManager.java:392)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.Resources.loadDrawable(Resources.java:1634)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 32 more

Error points to setContentView() line in the LoginDialog class.
Can anyone tell what is stopping it to show up in 1.5.
Thanks

A: The very first exception is a FileNotFoundException. Check if the file res/drawable/scrollbar_handle_vertical.9.png does exist.

A: SOLution :
The image on which the error is locating i.e. "0x7f020005" which is a .png image. 1.5 doesn't recognize png images in drawable-hdpi or any, it looks in /drawable folder. I created a drawable folder in /res and copied the png image to it and the screen showed up. But due to small screen size, everything is one upon other. I tried with android:scrollbars="vertical|horizontal" attribute in ScrollView, but it only works vertical scrolling, horizontal scrolling doesn't work. What to do with this problem (Scroll Horizontal) now ?


text:
Q: How do I join this sql query to another table? I have the following SQL query and so far it works the way it should and gets the top 40 tag ids that I have stored in the tagmap table.
SELECT TOP 40
tbrm_TagMap.TagID,
Count(*)
FROM tbrm_TagMap
GROUP BY tbrm_TagMap.TagID
ORDER BY COUNT(tbrm_TagMap.TagID) DESC

I also want to join to the Tags table which contains the actual name of each TagID. Each attempt I make comes back with an error. How can I achieve this? I am using SQL 2008.

A: SELECT  *
FROM    (
        SELECT  TOP 40
                tbrm_TagMap.TagID, COUNT(*) AS cnt
        FROM    tbrm_TagMap
        GROUP BY
                tbrm_TagMap.TagID
        ORDER BY
                COUNT(*) DESC
        ) q
JOIN    Tags
ON      Tags.id = q.TagID
ORDER BY
        cnt DESC

A: My guess is that when you were joining tags, you weren't including it in the group by clause, which will always through an error in SQL Server. Every column not aggregated but returned needs to be in the group by.
Try something like this:
SELECT TOP 40
    tbrm_TagMap.TagID,
    t.Tag,
    Count(*)
FROM
    tbrm_TagMap
    INNER JOIN tags t ON
        tbrm_TagMap.TagID = t.TagID
GROUP BY
    tbrm_TagMap.TagID,
    t.Tag
ORDER BY 3 DESC

A: SELECT TOP 40
tbrm_TagMap.TagID, Tags.TagName Count(*)
FROM tbrm_TagMap INNER JOIN Tags ON tbrm_TagMap.TagID = Tags.TagID
GROUP BY tbrm_TagMap.TagID, Tags.TagName
ORDER BY COUNT(tbrm_TagMap.TagID) DESC

A: Try this..
SELECT top 40 tags.TagDescription, tbrm_TagMap.TagID, Count(*)
FROM tbrm_TagMap
    INNER JOIN Tags
       ON TagMap.TagID = Tags.TagId
GROUP BY tags.TagDescription, tbrm_TagMap.TagID
ORDER BY COUNT(tbrm_TagMap.TagID) DESC


text:
Q: Не работает ssh подключение Использую 2 машины, первая win вторая ubuntu server. Настроил подключение по ssh через Putty, подключение работало, проверял пару раз, но после перезагрузки win машины на которой стоит Putty он перестал подключатся по ssh, ошибка: таймаут. Сервер не трогал. Мои предположения: Может быть дело в адресах ведь ip я получаю по dhcp но в роутере порт проброшен и мак привязан к ip сервера. ifconfig постоянно проверяю на сервере ip не меняется значит с ip вроде все нормально. Фаервол выключен, iptables правило добавлено. У кого какие предположения?

A: 1) проверь через телнет доступность порта. например telnet    someipaddress 22. если есть возможность с разных машин (можно и с    телефона)
2) отключить антивирусные продукты временно (редко но    бывает симантек и другие порождают фантомные проблемы)
3) если есть  возможность покажи iptables -L


text:
Q: Synchronized Android surface view I am kind of new to java and android.
Now I am using the canvas to draw on the surface view because the faster speed than customer view.
But when it comes to synchronized the surface view in android I am getting kind of confuse
I take this link as the reference
http://android-er.blogspot.com/2010/05/android-surfaceview.html
also the android lunar lander
I have  two  version that slightly modified form example when I write the surfaceview rendering thread run method part, but I am not sure which one is more correct in concept. They both works,
But I just want to clear my concepts.
Thank for any help and suggestions in advanced and if i have ask question in wrong way please also corrected me   :)
version1 :
protected void run()
{
  while (isRunning)
 {
          if(RenderThreadSurfaceHolder.getSurface().isValid())
          {
            Canvas Draw = null;
            try
            {
              Draw =RenderThreadSurfaceHolder.lockCanvas(null);
              synchronized (RenderThreadSurfaceHolder){
                  if(Draw!=null)
                  {
                       RenderThreadSurfaceView.onDraw(Draw);
                  }
              }
            }
            finally{
              if(Draw!=null)
              {
                      RenderThreadSurfaceHolder.unlockCanvasAndPost(Draw);
              }
            }
        }
    }
}

version 2 :
protected void run()
{
  while (isRunning)
 {
          Canvas Draw = null;
                try
                {

                     synchronized (RenderThreadSurfaceHolder)
                     {
                             if(RenderThreadSurfaceHolder.getSurface().isValid())
                             {

                                   Draw=RenderThreadSurfaceHolder.lockCanvas(null);
                                   if(Draw!=null)
                                   {
                                      RenderThreadSurfaceView.onDraw(Draw);
                                   }

                             }
                     }
                 }
                 finally
                 {

                             if (Draw != null)
                             {
                                 RenderThreadSurfaceHolder.unlockCanvasAndPost(Draw);
                             }
                 }
    }
}

Edit
In additional synchronized the surface view I also want to add on a lock to control the data that share data between Activity and OnDraw method
Because I Think synchronized lots of data and lots process function is too much overhead
So I want to just synchronized a boolean , But What I do research on the Internet say that
Synchronized boolean is really not a good idea //still confusion me a lot
such as
synchronized (Check)
{
   Check=true;
}

But if I do something like below
private static lock Lock; //declare in the Activity

public synchronized void setlock(boolean newlock)
{
  if (newlock!=lock){
    lock = newlock;
  }
}

public synchronized boolean isTrue() {
    return lock;
}

Is that still not a good idea?
My concept is want to add the lock between the process function and OnDraw method :

A: This is a very subjective question, but I would go with 1.
The first approach has a tighter synchronized(RenderThreadSurfaceHolder); less code requires synchronization and this can help avoid blocking issues.
Besides that, it seems to be mostly ordering.  In solution 1 it also makes sense to call           if(RenderThreadSurfaceHolder.getSurface().isValid()) as soon as possible, because if the surface is invalid then nothing can happen anyways.  This avoids unnecessary if/else checks.
yeah, synchronization doesn't work on a boolean.  The reason is that BOOLEAN.TRUE and BOOLEAN.FALSE are static constants.
The idea is that when you synchronize a reference variable, any other threads that try to use that must wait until the currently running synchronized block ends.  As your boolean references either BOOLEAN.TRUE or BOOLEAN.FALSE, as soon as you synchronize on a second boolean you will start to see issues.
continue to synchronize on the RenderThreadSurfaceHolder, that is how I do it and how I have seen it done.
Why would you want to add a lock between drawing and updating?  Maybe if I knew the reason, I could help ya out with another approach.  Also, That will just add overhead, remember you want to keep your game loop as tight as possible.


text:
Q: How can I check if a modal view is currently over my self.window.rootViewController? I need to check if there is still a modal view over the root view controller.
The problem I am facing is that I have a second modal view coming from some thread that needs to be displayed. I want to delay the second modal view until the first one is gone.
I cannot just launch it after the first is dismissed because the second modal view is conditional.
[self.window.rootViewController presentModalViewController:vc animated:YES];

What I want to do (feel free to suggest a better alternative way):

*

*Check if self.window.rootViewController currently has a modal view displayed on top (or is still animating modal view).

*use performSelector:afterDelay:0.1

*Check again, and if needed, delay again

A: Get rootViewController.presentedViewController (available in iOS 5.0+) or rootViewController.modalViewController (available in iOS 2.0+) and see if it's nil.
Also, you don't want to present the second view controller from the secondary thread, all UI stuff has to be done on the main thread.

A: I also faced this kind of problem. I wanted to pop up a modal from push and before I do that I wanted to check if some screen is already presented and if yes dismiss those and pop my screen below is the code.
    // Dismiss all the modals which are currently shown.
    - (void) dismissAllModalsIfAnyWithCompletion:(void(^)(BOOL success)) completion{

            BOOL hiddenByModal = nil != [[UIApplication sharedApplication].keyWindow.rootViewController presentedViewController];
        if (hiddenByModal) {
//We need to dismiss the existing modal and after completion pop up the new modal.
            [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:NO completion:^{
                // After dismissing let the handler know.
                completion(YES);
            }];
        }
        else{
// If there is no modal, then simply let the handler know to pop the new modal.
            completion(YES);
        }
    }

A: I'd be tempted to do something a bit more deterministic.  Have one piece of code responsible for doing both modal displays and let it keep track of when the first modal appears and disappears so that, if it receives a message to display the second one, it knows whether to do it or just set a "pending" flag.  When it is told that the first one has been dismissed, it can check whether a second is pending.


text:
Q: Why is "fulfil" spelt as "fulfill" in American English? In this answer, simplification is stated as one reason for spelling variations in American English. But unlike in color and favorite, the number of letters to spell the word in fulfil increases in American English.
Other than for "creating a distinct" variant, is there any reason for the change? Going by the etymology the ideal spelling should be fullfill, so even that may be not a motivation.

A: Interesting question :) Reading up on this has been a pretty crazy experience. My conclusions are the following:

*

*The reason for the change from fulfil to fulfill is attributed to inflection, with the spelling modified to suit the function of the word.

*The reason why it isn't spelt fullfill is similar to why parallel only retains the single 'l' at the end—to curb the apparent fugliness of an '-llell' cluster in words such as unparalleled etc.

*There is also a question of consistency involved.

But, unfortunately, another rule in the AE transition was to preserve the "base" word as much as possible, which is why skill/_skilful in BE became skill/skillful in AE. However, this introduced a cluster of letters in words such as skillfully. To put it mildly, the result of exercise was and remains consistently inconsistent.
A related question on the difference in the AE/BE spellings of propelling covers similar territory. It also points to a WP page detailing the differences between American and British spelling which includes the following section on the madness of doubled consonants:

*

*The word parallel keeps a single -l- in British English, as in American English (paralleling, unparalleled), to avoid the unappealing
  cluster -llell-.

*Words with two vowels before a final l are also spelled with -ll- in British English before a suffix when the first vowel either acts as
  a consonant (equalling and initialled; in the United States, equaling
  or initialed), or belongs to a separate syllable (British fu•el•ling
  and di•alled; American fu•el•ing and di•aled).

*

*British woollen is a further exception due to the double vowel (American: woolen). Also, wooly is accepted in American English,
  though woolly prevails in both systems.

There's also a note on -ful and -fil:

In both American and British usages, words normally spelled -ll
  usually drop the second l when used as prefixes or suffixes, for
  example full→useful, handful; all→almighty, altogether; well→welfare,
  welcome; chill→chilblain. The British fulfil and American fulfill are
  never fullfill or fullfil. Johnson wavered on this issue. His
  dictionary of 1755 lemmatises distil and instill, downhil and uphill.

A: Not so much an answer, but I was brought up to consider that a second vowel (particularly an "e") after a vowel-consonant combination changes the pronunciation of the first vowel, thus
initial -> initialled ok
initial -> initialed not ok
as this second case would be pronounced "initial-Ale-d" rather than "initial-ud". This is perhaps somewhat related to for instance the word "impaled", so clearly the "-aled" construct has one use case.


text:
Q: Phoenix: Controller test vs view test? I have a controller:
defmodule ParrotApi.MeetupController do
  use ParrotApi.Web, :controller
  alias ParrotApi.Meetup

  def index(conn, _params) do
    one_hour_ago = Timex.now
                   |> Timex.shift(hours: -1)
                   |> Timex.to_unix
    meetups = from(m in Meetup, where: m.timestamp >= ^one_hour_ago)
              |> Repo.all
              |> Repo.preload(:topic)
    render conn, meetups: meetups
  end
end

and a view for this controller:
defmodule ParrotApi.MeetupView do
  use ParrotApi.Web, :view

  def render("index.json", %{ meetups: meetups }) do
    render_many(meetups, ParrotApi.MeetupView, "meetup.json")
  end

  def render("meetup.json", %{ meetup: meetup }) do
    %{
      id: meetup.id,
      timestamp: meetup.timestamp,
      topic: meetup.topic.title,
    }
  end
end

I'm writing my first controller test:
defmodule ParrotApi.MeetupControllerTest do
  use ParrotApi.ConnCase
  alias ParrotApi.Meetup
  alias ParrotApi.Topic
  alias ParrotApi.Repo

  require Logger

  describe "#index" do
    test "returns future meetups" do
      topic_title = "Is Jesus your savior?"
      future_time = Timex.now
                    |> Timex.shift(minutes: 1)
                    |> Timex.to_unix
      {:ok, topic} = Topic.changeset(%Topic{}, %{title: topic_title}) |> Repo.insert
      {:ok, meetup} = Meetup.changeset(%Meetup{}, %{timestamp: future_time, topic_id: topic.id}) |> Repo.insert

      conn = build_conn()
      conn = get conn, meetup_path(conn, :index)

      assert json_response(conn, 200) == [
        %{
          "id" => meetup.id,
          "timestamp" => future_time,
          "topic" => topic_title,
        }
      ]
    end

It passes. However... it feels like a view test to me? It's testing the decorated/presented response that the view manipulates. So I don't really know what to do for my view test.
Is there a way to test the render conn, meetups: meetups response only, and then extract the stuff currently in my controller test into a view test? Or is this the wrong way to test things?

A: Although I think testing best practices are a lot about a developers opinions and biases, I strongly agree that your test is testing something outside of its responsibility and that the actual JSON structure should be tested in the view test.
Personally, I prefer testing json responses for their content as well as the response status in the controller test, however your test makes a very strong assumption about the "how is the jsons structured" instead of "what is the content".
You would usually leave the json creation to the json creator (your view) and only care about "does the controller render what it is supposed to render?"
If I was pressed to sum up the most important thing for testing in one sentence it would be: "Formulate what you want to test in your mind and then try to make your testing code read exactly like that". So basically what I want my test to read like is this:

I am expecting a json encoded response with the status code 200 of all future meetups.

test "returns future meetups" do
  topic_title = "Is Jesus your savior?"
  future_time = Timex.now
                |> Timex.shift(minutes: 1)
                |> Timex.to_unix
  {:ok, topic} = Topic.changeset(%Topic{}, %{title: topic_title}) |> Repo.insert
  {:ok, meetup} = Meetup.changeset(%Meetup{}, %{timestamp: future_time, topic_id: topic.id}) |> Repo.insert

  conn = build_conn()
  conn = get conn, meetup_path(conn, :index)

  future_meetups_json = MeetupView.render("index.json", %{meetups: MeetupQuery.future_meetups()})

  assert conn.status == 200
  assert conn.response_body == future_meetups_json
end

With the meetup query tucked away in a seperate method, you can test it seperately to ensure it really only returns the meetups it should return and the actual view testing can be done in the view tests :)


text:
Q: How to catch IllegalStateException displayed in Firebase coming from Apollo GraphQL Android SDK I'm unsure of how to catch this crash tracked in Firebase in our codebase which is coming from the Apollo GraphQL SDK for Android, version 2.5.12. I have also not been able to reproduce it. It seems to be similar to this issue: https://github.com/awslabs/aws-mobile-appsync-sdk-android/issues/153. Though, that issue is from RealAppSync, not Apollo.
Because Apollo uses callbacks, is it even possible to catch and handle this IllegalStateException in our codebase? Below is the stacktrace.
Fatal Exception: java.lang.IllegalStateException
Found: TERMINATED, but expected [ACTIVE, CANCELED]

com.apollographql.apollo.internal.RealApolloCall.responseCallback (RealApolloCall.java:367)
com.apollographql.apollo.internal.RealApolloCall$1.onFetch (RealApolloCall.java:287)
com.apollographql.apollo.internal.fetcher.CacheFirstFetcher$CacheFirstInterceptor$1.onFetch (CacheFirstFetcher.java:48)
com.apollographql.apollo.internal.interceptor.ApolloCacheInterceptor$1.run (ApolloCacheInterceptor.java:60)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
java.lang.Thread.run (Thread.java:923)

A: This looks like this issue, for which a fix is currently pending to be part of the next release of Apollo Android 2.x.


text:
Q: Database design with undetermined data Recently I have been planning a system that allows a user to customize and add to a web interface. The app could be compared to a quiz creating system. The problem I'm having is how to design a schema that will allow for "variable" numbers of additions to be made to the application.
The first option that I looked into was just creating an object for the additions and then serializing it and putting it in its own column. The content wouldn't be edited often so writing would be minimal, reads however would be very often. (caching could be used to cut down)
The other option was using something other than mysql or postgresql such as cassandra. I've never used other databases before but would be interested in learning how to use them if they would improve the design of the system.
Any input on the subject would be appreciated.
Thank you.
*edit 29/3/14
Some information on the data being changed. For my idea above of using a serialized object, you could say that in the table I would store the name of the quiz, the number of points the quiz is worth and then a column called quiz data that would store the serialized object containing the information on the questions. So overall the object could look like this:
Questions(Array):{
    [1](Object):Question{
        Field-type(int):1
        Field-title(string):"Whats your gender?"
        Options(Array):{"Female", "Male"}
        }
    [2](Object):Question{
        Field-type(int):2
        Field-title(string):"Whats your name?"
        }
}

The structure could vary of course but generally i would be storing integers to determin the type of field in the quiz and then a field to hold the label for the field and the options (if there are any) for that field.

A: In this scenario I would advise looking at MongoDB.
However if you want to work with MySQL you can think about the entity-attribute-value model in your design. The EAV model allows you to design for entries that contain a variable number of attributes.
edit
Following your update on the datatypes you would like to store, you could map your design as follows:
+-------------------------------------+
| QuizQuestions                       |
+----+---------+----------------------+
| id | type_id | question_txt         |
+----+---------+----------------------+
| 1  |    1    | What's your gender?  |
| 2  |    2    | What's your name?    |
+----+---------+----------------------+

+-----------------------------------+
| QuestionTypes                     |
+----+--------------+---------------+
| id | attribute_id | description   |
+----+--------------+---------------+
| 1  |      1       | Single select |
| 2  |      2       | Free text     |
+----+--------------+---------------+

+----------------------------+
| QuestionValues             |
+----+--------------+--------+
| id | question_id  | value  |
+----+--------------+--------+
| 1  |      1       | Male   |
| 2  |      1       | Female |
+----+--------------+--------+

+-------------------------------+
| QuestionResponses             |
+----+--------------+-----------+
| id | question_id  | response  |
+----+--------------+-----------+
| 1  |      1       | 1         |
| 2  |      2       | Fred      |
+----+--------------+-----------+

This would then allow you to dynamically add various different questions (QuizQuestions), of different types (QuestionTypes), and then restrict them with different options (QuestionValues) and store those responses (QuestionResponses).


text:
Q: write error: Broken pipe I have to run a tool on around 300 directories. Each run take around 1 minute to 30 minute or even more than that. So, I wrote a python script having a loop to run the tool on all directories one after another.
my python script has code something like:
for directory in directories:
  os.popen('runtool_exec ' + directory)

But when I run the python script I get the following error messages repeatedly:
..
tail: write error: Broken pipe
date: write error: Broken pipe
..

All I do is login on a remote server using ssh where the tool, python script, and subject directories are kept. When I individually run the tool from command prompt using command like:
runtool_exec directory

it works fine. "broken pipe" error is coming only when I run using the python script.
Any idea, workaround?

A: The errors you see are because you're using os.popen() to run the command, which means a pipe is opened and connected to the command's stdout. Whenever the command (or anything it executes without redirecting stdout) wants to write to stdout, it'll try to write to the pipe. But you don't keep the pipe around, since you don't assign the result of os.popen() anywhere, so it's cleaned up by Python, and closed. So the processes that try to write to it encounter a broken pipe, and produce the error you see. (os.popen() does not redirect stderr to the pipe, so you still see the errors.)
Another problem in your os.popen() call is that you don't check to make sure directory doesn't contain any characters special to your shell. If the directory contained a quote, for example, or a *, weird things might happen. Using os.popen() like that is pretty bad.
You should use subprocess.Popen() instead, and explicitly tell it what you want to do with the process's output (both stdout and stderr.) You pass subprocess.Popen() a list of arguments (including the thing you want to start) instead of a single string, and it avoids the shell altogether -- no need to sanity-check your strings. If you really want to ignore the output, you would do it with something like:
devnull = open(os.devnull, 'w')
for directory in directories:
    subprocess.Popen(['runtool_exec', directory], stdout=devnull)

although I would strongly recommend at least doing some rudimentary checks on the result of subprocess.Popen to see if the process didn't execute prematurely or with an error code.

A: In case it's helpful for anyone else, this same problem can be a result of using pipes (|) in the shell command.  See here for solution https://stackoverflow.com/a/4106633/1904913


text:
Q: Add a row to RoR database that references other tables I have a table Owners, and Pets. Each Owner has_many pets, and each pet belong_to owner. I'm writing a function that creates a new pet by taking in the owner_id and the pet information. So far I have
pet = Pet.new(pet_hash)
pet.save

But how do I associate that Pet with the owner_id?

A: Assuming you have the owner, you can do something like:
owner.pets.build(pet_hash)
owner.save


text:
Q: export is not recognize in cmd while Cygwin is installed My machine is running win7 64bit. I installed Cygwin and added C:\cygwin64\bin to the PATH. Now linux commands work on cmd , but export is not recognized:

'export' is not recognized as an internal or external command,
  operable program or batch file.

while it works properly in Cygwin64 Terminal. How should I add it to windows default cmd?

A: export is not recognized in cmd.

'export' is not recognized as an internal or external command, operable program or batch file.

Let's open a bash shell and look for the export command:
DavidPostill@Hal /f/test
$ which export
which: no export in (.:/home/DavidPostill/bin:/usr/local/bin:/usr/bin:/c/Windows/system32:/c/Windows)

That tells us that there isn't a program called export.
So what is it?

export is a bash built in command.

Source export.
It has no meaning outside of a bash shell.

Further Reading

*

*An A-Z Index of the Bash command line for Linux -  An excellent reference for all things Bash command line related.

*export - Set an environment variable. Mark each name to be passed to child processes in the environment.

A: EXPORT SQUAD_DIRECTORY ="/path/to/SQUAD"

Alternative for export in windows is SET :
SET SQUAD_DIRECTORY ="/path/to/SQUAD"

Refer : https://ss64.com/nt/set.html

A: In Windows use set instead of export.

A: 'set export' work for me on windows 10


text:
Q: How to restrict CKEditor to paste only 2000 characters? I have integrated CKEditor in my JSF file. I need to allow only 2000 characters in the editor but while pasting it is taking more than 2000 characters. How can I restrict the editor to take only 2000 characters.

A: If you not already are, you can use PrimeFaces Extensions library, which contains the pe:ckEditor component. You can simply add a f:validateLength validator to it like:
<pe:ckEditor ...>
  <f:validateLength maximum="2000"/>
</pe:ckEditor>


text:
Q: Why are these sites receiving network timeouts for me, but not for others? I've kind of ran into an ugly snag.  I developed a website for a client a few years back, and since then they've transferred their site to a different domain name provider and host.  Now they want some updates, but when I try to access their site I get a Network Timeout (the page just tries to load for a few minutes, then firefox shows a Network Timeout error).  I can access the site via a proxy, but proxies kinda suck and don't support everything, plus I'm a little paranoid about sending sensitive data through a proxy, not to mention I don't see how that would help me with FTP access and what not.  I'm not exactly sure where along the line this problem is occurring... is my ISP blocking it, is the webserver blocking me, is it my router, or what's going on? I know of two sites that do this, and I think they're hosted by the same people.
The sites are http://fvringette.com/ and http://damngoodtimes.com/

@MarkusQ: traceroute for fvringette.com (which turns out to be the same as with damngoodtimes.com)
traceroute: Warning: Multiple interfaces found; using 134.117.14.35 @ hme0
traceroute to 76.74.225.90 (76.74.225.90), 30 hops max, 40 byte packets
 1  unix-gate.physics.carleton.ca (134.117.14.1)  0.973 ms  0.513 ms  0.514 ms
 2  10.50.254.3 (10.50.254.3)  0.437 ms  0.385 ms  0.351 ms
 3  10.30.33.1 (10.30.33.1)  0.488 ms  0.394 ms  0.370 ms
 4  10.30.55.1 (10.30.55.1)  0.396 ms  0.416 ms  0.391 ms
 5  134.117.254.242 (134.117.254.242)  0.708 ms  0.720 ms  0.704 ms
 6  10.30.57.1 (10.30.57.1)  1.338 ms  1.221 ms  1.237 ms
 7  kolker.fcican.com (207.34.252.249)  1.464 ms  1.544 ms  1.459 ms
 8  * * *
 9  154.11.3.17 (154.11.3.17)  7.355 ms  7.393 ms  7.426 ms
10  oc48.so-2-0-3.van-hc21e-cor-1.peer1.net (216.187.114.137)  62.762 ms  62.838 ms  62.625 ms
11  oc48.pos4-0.van-hc21e-dis-1.peer1.net (216.187.89.253)  62.795 ms  63.238 ms  62.893 ms
12  64.69.91.245 (64.69.91.245)  64.103 ms  62.908 ms  63.266 ms
13  64.69.91.245 (64.69.91.245)  63.094 ms !H  63.072 ms !H  63.173 ms !H

64.69.91.245 - Geo Information
IP Address  64.69.91.245
Host        64.69.91.245
Location    CA CA, Canada
City        Vancouver, BC v6b4n5
Organization    Peer1 Internet Bandwidth & Server Co-Location Faci
ISP         Peer 1 Network
AS Number   AS13768
Latitude    49°25'00" North
Longitude   123°13'33" West
Distance    9281.29 km (5767.13 miles)

64.69.91.245 - Whois Information
OrgName:    Peer 1 Network Inc.
OrgID:      PER1
Address:    75 Broad Street
Address:    2nd Floor
City:       New York
StateProv:  NY
PostalCode: 10004
Country:    US

NetRange:   64.69.64.0 - 64.69.95.255
CIDR:       64.69.64.0/19
NetName:    PEER1-BLK-01
NetHandle:  NET-64-69-64-0-1
Parent:     NET-64-0-0-0-0
NetType:    Direct Allocation
NameServer: NS1.PEER1.NET
NameServer: NS2.PEER1.NET
Comment:
RegDate:    2000-04-12
Updated:    2007-08-29

RTechHandle: ZP55-ARIN
RTechName:   Peer1 Network Inc.
RTechPhone:  +1-604-683-7747
RTechEmail:  net-admin@peer1.net

OrgAbuseHandle: NSA-ARIN
OrgAbuseName:   Peer 1 Network AUP Enforcement
OrgAbusePhone:  +1-604-484-2588
OrgAbuseEmail:  abuse@peer1.net

OrgTechHandle: ZP55-ARIN
OrgTechName:   Peer1 Network Inc.
OrgTechPhone:  +1-604-683-7747
OrgTechEmail:  net-admin@peer1.net

OrgName:    Peer1 Internet Bandwidth & Server Co-Location Facilities
OrgID:      PIBSCF
Address:    2100-555 W. hastings St.
City:       Vancouver
StateProv:  BC
PostalCode: V6B 4N5
Country:    CA

NetRange:   64.69.91.240 - 64.69.91.255
CIDR:       64.69.91.240/28
NetName:    PEER1-GVLANPRI-01
NetHandle:  NET-64-69-91-240-1
Parent:     NET-64-69-64-0-1
NetType:    Reassigned
Comment:
RegDate:    2002-03-14
Updated:    2002-03-14

RTechHandle: MT1763-ARIN
RTechName:   Teolis, Mark
RTechPhone:  +1-604-683-7747
RTechEmail:  net-admin@peer1.net

# ARIN WHOIS database, last updated 2009-04-06 19:10
# Enter ? for additional hints on searching ARIN's WHOIS database.

It occured to me that it may be more useful if I do a trace from my home computer, to fvringette.com rather than from some random computer which may actually be able to connect. Output of tracert:
  1    <1 ms    <1 ms    <1 ms  <snip>
  2    24 ms    24 ms    23 ms  70.71.106.1
  3    24 ms    24 ms    24 ms  rd1bb-ge5-0-0-1.vc.shawcable.net [64.59.149.2]
  4    25 ms    29 ms    29 ms  rc2bb-tge0-15-0-0.vc.shawcable.net [66.163.69.137]
  5    28 ms    30 ms    29 ms  rc2wh-tge0-15-1-0.vc.shawcable.net [66.163.69.121]
  6    25 ms    24 ms    24 ms  204.239.129.213
  7    26 ms    29 ms    29 ms  oc48.pos3-0.van-spenc-dis-1.peer1.net [216.187.89.250]
  8    27 ms    29 ms    30 ms  64.69.91.245
  9     *        *        *     Request timed out.
 10     *        *        *     Request timed out.

After this all requests just keep timing out. It's the same IP, 64.69.91.245 that seems to be causing the problem... does this mean that I'm just unlucky and got a dead server that won't forward my request? I have no idea how these things work.

I can ping 64.69.91.245, but not telnet 64.69.91.245. It says 'connect failed', not 'connection refused'... I can't think of why it would fail for me, but no one else?

A: Try doing a traceroute for starters.
The "!H"s on line 13 mean that the host (64.69.91.245) is unreachable--but not all the time (see line 12).  This looks at a glance to be further than your ISP, maybe at theirs.
Next step would be to figure out who that is...

A: My guess is either their hardware is faulty, or that they are blocking you inadvertently.
Some networks have the policies to block telnet connections/packets on the premise that they are unencrypted and only allow SSH.
Of course they may be blocking you for another reason.

A: Perhaps you should discuss it with them.  It may be the case that they have blocked your IP address because you've been trying to telnet into their servers all day. :)


text:
Q: how to implement Northwind in Django I am trying to implement Northwind database model in MySQL using Django-admin for displaying data. Does someone know how to do it "clean" way from original model? Is there any functional implementation to download (models, admin)?

A: Totally untried procedure follows. Not sure what you mean by 'clean'. Here's a few things on the internet that might help:
Step 1 - export from Access to MySQL:
http://www.geeksengine.com/article/export-access-to-mysql-4.html
Step 2 - point django at the database and use inspectdb to create models.py
https://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb
Step 3 - clean up models.py, run syncdb, add it to the admin, see what you go.
Step 4 - ask this guy if he ever managed it:
http://ifdebug.com/django-northwind-coming-soon/ - he's had four years!

A: https://github.com/ouykjh/northwind_management/
I managed to create models for Northwind Database.
Just clone the repo. Make sure that settings.py are set.
Enter postgres -> create database named 'mydb' (as in settings.py).
Hit python manage.py syncdb - it will create tables with relations.
Enter postgres -> psql mydb
hit
\i inserty.psql
Inserts are here(https://github.com/ouykjh/northwind_management/blob/master/inserty.sql#L11)
Hope it works :)


text:
Q: summarize word count for a timeframe I have the below table which stores the response text and the keyword search associated with it.
create table nlp.search(response string, words string,inquiry_time timestamp);
insert into nlp.search values('how to reset password','reset word password',TIMESTAMP ("2021-09-19 05:30:00+00"));
insert into nlp.search values('how to reset password','reset passphrase',TIMESTAMP ("2021-09-20 07:30:00+00"));
insert into nlp.search values('how to reset password','password',TIMESTAMP ("2021-09-16 08:30:00+00"));
insert into nlp.search values('how to reset password','reset',TIMESTAMP ("2021-09-14 08:30:00+00"));
I want to provide a summary report in this format
response and the count of each individual words associated with it.
response                                     individual_word_count
how to reset password                        reset(3) word(1) password(2) passphrase(1)
also the timestamp column inquiry_time can be passed to narrow down the date range and the summary values must be computed accordingly
e.g for timeframe filter 2021-09-19 till 2021-09-20
response                                     individual_word_count
how to reset password                        reset(2) word(1) password(1) passphrase(1)
can this be accomplished using a view?

A: Use below
select response, word, count(1) ndividual_word_count
from `nlp.search`,
unnest(split(words, ' ')) word
where date(inquiry_time) between '2021-09-19' and '2021-09-20'
group by response, word

if applied to sample data in your question - output is

I Need to display the word and count in 1 single column

use below then
select response,
  string_agg(format('%s (%i)', word, individual_word_count)) counts
from (
  select response, word, count(1) individual_word_count
  from `nlp.search`,
  unnest(split(words, ' ')) word
  where date(inquiry_time) between '2021-09-19' and '2021-09-20'
  group by response, word
)
group by response

with output


text:
Q: Abstract baseclass: How to add a standard action after unique implementations of abstract method? I'd like to reduce boiler plate code needed to implement my FooBC abstract baseclass for dataclasses. What the ABC needs to do:

*

*Every inheritor will be created slightly differently from (eg) a float, that's why each needs to implement the from_float() class method.

*but all inheritors should save float_value / 2. How can I automate this? Currently, the user is forced to paste float_value / 2 in each implementation of from_float().

Right now, this is my code:
# Abstract Base Class
@dataclass
class FooBC(ABC):
   always_save_half: float

@classmethod
@abstractmethod
def from_float(cls, value: float):
    pass

def __post_init__(self):
    """Allows inheritance by 'dataclasses'"""
    # just intercept the __post_init__ calls so they
    # aren't relayed to `object`

# Inheritor
@dataclass
class FooInheritor(FooBC):
    special_foo_result: float

    def from_float(cls, value: float):
        return cls(
            special_foo_result: value * 10,  # intended, unique use of 'from_foodata'
            ##### IDENTICAL FOR ALL INHERITORS; HOW CAN I GET RID OF THIS: #####
            always_save_half: value / 2,
        )

I'd love to reduce the Inheritor boiler plate to:
# Inheritor
@dataclass
class FooInheritor(FooBC):
    special_foo_result: float

    def from_float(cls, value: float):
        return cls(
            special_foo_result: value * 10,  # intended, unique use of 'from_float'
        )

How can I upgrade the FooBC class to automatically save float_value/2 whenever from_float is called?
I imagine something like this would be great:
# Abstract Base Class
@dataclass
class FooBC(ABC):
   _always_save_half: float = field(init=False, repr=False)

@classmethod
@abstractmethod
def from_float(cls, value: float):
    pass

@use_input.from_float  # my fantasy decorator, using from_float()'s input
def _init_after_from_float(value: float):
    self._always_save_half = value / 2

@property
def always_save_half() -> float:
    return self._always_save_half
...


text:
Q: Python multithreading - play multiple sine waves simultaneously I would like to generate sine wave noises at a given frequency and duration. I would like this to play simultaneously while using a GUI.
I've created a class that makes use of threading but it doesn't seem to work. I cannot execute code at the same time as invoking the .run() line. For example when running the below code, the print statement executes after the sound has completed.
import pyaudio
import numpy as np
import threading

class WavePlayerLoop(threading.Thread) :
  """
  A simple class based on PyAudio to play sine wave at certain frequency.
  It's a threading class. You can play audio while your application
  continues to do stuff.
  """

  def __init__(self, freq=440., length=1., volume=0.5):
    threading.Thread.__init__(self)
    self.p = pyaudio.PyAudio()

    self.volume = volume     # range [0.0, 1.0]
    self.fs = 44100          # sampling rate, Hz, must be integer
    self.duration = length   # in seconds, may be float
    self.f = freq            # sine frequency, Hz, may be float

  def run(self) :
    """
    Just another name for self.start()
    """
    # generate samples, note conversion to float32 array
    self.samples = (np.sin(2*np.pi*np.arange(self.fs*self.duration)*self.f/self.fs)).astype(np.float32)

    # for paFloat32 sample values must be in range [-1.0, 1.0]
    self.stream = self.p.open(format=pyaudio.paFloat32,
                    channels=1,
                    rate=self.fs,
                    output=True)

    # play. May repeat with different volume values (if done interactively)
    self.stream.write(self.volume*self.samples)

    self.stream.stop_stream()
    self.stream.close()

    self.p.terminate()

s = WavePlayerLoop(freq=440., length=10., volume=0.5)
s.run()
print 'this should print while there is a beep sound'

What do I need to do to allow this sound to play simultaneously while other code can execute?

A: You seem to have got it fully right. Following test code is working perfectly fine with your code.
objs = []
number_of_threads = 10

print 'Creating thread objects'
for i in range(number_of_threads):
    objs.append(WavePlayerLoop(freq=440 * i, length=10., volume=0.1 * i))

print 'Starting thread objects'
for i in range(number_of_threads):
    objs[i].start()

print 'Waiting for threads to finish'
for i in range(number_of_threads):
    objs[i].join()

print ('Finishing program')

A: Here's a cleaned up and Python-3-ified version that might be helpful for the contemporary seeker
import numpy as np
import pyaudio
import threading

class WavePlayerLoop(threading.Thread):

    def __init__(self, freq=440., volume=0.5, duration=1.):
        threading.Thread.__init__(self)
        self.p = pyaudio.PyAudio()
        self.volume = volume     # range [0.0, 1.0]
        self.fs = 44100          # sampling rate, Hz, must be integer
        self.duration = duration # in seconds, may be float
        self.f = freq            # sine frequency, Hz, may be float

    def run(self) :
        self.samples = (np.sin(2*np.pi*np.arange(self.fs*self.duration)*self.f/self.fs)).astype(np.float32)
        self.stream = self.p.open(format=pyaudio.paFloat32,
                              channels=1,
                              rate=self.fs,
                              output=True)
        self.stream.write(self.volume*self.samples)
        self.stream.stop_stream()
        self.stream.close()
        self.p.terminate()

duration = 5
tones = [
    {'frequency': 100, 'volume': .8},
    {'frequency': 200, 'volume': .6},
    {'frequency': 500, 'volume': .4},
]
for tone in tones:
    WavePlayerLoop(tone['frequency'], tone['volume'], duration).start()


text: Q: Load balancing issue during performance testing A strange observation from a recent test. Any direction would really help. 2 load balanced presentation servers are showing cpu usage moving in opposite direction i.e. 1 node reaches 100% gradually while the other node cpu usage decreases after test is started. The next day test, same pattern was seen but node 2 was reaching 100% but node 1 usage decreased.  From F5 we can see connections are nearly equal in both nodes. F5 rule is round robin.


text:
Q: To speed up the SUM and Filter functions I wrote following MDX query:
 SUM(
        (
        Filter
            ([Shop].[Shop ID].[Shop ID].Members,
            IsEmpty(([Time].[Calendar].CurrentMember))
            = false
            AND
            IsEmpty(([Time].[Calendar].CurrentMember.Lag(1)))
            = false
            AND
            IsEmpty(([Time].[Calendar].CurrentMember.Lag(2)))
            = false)
        ,
        [Measures].[Real weight]
        )
    )

However it works slow. I believe I can speed it up. Any ideas?
I've read the following blog, but it didn't help me much. Probably I miss something important there:
http://sqlblog.com/blogs/mosha/archive/2005/02/13/performance-of-aggregating-data-from-lower-levels-in-mdx.aspx
Thanks in advance!
EDIT:
I'm sorry, find the answer here: http://sqlblog.com/blogs/mosha/archive/2008/10/22/optimizing-mdx-aggregation-functions.aspx
SUM([Shop].[Shop ID].[Shop ID].Members,
        (
        IIF(

            IsEmpty(([Time].[Calendar].CurrentMember,[Measures].[Real weight]))
            = false
            AND
            IsEmpty(([Time].[Calendar].CurrentMember.Lag(1),[Measures].[Real weight]))
            = false
            AND
            IsEmpty(([Time].[Calendar].CurrentMember.Lag(2),[Measures].[Real weight]))
            = true

            ,
            [Measures].[Real weight]
            ,
            NULL)
        ))

A: I'm sorry, find the answer here: http://sqlblog.com/blogs/mosha/archive/2008/10/22/optimizing-mdx-aggregation-functions.aspx
SUM([Shop].[Shop ID].[Shop ID].Members,
        (
        IIF(

            IsEmpty(([Time].[Calendar].CurrentMember,[Measures].[Real weight]))
            = false
            AND
            IsEmpty(([Time].[Calendar].CurrentMember.Lag(1),[Measures].[Real weight]))
            = false
            AND
            IsEmpty(([Time].[Calendar].CurrentMember.Lag(2),[Measures].[Real weight]))
            = true

            ,
            [Measures].[Real weight]
            ,
            NULL)
        ))


text:
Q: Blur half a page I need to blur the content of half a page, basically I need to show a document preview before the customer pays for it.
In order to accomplish that I have a HTML page which looks pretty much like this:

I need to apply a blur, the blur should start from the 50% of the page height, then I will take an screenshot and show that image to the customer.
So:

*

*I can't apply the filter blur to a div because there are many divs involved. Lets say that the blur will start from somewhere around "Where does it come from"

*I tried to add a div position absolute with a filter blur, but the blur is not being applied over the text. I also tried to do that with SVGs but no joy.

Ideas?

A: Here's a solution that may be a bit rickety, but works - in Firefox, at least:
<?xml version="1.0" standalone="yes"?>
<svg width="600" height="800" version="1.1"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     xmlns:html="http://www.w3.org/1999/xhtml">
  <filter id="halfBlur" filterUnits="objectBoundingBox" x="0" y="0.5" width="1" height="0.5">
    <feGaussianBlur in="SourceGraphic" stdDeviation="2" />
  </filter>
  <g id="source">
    <foreignObject width="600" height="800">
      <html:iframe style="width:600px;height:800px" src=""></html:iframe>
    </foreignObject>
  </g>
  <use xlink:href="#source" filter="url(#halfBlur)"/>
</svg>

Mark that the <use> element only works if it references an SVG container element, but not the <foreignObject> directly.
Care must be taken to make all elements big enough to contain the complete html page. As an extra measure, it might be a good idea to provide the html element of the embeded page with a overflow:hidden rule. If scrollbars show up, they will work on both halfs of the page independently.


text:
Q: zipping a folder using 7zip and python sub process module I am trying to zip a folder using subprocess:
zip_file = "7z a \"%s\" \"%s\"" %( afterzip, beforezip )
retV = subprocess.Popen(zip_file, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
outData = retV.stdout.readlines()

this particular code works for files not folders.
The zip itself is created but it is empty. The command itself works for folders in CMD. All help is appreciated.


text:
Q: Open application with bundle identifier Is it possible to open a application from our application with bundle identifier. Suppose I have two apps installed on device one with com.test.app1 and com.test.app2. Can I open app1 from my app2.
I know about openUrl method. for that I have to register url scheme in info.plist. and then i can use following method:
[[UIApplication sharedApplication] openUrl:[NSURL urlWithString:@"myApp1://"]];

But what if I didn't register url scheme or don't know the registered url.
Any idea..?

A: The Swift version of @EvanJIANG answer.
guard let obj = objc_getClass("LSApplicationWorkspace") as? NSObject else { return false }
let workspace = obj.perform(Selector(("defaultWorkspace")))?.takeUnretainedValue() as? NSObject
let open = workspace?.perform(Selector(("openApplicationWithBundleID:")), with: "com.apple.mobilesafari") != nil
return open

A: I don't think that's possible.

A: You can use the openUrl call, but in order to succeed you must add some values to your project's xy-Info.plist file.

Once you've done that you can then call:
[[UIApplication sharedApplication] openUrl:[NSURL urlWithString:@"xingipad://"]];

A: You can use private API to do that
Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
NSObject * workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
BOOL isopen = [workspace performSelector:@selector(openApplicationWithBundleID:) withObject:@"com.apple.mobilesafari"];

A: Answer: You can't open app directly only with Bundle identifier.
Solution: You can implement deep linking (and take your bundle id as your deep linking id)concept to do this: Deep-linking

A: It is possible using URL Schemes .


text:
Q: How to set a selected value by using id on selectpicker plugin from bootstrap I'm testing the selectpicker plugin of bootstrap like this:
HTML
<select class="selectpicker form-control" id="preffrom">
  <optgroup label="北海道" class="area-hokkaido">
    <option id="p01">北海道</option>
  </optgroup>
  <optgroup label="東北" class="area-tohoku">
    <option id="p02">青森県</option>
    <option id="p03">岩手県</option>
    ...
    <option id="p07">福島県</option>
  </optgroup>
  ...
  <optgroup label="沖縄" class="area-okinawa">
    <option id="p47">沖縄県</option>
  </optgroup>
</select>

JavaScript
$(function(){
  $('.selectpicker').selectpicker();
  // this event is for test  but it does not work...
  $('#test').bind('click', function(e){
    $('#preffrom').val('p03');
    $('#preffrom').selectpicker('refresh');
  });
});

I referenced this:
How to set selected value on select using selectpicker plugin from bootstrap
But nothing happens.
Please tell me correct way to select an option using id value.

A: If all you are trying to do is selected the #p03 option then $('#p03').prop('selected', true); should work (instead of $('#preffrom').val('p03');). Here is a working example: https://jsfiddle.net/kwm9rsee/


text:
Q: Why doesn't this org-mode header-arg get applied? When I try to run this:
** Header name
   :PROPERTIES:
   :header-args: :noweb yes
   :END:

#+NAME: prop_test
#+begin_src sh
  echo "...and it worked!"
#+end_src

#+begin_src sh
  echo "Beginning expansion..."
  <<prop_test>>
#+end_src

I get the error sh: 2: Syntax error: end of file unexpected.
If I add :noweb yes to the code header, it executes as expected. I thought the :header-args: property was supposed to do that automatically, but apparently it isn't. I've tried removing the whitespace separating the snippets and (unsurprisingly) it doesn't make a difference. I've tried specifying that the property is for sh (:header-args:sh:) but that doesn't do it either. Why doesn't the header-arg get applied?

A: I'm not sure why the code in the question doesn't work, since it's what's in the org-mode manual. What does work is the following, which I got from a different org-mode manual:
* Header name
  :PROPERTIES:
  :noweb: yes
  :END:

A: The syntax was changed with Org 8.0. The syntax in your answer is for <8.0. You are probably using your distro's Org which is still 7.something. You can set Orgmode.org as a source for package.el or el-get to stay with the latest org.
For the record, the code in your question yields:
1.1 Header name
───────────────

  ┌────
  │ echo "...and it worked!"
  └────

  ┌────
  │ echo "Beginning expansion..."
  │ echo "...and it worked!"
  └────


text:
Q: How can I install Ubuntu Server on HP MediaSmart (Model: EX495)? I have no idea how to install server OS. I'm not sure if this device supports 64-bit. If not, where can I download a 32-bit version?

*

*RAM: 2GB

*HDD: 160GB, 1.5TB and 40GB

The previous owner took all the HDD(s) out of the machine before he sold it to me and I don't have any recovery CD or anything like that.
My friend suggested I look into Ubuntu for my HP MediaSmart Server...
What should I do to install Ubuntu Server on this device?

A: The article at the following link describes a procedure that worked well for me.
https://dagolav.prestegarden.com/post/instaling-ubuntu-on-the-hp-mediasmart-ex490/
The basic idea is to take the boot disk out of the server and put it in another PC with keyboard and video support. Do the install and then put it back in the MediaSmart Server.
The article refers to Ubuntu 10, but I installed 18.04.1 successfully. I'd add that it's useful to install ssh server and perhaps xRdp for remote access, both of which I've done.
Don't expect zippy performance, it's a pretty underpowered box. Also, as yet it doesn't show all the drives that are physically plugged in. In my case it shows drive 1 and 3, but not 2 and 4.


text:
Q: CSS visited links code. Link who is opened to stay in other color. Where is my mistake? When someone open a link in my menu i want the style of the link to change with the same style as the hover and stay in this till the user is on that page.
I make mistake somewhere and i cant find where. I hope someone can help me. I know there is a lot of other similar questions but i know the way how to do it but i do some mistake in my code and cant find it.
EDIT:
I found where is my mistake so i will edit the code with the correct one if anyone needs this in the feature.
HTML CODE:

Home

Testimonials

Prices

Galerry

FAQ's

Contacts

CSS CODE of all of my menu links:
    #h_menu{
    width: 100%;
    height: 35px;
    background-color: #D8D8D8  ;
    margin:10px;
    margin-left: 0px;

}

.horizontal
{
    width: 100%;
    height: 30px;
}

.horizontal ul
{
    list-style-type: none;
    margin: 0;
    padding: 0;

}

.horizontal li
{
    float: left;
}

.horizontal a
{
    display: block;
    width: 116px;

}

.horizontal a:link, .horizontal a:active
{
    font-family: Arial, Helvetica, Sans-serif;
background-image:url(img/imgs/buttons1.png);
    font-size: 13px;
    text-decoration: none;
    border-right: 1px;
    border-color: grey;
    border-right-style: solid;
    padding-top: 9px;
    height: 22px;
    width: 151px;
    color: #B00000;
    font-weight: bold;

}
.horizontal a:visited{

font-family: Arial, Helvetica, Sans-serif;

    font-size: 13px;
    text-decoration: none;
    border-right: 1px;
    border-color: grey;
    border-right-style: solid;
    padding-top: 9px;
    height: 22px;
    width: 151px;
    color: #B00000;
    font-weight: bold;
}

.horizontal a:hover
{
        background-position: 0 -33px;
}
#h_menu .b
{
         background-position: 0 -33px;
}

A: I think you should use

background-color

instead of

color

in .horizontal a:visited class.
http://www.w3schools.com/cssref/tryit.asp?filename=trycss_sel_visited


text:
Q: Use variable in I have this code:
//This one gets the image from the first product in the product category category:

$catimg = get_the_post_thumbnail( $product->id, 'thumbnail' );

//This code contains custom text that also reads info from various variables, including the `$catimg` variable:

$cat_art1 =  '
'.$variable1.' This is some text that will be outputted to my site.

Here i want to screen the image
Some more text and another '.$variable.' to end the line';

I've tried various solutions from many google searches but none works for me as they all outputs the html tags. My output looks like this:

Is this possible to achieve?
Thanks!

A: As it says in the doc https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/ it return tag, not url.
To get the url, do
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );

Go to doc https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/ for further informations ;)

A: I think Your $catimg is returning nothing or blank string
I have tried this code in php fiddle with static image its working fine so your string interpolation is correct . Please Check your $catimg variable
<?php
//This one gets the image from the first product in the product category category:

$catimg = 'https://pbs.twimg.com/profile_images/718314968102367232/ypY1GPCQ_400x400.jpg';
$variable1 = "Rajesh";
$variable = "Text";
//This code contains custom text that also reads info from various variables, including the `$catimg` variable:

$cat_art1 =  '
'.$variable1.' This is some text that will be outputted to my site.

Here i want to screen the image
Some more text and another '.$variable.' to end the line';
echo $cat_art1;
?>

A: Reference: To Get image url
 wp_get_attachment_image_src( int $attachment_id, string|array $size = 'thumbnail', bool $icon = false )

//This one gets the image from the first product in the product category category:

$catimg = wp_get_attachment_image_src(get_the_post_thumbnail( $product->id, 'thumbnail' ));

//This code contains custom text that also reads info from various variables, including the `$catimg` variable:

$cat_art1 =  '
'.$variable1.' This is some text that will be outputted to my site.

Here i want to screen the image
Some more text and another '.$variable.' to end the line';


text:
Q: Kohana PHP and module hooks We're running a fairly customised version of Kohana PHP, where we have a extensive amount of base modules running and used for each web page.
I've been tasked in speeding up some of our applications and one of the modules we use and have written, which is included into every application, has a hook which initializes sessions.
Now this isn't a problem for the majority of apps, except for the one we have that serves images, as it's just being called by other apps, so sessions aren't needed.
So for instance we have the module hook: /modules/mod_name/hooks/sessions_hooks.php
In my app, I have the app hooks directory: /application/hooks/sessions_hooks.php
From the looks of things, the application hooks is not overriding the module one. I tried creating a similar module structure under my app to the main kohana module directory, but that didn't help either. It actually looks like modules are fully loaded before anything else happens, but I could be wrong.
How do I go about overriding a module hook with a website application hook?

A: You cant. Kohana includes every hook file. What if you add special checks in that module hook? For example, you can load config value.


text:
Q: Cumulative sums over run lengths. Can this loop be vectorized? I have a data frame on which I calculate a run length encoding for a specific column. The values of the column, dir, are either -1, 0, or 1.
dir.rle <- rle(df$dir)
I then take the run lengths and compute segmented cumulative sums across another column in the data frame. I'm using a for loop, but I feel like there should be a way to do this more intelligently.
ndx <- 1
for(i in 1:length(dir.rle$lengths)) {
    l <- dir.rle$lengths[i] - 1
    s <- ndx
    e <- ndx+l
    tmp[s:e,]$cumval <- cumsum(df[s:e,]$val)
    ndx <- e + 1
}

The run lengths of dir define the start, s, and end, e, for each run. The above code works but it does not feel like idiomatic R code. I feel as if there should be another way to do it without the loop.

A: Both Spacedman & Chase make the key point that a grouping variable simplifies everything (and Chase lays out two nice ways to proceed from there).
I'll just throw in an alternative approach to forming that grouping variable. It doesn't use rle and, at least to me, feels more intuitive. Basically, at each point where diff() detects a change in value, the cumsum that will form your grouping variable is incremented by one:
df$group <- c(0, cumsum(!(diff(df$dir)==0)))

# Or, equivalently
df$group <- c(0, cumsum(as.logical(diff(df$dir))))

A: Add a 'group' column to the data frame. Something like:
df=data.frame(z=rnorm(100)) # dummy data
df$dir = sign(df$z) # dummy +/- 1
rl = rle(df$dir)
df$group = rep(1:length(rl$lengths),times=rl$lengths)

then use tapply to sum within groups:
tapply(df$z,df$group,sum)

A: This can be broken down into a two step problem. First, if we create an indexing column based off of the rle, then we can use that to group by and run the cumsum. The group by can then be performed by any number of aggregation techniques. I'll show two options, one using data.table and the other using plyr.
library(data.table)
library(plyr)
#data.table is the same thing as a data.frame for most purposes
#Fake data
dat <- data.table(dir = sample(-1:1, 20, TRUE), value = rnorm(20))
dir.rle <- rle(dat$dir)
#Compute an indexing column to group by
dat <- transform(dat, indexer = rep(1:length(dir.rle$lengths), dir.rle$lengths))

#What does the indexer column look like?
> head(dat)
     dir      value indexer
[1,]   1  0.5045807       1
[2,]   0  0.2660617       2
[3,]   1  1.0369641       3
[4,]   1 -0.4514342       3
[5,]  -1 -0.3968631       4
[6,]  -1 -2.1517093       4

#data.table approach
dat[, cumsum(value), by = indexer]

#plyr approach
ddply(dat, "indexer", summarize, V1 = cumsum(value))


text:
Q: jQuery - catching validate error callback from server I'm trying to capture the jquery validate plugin error callback. I understand you can easily hook into this if I was calling validate directly:
$('#form').validate({
    invalidHandler: function(form, validator) {
       var errors = validator.numberOfInvalids();
       if (errors) {
           //etc
       }
    }
});

But I'm not. Instead, my form is submitted to server and if !Model.IsValid then the server returns the invalid model and populates the place holder  with the error message:
This field is required

I need to know when this span gets updated with the error message because I have the following wrapper for it:

     @Html.ValidationMessageFor(m => m.Email)  /*This is the span above*/

Where div.errorContainer { visibility : hidden; } and I need to make it visible only when there is an error message (because it has a background and does not belong unless there is an error inside).
How can I do this? The optimal solution would be where I can respond to the error from BOTH client and server side validation because I plan to build in the client-side validation after I make sure the server side is covered. I guess the better question then is, is there a way to have the invalidHandler callback fire from server returned errors?

A: I just thought of this and haven't  tested it yet but I think it will work. Will report back. Thanks Barney, your comment gave me a lightbulb.
$.ajax({
    url : '/Account/Login',
    dataType: $('#form').serialize(),
    beforeSend : function(xhr, opts){

        ... form validation ...

        if(formNotValid){
             xhr.abort(); /*Abort request*/
             /*Display client generated errors*/
        }

    },
    success: function(result){  // return from server is a JsonResult(new { success = true/false, viewResult = this.RenderPartialView("Login", model)})

        if(result.success){
            //No errors
        }
        else{

            /*Display server generated errors*/

            $('#form').empty().html(result.viewResult);
            $('span.field-validation-error').each(function () {
                 $(this).parent().css({ "visibility": "visible" });
            });

            $('span.field-validation-valid').each(function () {
                 $(this).parent().css({ "visibility": "hidden" });
            });
        }

    }
});

NOTE: this.RenderPartialView("Login", model) is a custom extension method found here


text:
Q: Excel Array Formula Error I am coming to seek guidance with another question with Excel Array Formulas.
I am using Excel 2003 and trying to understand a new spreadsheet with the following type of formula :
{=IF($B$6,SUM(($C$6:$AM$6=1)*1),)}

I have tried using the Excel formula audit tool to understand the formula but it crashes when I run it on these type of array formula.
As of now I am thinking that the formula does this :
B6 has a number = True / False
If True do SUM of (C6:AM6=1) and multiply by 1
If False do nothing

However, I am not 100% of the second statement. Does it say SUM the number of times 1 is present in C6:M6 then multiply by 1? If so why multiply by 1. My only guess on the latter is that the (C6:M6=1) returns a True or False value and the *1 converts it to 0 or 1. Then if this is correct, what is the purpose of the sum function?
Thanks for any guidance.

A: You are correct.
($C$6:$AM$6=1) returns an array of TRUE/FALSE values, which SUM would ignore.
Multiplying by 1 creates an array of 1/0 values, which are then added by SUM to create a count of the number of cells in the range that equal 1.
COUNTIF would be simpler as mentioned previously.

A: I think you do not need an array function.  Try this non-array formula:
=IF($B$6,SUMIF($C$6:$AM$6,1,$C$6:$AM$6),"Do Nothing")


text:
Q: display depth of stimulus (front, back, behind in front) According to http://www.psychopy.org/api/visual/textstim.html 'depth' is now deprecated and 'Depth is now controlled simply by drawing order.'
I'm using Builder 1.80.06 and have most stimuli defined in Routine dialogs but I need to draw some at runtime using code and I want them to go behind the other stimuli but can't work out how to do this.
Is there any way this can be done now?

A:
UPDATE: given the new details, I believe that Jon's answer is the correct one.
OLD ANSWER: Since 1.72.00, the order of drawing in Builder is controlled by their order in the rutine. The topmost component is drawn first, then then the second on top and so on. The bottom component is always on top.
The order of components in a routine can be changed by right-clicking on a component to bring up a contextual menu with items like "move up", "move down", "move to top", etc.
As a side note: in code, the drawing order is simply the order of the lines of code:
background.draw()
stim.draw()  # on top of background
fixationCross.draw()  # on top of the other.
win.flip()  # show it

You can verify that Builder does exactly this by looking at the python code it generates.

A: The Code Component code really is inserted in order, as well as the code form standard components. The order of code in different Routines during creation is unspecified (you don't have control over which Routine's "Begin Experiment" code is executed first) but this doesn't affect your drawing depth anyway.
The key is that in your Routine the code in the "Every Frame" section, with the draw() command, has to be in the right order (before your standard components).


text:
Q: Trying to define the set of alternate derivatives associated with the set of periodic functions with some rational number period I have been working on some math proofs and general theory stuff in a paper linked below and I have hit a mental block on something.
Piecewise Constant Functions in Differential and Functional Equations
On page 22 there is a definition given for the set of alternate derivatives associated with any differential fork, which is a set of functions. The set of periodic functions with a rational number period seems to meet the definition of a differential fork. So does anyone know how to write the associated alternate differential for that set aside from that definition? I'm trying to come up with a more useful way of writing it for that particular set, but I haven't been able to come up with anything for months.
I have really no clue at all how to go about doing it.

A: This is general theory and will still need some work. First we will prove a lemma needed to justify a restriction that will follow.

The set $S$ of all functions periodic with a period of $1$ is a differential fork.
Proof: First we establish that the set of all constant functions is a subset of $S$. This is observed by the fact that constant functions are periodic with any real number period.
Now we must prove that if $f \in S$ and $g \in S$ and $H(x,y)$ is some function of $x$ and $y$ then $M(x) = H(f(x),g(x)) \in S$. By the definition of periodicity we know that for all real numbers $x$ that $f(x) = f(x+1)$ and $g(x) = g(x+1)$. Therefore, substituting into $H(f(x),g(x))$ we have that $H(f(x),g(x)) = H(f(x),g(x))$ and therefore by transitivity we have that $M(x) = M(x+1)$ for all real numbers $x$. Therefore, by the definition of periodicity we have that $M(x) \in S$.
Therefore, by the definition of a differential fork we have that the set $S$ is a differential fork. []

The reason I did this is because it is particularly easier to deal with functions with period $1$ rather than arbitrary periods that are rational multiples of $1$. In fact, I would not be surprised if such an alternate differential has no closed form as a standard limit.
Here is my thinking which I will further develop into a formal definition. Consider the following graph of $\sin{x}$ (and please ignore that I forgot scale the period to $1$).

Each point on the graph $x$ has a line segment connecting it to $x+1$ and $x-1$. My thinking is that the operator I am seeking should a derivative whose value at $x$ is some (as of yet undetermined) set of linear combinations of the slope between each point and the point in the adjacent period.
In the case of sin or any periodic function this results in $0$ everywhere, which makes sense. Interestingly enough consider this graph of $x * \sin{x}$:
https://www.google.com/search?q=x*sin%28x%29&ie=utf-8&oe=utf-8
(zoom out a lot)
You should upper and lower curves that look like $x$ and $-x$. Note, the result we expect with the operator (ignoring the incompatible period) is $\sin{x}$! Taking that derivative on the upper and lower curves we would have them both evaluate to $1$ and $-1$.
This lends credence to method potentially working. Mostly, I am just working out the analytical details and whatnot it took me 2 years to formalize the other alternate derivative (for piecewise constant functions), so please don't get upset that I have not quite figured out the exact expression yet.


text:
Q: can not find corresponding collection of .wt file in mongodb I found a huge .wt file in mongodb dbPath:
ubuntu@node11:~$ sudo ls -lah /data/shard-cluster-test/s0  | grep collection-14
-rw------- 1 mongodb nogroup  18G Oct 25 22:57 collection-14--5786157352597922030.wt

But I can not find collection-14--5786157352597922030 in db.printCollectionStats()
I also tried to find the filename in the stats() of every collection in every database but can not find it.
I'm pretty sure there is no collection of that big size in my mongodb cluster, the biggest collection is 7.5GB and sharded into 3 shards, each about 2.8GB
So what is in the 18GB .wt file? Is it a corpse of a deleted collection? But the update time of the file is quite recent than any db operation.


text:
Q: Dax Query- To Calculate MAXID and Sum of Amount I have below sample data:
IncidentID  TransactionID   Recordeddate    Name    Amount
10             1             13/01/2023 Recovery 1000
10             2             13/01/2023 Reserve  2000
10             3             13/01/2023 Reserve  3000
10             4             14/01/2023 Reserve  4000
11             5             14/01/2023     Recovery 3000
11             6             14/01/2023 Payment  4000
12             7             14/01/2023 Reserve  5000
13             8             14/01/2023 Reserve  4000
13             9             14/01/2023 Payment  2000

I need to calculate sum of amount for each incident id, for each date only Max Transaction ID and Name should be Reserve only.
I tried doing it be below expression:
Table2 = summarize(Table,Table[IncidentID],Table[RecordedDate],Table[Name],"MAXID",
calculate(max(TransactionID),AllExcept(IncidentID,RecordDate,Name)))

this table is giving me required filtered table, but i am not able to add amount column.
If i add amount column grouping is not working, and i need to get amount included so that i can calculate sum of amount.
Expected- Not able to add amount column in this, as adding amount it is not giving required results.


text:
Q: Automatically select new elements on scroll Let's say i want to select all <a> tags of a webpage (like Facebook or so). I'm doing this by:
document.getElementsByTagName("a");

Currently, i'm just running a function every second or so, that search for all a-tags and then processes these a-tags.
The problem is however:

*

*Newly added  tags (by scrolling), will have to wait some time before being discovered

*Old tags will be discovered every time.

I don't think this is very efficient as well. How can I make a function that selects only newly added elements, and processes them directly?
Any ideas on how to do this efficient?

A: let's say the <a> tags are under a <div> tag.
you can try add listener to the <div> and check are the tag name of event.target and 'a' same when it clicked.
like this:
document.querySelector("div").addEventListener(function(e){
  alert(e.target.tagName === "a");
  // and do anything you want...
}


text:
Q: Uncaught ReferenceError: down_value is not defined at HTMLButtonElement.onclick Estoy tratando de hacer a base de dos botones un incremento y decremento de la variable que se mostrará en mitad de estos, la variable la uso en la función que llamo desde la de cada botón. Como puedo solucionar este error?
Mi html es el siguiente:

                      <button class="incremento" onclick="down_value()">
                          Disminuir
                      </button>

                      <button class="incremento" onclick="up_value()">
                          Aumentar
                      </button>

Mi javascript es este:
//Creo una función para aumentar el número
function up_value(){
  i_NTemp = i_TempObj + x;
  temperatura_objetivo();
  document.getElementById("i_tempobj").innerHTML=i_NTemp;
  console.log(i_NTemp);
}
//Creo una finción para disminui el número
function down_value(){
  i_NTemp = i_TempObj - x;
  temperatura_objetivo();
  document.getElementById("i_tempobj").innerHTML=i_NTemp;
  console.log(i_NTemp);
}

A: La solución que te propongo funcionaría correctamente...
const x = 1;
function up_value(){
    var i_TempObj = parseInt(document.getElementById("i_tempobj").innerHTML) || 0;
    i_NTemp = i_TempObj + x;
    // temperatura_objetivo();
    document.getElementById("i_tempobj").innerHTML=i_NTemp;
    console.log(i_NTemp);
}
//Creo una finción para disminui el número
function down_value(){
    var i_TempObj = parseInt(document.getElementById("i_tempobj").innerHTML) || 0;
    i_NTemp = i_TempObj - x;
    //temperatura_objetivo();
    document.getElementById("i_tempobj").innerHTML=i_NTemp;
    console.log(i_NTemp);
}

Eso sí... como ves, i_TempObj está definido dentro de cada función. También podrías definirlo fuera si lo haces cuando la página está completamente cargada (con window.onload)


text:
Q: Jenkins job unable to pass integer parameters into python script during build I have a python script that I tested on an EC2 instance, which works perfectly fine on the server but when I try to pass the same parameters from Jenkins job as shown below. I get the error message:

Security Group Created sg-ca09bcae in vpc vpc-d79691b9. Traceback (most recent call last):   File "./create_sg.py", line 32, in
        'FromPort': int(FROM_PORT_1.strip("")),
    marked build as failure Finished: FAILURE> ValueError: invalid literal for int() with base 10: 'within' Build
    step 'Execute shell'

I'm pretty sure the error is because of the string parameter that I'm passing through Jenkins parameters but there isn't an option to send both From and To ports as integers in jenkins parameters.
How can I set the parameters to an integer within Jenkins build job?
Python code to create SG:
#!/usr/bin/env python

import sys
import boto3
from botocore.exceptions import ClientError
region = "us-west-1"

VPC_ID=sys.argv[1]
SECURITY_GROUP_NAME=sys.argv[2]
DESCRIPTION=sys.argv[3]
IP_PROTOCOL_1=sys.argv[4]
FROM_PORT_1=sys.argv[5]
TO_PORT_1=sys.argv[6]
CIDR_IP_1=sys.argv[7]

ec2 = boto3.client('ec2')

response = ec2.describe_vpcs()

vpc_id = VPC_ID

try:
    response = ec2.create_security_group(GroupName=SECURITY_GROUP_NAME,Description=DESCRIPTION,VpcId=VPC_ID)
    security_group_id = response['GroupId']
    print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))

    data = ec2.authorize_security_group_ingress(
        GroupId=security_group_id,
        IpPermissions=[
            {'IpProtocol': IP_PROTOCOL_1,
             'FromPort': int(FROM_PORT_1),
             'ToPort': int(TO_PORT_1),
             'IpRanges': [{'CidrIp': CIDR_IP_1}]}
        ]
    )
    print('Ingress Successfully Set %s' % data)
except ClientError as e:
    print(e)

@nosklo, Suggested I try the following:
VPC_ID=sys.argv[1]
SECURITY_GROUP_NAME=sys.argv[2]
DESCRIPTION=' '.join(sys.argv[3:-4])
IP_PROTOCOL_1=sys.argv[-4]
FROM_PORT_1=sys.argv[-3]
TO_PORT_1=sys.argv[-2]
CIDR_IP_1=sys.argv[-1]

With which the ports are listed as 0 vs the values that I passed in the parameters.

A: I haven't any way to test this, but the error message shows the invalid int value as the word "within". That suggests that the Description parameter is being substituted directly onto a command line without any quoting, so that sys.argv[5] would indeed be the string "within". You might try including quotes around the description: `"Security group within dev environment".

A: I think what you're looking for is os.getenv:
import os

VPC_ID = os.getenv('VPC_ID')

print(VPC_ID)

should work.


text:
Q: Does Iterable#iterator() return a new iterator or an existing one? Does calling anIterable.iterator() return a new or an existing Iterator? Does it depend on the Iterable implementation?
More specifically, would the following code work as expected (i.e. the inner loop would iterate from the beginning)?
for (Item itemA : items) {
    for (Item itemB : items) {
        ....
    }
}

If not, than how can this be achieved on an Iterable?

A: Iterable
Iterable is the Interface, we need to provide implementation for iterator() method.
public class MyCollection<E> implements Iterable<E>{

    public Iterator<E> iterator() {
        return new MyIterator<E>();
    }
}

Implementation skeleton of the MyIterator class:
public class MyIterator <T> implements Iterator<T> {

    public boolean hasNext() {

        //implement...
    }

    public T next() {
        //implement...;
    }

    public void remove() {
        //implement... if supported.
    }
}

Using MyCollection generified, and with the new for-loop
public static void main(String[] args) {
    MyCollection<String> stringCollection = new MyCollection<String>();

    for(String string : stringCollection){

    }
}

For your 2nd question, output speaks, the inner loop will loop from the starting everytime.
public static void main(String[] args) {
        List<String> names = new ArrayList<String>();
        names.add("a1");
        names.add("a2");

        for (String itemA : names) {
            for (String itemB : names) {
                System.out.println("Inner => " + itemB);
            }
            System.out.println("Outer => " + itemA);
        }
    }

Inner => a1
Inner => a2
Outer => a1
Inner => a1
Inner => a2
Outer => a2

Refereed this for examples

A: Iterable<T> is an interface, so there is no default implementation.
In ArrayList<T> for instance, the iterator<E> method will return a new instance of the nested class Itr each invocation:
public Iterator<E> iterator() {
    return new Itr();
}

A: anIterable.iterator() should return a new iterator and in that case the nested enhanced for loops will work as expected. All standard implementations of Iterable return a new Iterator when iterator() is called.
If some bad implementation of the Iterable interface doesn't return a new Iterator in consecutive calls to iterator(), the nested enhanced for loops will break.
BTW, the Javadoc of Iterable's iterator() method doesn't require that it return a new Iterator.

A: Depends how iterable interface is implemented. Generally the collection frameworl classes returns new instance.

A: You may iterate the same collection in parallel, but you cannot modify it. So your code is completely correct: the new iterator would be returned each time.