text:
Q: I am getting Visualforce error like Unknown property 'wrapp' referenced in deletewrap I have written wrapper class and created visualforce page but i am getting error
"Unknown property 'wrapp' referenced in deletewrap".
public class DeletingCheckedRowsController{
 public list<WrapperClass>wrapp{get;set;}
 public Boolean bool{get;set;}
  public DeletingCheckedRowsController(){
    wrapp=new list<WrapperClass>();
    List<Account> acc=[select id, name from Account Limit 10];
    for(Account a: acc){
      wrapp.add(new WrapperClass(a));
     }
  }

public class WrapperClass{
  public Boolean checked{get;set;}
  public Account a{get;set;}
    public WrapperClass(Account acc, Boolean b){
       checked=b;
       a=acc;
     }
   }

public void del(){
List<Account>accToDel=new List<Account>();
for(WrapperClass w: wrapp){
  if(w.checked){
  accToDel.add(w.acc);

  }
}
 if(accToDel.size()>0){
     delete accToDel;
  }

  }
}

Visualforce code

<apex:page>
 <apex:form>
  <apex:pageBlock>
   <apex:pageBlockButtons>
    <apex:commandButton value="delete" action="{!del}"/>
  </apex:pageBlockButtons>
  <apex:pageBlockTable value="{!wrapp}" var="w">
     <apex:inputCheckbox value="{!w.checked}"/>
      <apex:column value="{!w.a.name}"/>
    </apex:pageBlockTable>
     </apex:pageBlock>
   </apex:form>
 </apex:page>

A: You are missing the controller attribute on apex:page. Add controller="DeletingCheckedRowsController" as you didn't add the controller you can't access it's property.

A: You're supposed to tell the VF Page where you have implemented all the logic. And as you have implemented the functionality in above provided Custom Controller.
So here, add an attribute in <apex:page> tag like:<apex:page controller="your_ControllerClass_Name">
Refer this link for more info: Controller Docs from Salesforce


text:
Q: CruiseControl.Net and NUnit - tests finish, but task doesn't? I've got a CruiseControl.Net setup using Nant to clean the previous logs, and then it kicks off a msbuild of a VS project, finally running nunit-console to execute the tests.
It seems to build for a few seconds (fine) and then hops on to running the 600 tests, which takes about a minute.  However even though the log files are there, it sits there doing 'nothing' for 10 minutes, at which point the built times out and the process exits.  The CruiseControl.NET webpage then shows the result as failed, with an exception:
ThoughtWorks.CruiseControl.Core.Tasks.BuilderException: Command Line Build timed out (after 600 seconds)
   at ThoughtWorks.CruiseControl.Core.Tasks.ExecutableTask.Execute(IIntegrationResult result)
   at ThoughtWorks.CruiseControl.Core.Tasks.TaskBase.Run(IIntegrationResult result)
   at ThoughtWorks.CruiseControl.Core.Project.RunTask(ITask task, IIntegrationResult result, Boolean isPublisher)
   at ThoughtWorks.CruiseControl.Core.Project.RunTasks(IIntegrationResult result, IList tasksToRun, Dictionary`2 parameterValues)
   at ThoughtWorks.CruiseControl.Core.Project.Run(IIntegrationResult result)
   at ThoughtWorks.CruiseControl.Core.IntegrationRunner.Build(IIntegrationResult result)
   at ThoughtWorks.CruiseControl.Core.IntegrationRunner.Integrate(IntegrationRequest request) BaseDirectory: , Executable: C:\Program Files\NUnit 2.5.8\bin\net-2.0\nunit-console.exe

The ccnet.config script is below.  I've tried changing the timeout to 3 minutes just in case that was something to do with it, but even if that did work (it didn't) it's a dodgy hack, as by rights when the tests are finished running, they should exit gracefully!
I've run the command at the commandline and confirmed it only takes about a minute to run.  Any theories?
<cruisecontrol xmlns:cb="urn:ccnet.config.builder">

    <project name="CodeTests">
      <workingDirectory>C:\Source\Wholesale\Comp.EventControl.TestingFramework\</workingDirectory>
      <artifactDirectory>C:\Source\Wholesale\Comp.EventControl.TestingFramework\</artifactDirectory>

    <prebuild>
    <!-- clean nunit output to avoid CCNET reporting
           about previous build tests if current build fails -->
      <nant>
        <executable>C:\Nant\bin\nant.exe
        </executable>
        <baseDirectory>C:\Source\Wholesale\Comp.EventControl.TestingFramework</baseDirectory>
        <nologo>false</nologo>
        <buildFile>nant.build</buildFile>
        <targetList>
          <target>cleanNunit</target>
        </targetList>
      </nant>
    </prebuild>

    <tasks>
        <msbuild>
            <executable>C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe
            </executable>
            <workingDirectory>C:\Source\Wholesale\Comp.EventControl.TestingFramework\CodeReboot
            </workingDirectory>
        <projectFile>CodeReboot.sln</projectFile >
            <buildArgs>/noconsolelogger
            /v:quiet
            /noconlog
            /p:Configuration=Debug
            /p:ReferencePath="C:\Program Files\NUnit 2.5.8\bin;C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"
            /p:AdditionalReferencePath="C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"
            </buildArgs>
            <targets>ReBuild</targets >
            <timeout>180</timeout >
            <logger>c:\Program Files\CruiseControl.NET\server\Rodemeyer.MsBuildToCCNet.dll</logger>

        </msbuild>
        <exec>
            <executable>C:\Program Files\NUnit 2.5.8\bin\net-2.0\nunit-console.exe
            </executable >
            <buildArgs>/xml:C:\Source\Wholesale\Comp.EventControl.TestingFramework\nunit-results.xml
            /nologo C:\Source\Wholesale\Comp.EventControl.TestingFramework\CodeReboot\CodeReboot\bin\Debug\CodeReboot.dll
            </buildArgs>
        </exec>
    </tasks>
    <publishers>
      <merge>
        <files>
          <file>C:\Source\Wholesale\Comp.EventControl.TestingFramework\nunit-results.xml
          </file>
        </files>
      </merge>
      <xmllogger />
      <statistics />
      <artifactcleanup cleanUpMethod="KeepLastXBuilds"
        cleanUpValue="20" />
    </publishers>

    </project>
</cruisecontrol>

A: What version of nunit are you using? There were some problems in the 2.5.7/2.5.8 version that causes nunit-agent to hang at the end of a test. I had this problem and reverted back to an older version of nunit and the hang problem went away. In the release notes for 2.5.9 they show that "602761 nunit-agent hangs after tests complete" has been fixed. I have not upgraded to 2.5.9 yet but that may fix your problem.

A: The first thing you should do try and replicate the problem locally.  Do your tests run properly and exit cleanly?  Run them locally and see if the nunit process hangs around.
If your tests run fine locally, try and figure out which test the build server is stalling on or whether it is completing all of the tests.  If your build scripts cannot be run locally, it's a bit harder to diagnose.
Back in the day when our tests were riddled with threaded code, it was nearly always the case that a test (or the code under test) was creating threads and then failing to shut them down, causing NUnit to hang around.  Threading issues are irritating because they're non-deterministic may only be visible when run on machines with more cores (like .. build servers).
If you have tests with threading / external dependencies, I'd try disabling those first (the fact that 600 tests takes a minute to run indicates that external dependencies and/or threading is involved, as a unit test usually takes ~1ms to run).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot resolve symbol 'R' Запускаю проект - все работает отлично. Меняю текст в strings, запускаю чтобы проверить - выдает ошибку:
Error:Execution failed for task ':app:processDebugResources'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'E:\AutoDeep\Android Studio\Android\sdk\build-tools\23.0.1\aapt.exe'' finished with non-zero exit value 1

И подчеркивает R при наведении высвечивает -> Cannot resolve symbol 'R'.
Build -> Clean Project не помогло. После очистки перезапуск тоже не помог. Запускаю проект до изменения текста в string - работает. Меняю текст -> перестает работать. Возвращаю текст в проект, который не работает - не помогает. Что это такое?
File->InvalidateCahces - также не помог.

A: Tools → Android → Sync Project with Gradle Files


text:
Q: Is there a way to mock a web view in iOS by XCUITest? There is a new webview implemented in our iOS app and I was wondering is there anyway I can mock it via XCUITest?
I already has mocking done for the native view but not the web one so I was wondering if someone did this before?


text:
Q: Synergy server not receiving connections I'm using synergy with two Windows computers (both Win7 64-bit). The server's debug messages state that it doesn't receive any connections. The client connects to the server (right IP and port) and seemingly everything is fine from the client's side.
The config file of the server:
section: screens
    huldra:
    switchCorners = none
        switchCornerSize = 0
    Stahlu:
        switchCorners = none
        switchCornerSize = 0
end
section: links
    huldra:
        left = Stahlu
    Stahlu:
        right = huldra
end
section: aliases
    Stahlu:
        main
end
section: options
    heartbeat = 2000
    screenSaverSync = false
    switchDelay = 250
end


text:
Q: Using Linq to return each item only once Here's what I'm trying to do. Have a use right a sequence of numbers delimited by spaces. After I save those numbers, I want to return a string of all the numbers only once, even if a number has appeared n number of times in the sequence.
string[] tempNumbers = textValue.Split(' ');

IEnumerable<string> distinctNumbers = tempNumbers.Where(value => value.Distinct());

I'm getting this error:
Error   2   Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<char>' to 'bool' c:\users\sergio\documents\visual studio 2010\Projects\LinqPlayground\LinqPlayground\SetSemanticsExample.cs  67  75  LinqPlayground

A: The extension method IEnumerable.Distinct is not a predicate function. It operates on an IEnumerable<T> and returns a new IEnumerable<T> where each element appears only once.
To fix your code just do this instead:
IEnumerable<string> distinctNumbers = tempNumbers.Distinct();

I want to return a string of all the numbers only once

If you want the result as a single space-separated string then in addition to the above you will also need to call string.Join:
string result = string.Join(" ", distinctNumbers.ToArray());
txtResult.Text = result;

A: Where(value => value.Distinct()) will take each string from the tempNumbers to evaluate. Besides, the string is a  collection of chars. That's why you can apply the Distinct() to the

value.

Moreover the result of Distinct() extension method is and IEnumerable<T>, where T is char here. Hence the whole operation causes the exception.
In order to get distinct numbers , you can use the query
var distinctNumbers = (from elem in tempNumbers
                      select elem).Distinct();

Cheers


text:
Q: Android studio - "some errors occurred while accessing svn working copy database" In our Android studio environment we get the "some errors occurred while accessing svn working copy database" error.
This is an ubuntu machine.
We can commit/update just fine, but this error keeps showing.
Is there anyway to get a more detailed error? I would like to find out if some folders cause this error specifically?
I understand some other users asked similar questions and resolved by installing SVN, but our SVN appears to be working just fine.

A: The issue was resolved by reinstalling Ubuntu in English instead of Turkish.


text:
Q: Writing a double type value to a text file The below code is writing unreadable characters to the text file:
int main ()
{
    ofstream myfile ("example.txt");

    if (myfile.is_open())
    {
        double value       = 11.23444556;
        char   *conversion = (char *)&value;
        strcat (conversion, "\0");

        myfile.write (conversion, strlen (conversion));
        myfile.close();
    }

    return 0;
}

I want to see the actual number written in the file :( Hints please.
EDIT
Seeing the answers below, I modified the code as:
int main ()
{
    ofstream myfile ("example.txt");

    if (myfile.is_open())
    {
        double value       = 11.23444556;

        myfile << value;
        myfile.close();
    }

    return 0;
}

This produces the putput: 11.2344 while the actual number is 11.23444556. I want the complete number.
Editing the post to notify everyone:
The unreadable characters are due to ofstream's write function:

This is an unformatted output function

This quote is from: http://www.cplusplus.com/reference/iostream/ostream/write/

A: It's easier here to use the stream operators:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;

int main ()
{
    ofstream myfile ("example.txt");

    if (myfile.is_open())
    {
        double value       = 11.23444556;

        myfile << value;
        myfile.close();
    }

    return 0;
}

gives you what you want.

A: Why don't you simply do this (updated answer after the edit in the question):
 #include <iomanip>

 myfile << std::fixed << std::setprecision(8) << value;
 myfile.close();

Now, you can see the actual number written in the file.
See the documentation of std::setprecision. Note: you have to include the <iomanip> header file.

A: Others suggested better ways but if you really want to do it the pointer way there should be casts to convert char* to double * and vice versa
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;

int main ()
{
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    double value       = 11.23444556;
    char     *conversion = reinterpret_cast<char *>(&value);
    strcat (conversion, "\0");
    //myfile.write (*conversion, strlen (conversion));
    myfile << *(reinterpret_cast<double *>(conversion));
    myfile.close();
  }
  return 0;
}

A: You can write the value to file like this:
myfile << value;

Using the adress of value as parameter strcat corrupts your stack, since strcat expects a 0-terminated c-string as first argument (and actually allocated space).


text:
Q: How to work with multiple tabs using react-idle-timer I am having a react Application, where I need to display a modal with two buttons (Logout and Continue Session) when the user goes idle, It was actually working fine with the IdleTimer component from the react-idle-timer.
But If I open the Application in multiple tabs, and click on Continue session in one tab, the other tabs are not receiving that, The sample code that I have used is,
<IdleTimer
        timeout={1000}
        onIdle={// Opens a modal with two buttons Logout and Continue Session}
      ></IdleTimer>

Is it possible to use the crossTab prop? but I am not sure how to implement them.
How can I achieve my requirement to work with multiple tabs so that if I click on continue session all the tabs need to close the modal.
The version I am using is - react-idle-timer (4.6.4)
Could someone please help with this to achieve my requirement? Thanks in advance!!

A: You can use the Cross Tab Messaging feature from the documentation:
  // Action dispatcher (redux)
  const dispatch = useDispatch()

  // Message handler
  const onMessage = data => {
    switch (data.action) {
      case 'LOGOUT_USER':
        dispatch(logoutAction())
        break
      // More actions
      default:
        // no op
    }
  }

  // IdleTimer instance
  const { message } = useIdleTimer({ onMessage })

  // Logout button click
  const onLogoutClick = () => {
    // Tell all tabs to log the user out.
    // Passing true as a second parameter will
    // also emit the event in this tab.
    message({ action: 'LOGOUT_USER' }, true)
  }

See the documentation for v5, here.


text:
Q: Stripe Payment Keyboard Automatically Popping Open I'm working on an iOS app that uses Stripe's payment system. The problem is, the code I have below causes the stripe's keyboard for credit card information entry to automatically open:
// PaymentViewController.m

- (void)viewDidLoad
{
  [super viewDidLoad];
  PTKView *view = [[PTKView alloc] initWithFrame:CGRectMake(15,20,290,55)];
  self.paymentView = view;
  self.paymentView.delegate = self;
  [self.view addSubview:self.paymentView];
}

But I want the keyboard to be displayed after the user selects the PTKView (the grey bar like thing provided by Stripe) Right now, as soon as the view loads, the keyboard to enter credit card details is already open but I only want the bar to appear, so the user can tap that to open the keyboard.

A: Yes you have to stop the keyboard apperance, go to the PTKView.m fie there is one function "stateCardNumber" and comment the code,
[self.cardNumberField becomeFirstResponder];

that will stop the automatic keyboard open.

A: In ViewWillAppear: Find the current first responder by using below mentioned category over UIResponder and resignFirstResponder.
    @interface UIResponder (FirstResponder)
+(id)currentFirstResponder ;
-(NSString*) firstRespondersViewController;
@end

@implementation UIResponder (FirstResponder)
static __weak id currentFirstResponder;

+(id)currentFirstResponder {
    currentFirstResponder = nil;
    [[UIApplication sharedApplication] sendAction:@selector(findFirstResponder:) to:nil from:nil forEvent:nil];
    return currentFirstResponder;
}

-(void)findFirstResponder:(id)sender {
    currentFirstResponder = self;
}

-(NSString*) firstRespondersViewController{
    UIResponder *responder = self; \
    while ([responder isKindOfClass:[UIView class]]) \
        responder = [responder nextResponder]; \
    (UIViewController *)responder;
    NSLog(@"class is %@", NSStringFromClass([responder class]));
    return NSStringFromClass([responder class]);
}
@end

Hope this helps.


text:
Q: Bash: Scriptception, create scripts inside a script How would i create a script that creates two separate scripts with something inside them?
i tried this but failed
#!/bin/bash
cat > scriptMaster.sh << EOF

   cat > script1.sh << EOF
   #code
   EOF

   cat > script2.sh << EOF
   #code
   EOF

EOF

A: You must put the EOF marker at the left margin, unless you prefix it with -, which allows it to be indented with TAB characters, but not spaces. You'll need to use different EOF markers for the outer and inner here-docs; otherwise, the marker will terminate the outer one as soon as it's seen (since the inner here-docs aren't actually executed until you run the scriptMaster.sh script).
#!/bin/bash
cat >scriptMaster.sh <<EOF
#!/bin/bash
cat > script1.sh <<EOF1
#!/bin/bash
#code
EOF1
chmod +x script1.sh # Make the script executable

cat >script2.sh <<EOF2
#!/bin/bash
#code
EOF2
chmod +x script2.sh

EOF
chmod +x scriptMaster.sh

#Now run the scripts:
./scriptMaster.sh
./script1.sh
./script2.sh

A: You have to really execute the code inside the first EOF, this works for me:
#!/bin/bash
cat > scriptMaster.sh << EOF

`cat > script1.sh << EOF2
#code
EOF2

cat > script2.sh << EOF2
#code
EOF2`

EOF

A: The problem with your code is that it's indented. Rather than messing around with <<- and tabs to try to strip the indenting, just don't indent any of it and use different end tokens in your embedded scripts so they don't accidentally terminate your master here doc:
#!/bin/bash
cat > scriptMaster.sh << ENDMASTER

cat > script1.sh << EOF
#code
EOF

cat > script2.sh << EOF
#code
EOF

ENDMASTER

A: Here is some old-school stuff (the concepts are the same as above):
echo "=== 001. Create script-01.sh"
sed 's/.//' >script-01.sh <<'//GO.SYSIN DD script-01.sh'
-echo This
-echo is a content
-echo of 'script-01.sh'
//GO.SYSIN DD script-01.sh
chmod +x script-01.sh

echo "=== 002. Create script-02.sh"
sed 's/.//' >script-02.sh <<'//GO.SYSIN DD script-02.sh'
-echo This is a content
-echo of 'script-02.sh'
//GO.SYSIN DD script-02.sh
chmod +x script-02.sh

echo "=== 999. EOF"


text:
Q: add_filter not working for returning logged in user I have a snippet to detect whether a user is logged in - if yes, then "My account" and "Logout" links show in top menu, if no, "Login" link shows.
It works fine, until a user logs in with "remember me" option checked, leaves my website without logging out and comes back.
Then "Login" shows on top menu, instead of "My account" and "Logout". It doesn't behave normally, after clicking it, user is not redirected to login page, but instead "My account" and "Logout" instantly show up. Also adding anything to the cart makes "My account" and "Logout" show up.
I checked via var_dump() that is_user_logged_(in) doesn't return anything until I click "Login" or add something to the cart. I tried changing priority to 1 or 9999 and it didn't help.
// Add login & logout buttons to secondary menu.
add_filter( 'wp_nav_menu_items', 'add_loginout_link', 10, 2 );
function add_loginout_link( $items, $args ) {
  if (is_user_logged_in() && $args->theme_location == 'secondary') {
   $items .= '
My account

Logout
';
  }
  elseif (!is_user_logged_in() && $args->theme_location == 'secondary') {
   $items .= '
Login
';
  }
  return $items;
}

A: It should work like that.
2 things that came to my mind.
Plugin messing up with it. Try disabling all plugins and switching to default theme. If its still issue, workaround is to go without filter by creatign 2 menus and showing correct one depending on the if(is_user_logged_in()).... that one should work 100%.


text:
Q: Selecting data in two tables I have two tables: who contains these fields:

gmdc_employee
file_id     company_id  employee_id     employee_name   file_description    file_date      file_name              folder_access        upload_date  confirmation
    1        20111253     20080407         Mariel             file1         2000-01-01  agent_masterlist.xls    documents/20111253/     2011-05-16    Pending
    2        20112301     20864125         Keisha             file2         2000-02-01  auto_lapsed.xls         documents/20112301/     2011-05-16    Pending
   11        20111253     65513215          Rovy              file15        2008-01-01  attendancesheet.xls     documents/20111253/     2011-06-01    Pending

gmdc_user
company_id  company_name    employee_id     employee_name   username    password_clear           password_hash              login_number         last_login
 25014462       NCST          20132248          Danica      ncst            ncst         c7b080d11d6766a27c02591f74b2ea4d        3           2011-05-23 11:25:03
 20112301       EAC           20113318          Emilio      eac             each         933dd8674c563081260867dfa95b5e74        4           2011-05-23 11:52:58
 20111253       DLSU          20080040          John        dlsu            dasma        3c26c824914144d0addf0ceb850ed78a        15          2011-06-01 10:45:32

This is the query I used when I first need to get items in my gmdc_employee tables: the '%$search%' is my name for my search button and '$listname%' is my name for my panel tabs(A-Z list):
select *
   from gmdc_employee
   where employee_name like '%$search%'
     AND employee_name like '$listname%'

The problem is in my search button. Before, my search button will only search the employee_name (my code above is the one i used which is working). But the conditions changed unfortunately :( I was asked that aside from searching the employee_name(found in gmdc_employee table) the user may also search for employee_id (which is found in the gmdc_employee) and company_name (which is found in the gmdc_user), but I don't know how to do that :( I haven't learnt from school yet about the joining of two tables, although I learned a way to do that and tried it. Unfortunately it produced wrong results. So may I give an example?
If the user searched for the company name DLSU, the output should look like this:
employee_id     employee_name   title   file_date    status    confirmation
  20080407        Mariel        file1   2000-01-01   Pending     delete //delete is a link
  65513215         Rovy         file15  2008-01-01   Pending     delete

as to what you see,it searches and echoes files under the company name "DLSU" I hope someone could help me here :( I already tried everything but nothing works the way it was suppose to.
This is what I tried to used that produces wrong outputs. :( it echoed all data needed where and did not look in the condition that only the searched company_name info should output:
select
      a.employee_id,
      a.employee_name,
      a.file_description,
      a.file_date,
      a.confirmation
   from
      gmdc_employee  AS a
         JOIN gmdc_user AS b
   WHERE
          a.employee_name like'%'
      AND a.employee_id like '%'
      AND b.company_name like 'DLSU'

A: A query which should return the data you provided in the Question is:
SELECT `e`.`employee_id` ,
       `e`.`employee_name` ,
       `e`.`title` ,
       `e`.`file_date` ,
       `e`.`status` ,
       `e`.`confirmation` AS "status"
FROM `gmdc_employee` `e`
  JOIN `gmdc_user` `u` ON ( `u`.`company_id` = `e`.`company_id` )
WHERE `u`.`company_name` LIKE "DLSU"

A: I've formatted your queries, and it looks like you were very close... you just didn't have the ON condition for your join
select
      a.employee_id,
      a.employee_name,
      a.file_description,
      a.file_date,
      a.confirmation
   from
      gmdc_employee  AS a
         JOIN gmdc_user AS b
            on a.employee_id = b.employee_id
   WHERE
          ( a.employee_name like'%$search%'
          OR b.employee_name like '%$search%' )
      AND b.company_name like 'DLSU'

I'm not really sure this is the proper join is by the employee ID or not... you don't show any instances of same "employee" vs "user".  With no "ON" condition, its basically going to create a Cartesian join otherwise (or outright error out)...  You may also want to logically OR if you are looking for multiple criteria... such as the name found in one field OR the other... if found in both, no problem...


text:
Q: rails mongodb where in array i'm trying to get positive_power_values where it's meter_id in array

1.9.3p194 :100 > ppv = PositivePowerValue.first

  PositivePowerValue _id: 518dfd25a81fc61ece8d3d23, _type: nil, deleted_at: nil, created_at: "2013-05-11 19:04:54 +0800", updated_at: nil, positive_active_energy_power_indication: "100.00", positive_reactive_power_indication: "50", use_flag: "true", meter_id: "4f71181b6e92fe054b000006"
  1.9.3p194 :101 > PositivePowerValue.where(:meter_id.in => ["4f71181b6e92fe054b000006"]).count
   => 0

i wender why is 0?
i need to get positive_power_values where meter_id in array!

A: Are you using mongoid ?
The proper syntax would be :
PositivePowerValue.in(:meter_id => ["4f71181b6e92fe054b000006"])


text:
Q: Error installing Pycharm 4.0.4 Pro in Fedora 21 I am very new to using a linux system, I am getting the ERROR while installing PyCharm but unable to sort it out. If possible please help.
[ace139@localhost pycharm-4.0.4]$ cd bin
[ace139@localhost bin]$ ls
fsnotifier       inspect.sh              log.xml              pycharm.sh
fsnotifier64     libyjpagent-linux64.so  pycharm64.vmoptions  pycharm.vmoptions
idea.properties  libyjpagent-linux.so    pycharm.png
[ace139@localhost bin]$ ./pycharm.sh
OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=350m; support was removed in 8.0
[    200]  ERROR - nse.impl.GeneralLicenseManager - No valid license found
java.lang.Throwable
    at com.intellij.openapi.diagnostic.Logger.error(Logger.java:115)
    at com.intellij.ide.a.g.bb.a(bb.java:107)
    at com.intellij.idea.MainImpl$1.start(MainImpl.java:47)
    at com.intellij.idea.StartupUtil.prepareAndStart(StartupUtil.java:105)
    at com.intellij.idea.MainImpl.start(MainImpl.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.ide.plugins.PluginManager$2.run(PluginManager.java:91)
    at java.lang.Thread.run(Thread.java:745)
[    201]  ERROR - nse.impl.GeneralLicenseManager - PyCharm 4.0.4  Build #PY-139.1001
[    201]  ERROR - nse.impl.GeneralLicenseManager - JDK: 1.8.0_31
[    202]  ERROR - nse.impl.GeneralLicenseManager - VM: OpenJDK 64-Bit Server VM
[    202]  ERROR - nse.impl.GeneralLicenseManager - Vendor: Oracle Corporation
[    202]  ERROR - nse.impl.GeneralLicenseManager - OS: Linux

A: There is an article dealing with this problem. http://oonlab.com/fix-install-pycharm-fedora-21.onto/
TLDR:
sudo dnf install java-1.8.0-openjdk

Tested by myself on Fedora 21 and PyCharm 4.

A: Try doing a backup of ~./.PyCharm40 and remove that directory.

A: I was having same issue, try
yum install java-1.7.0-openjdk-devel

this will fix your problem


text:
Q: Can't find Word 2010 Document template in Visual Studio I have VS 2013 installed and Microsoft Office 2010 and I want to create a new project using Word 2010 document as my template, but I don't see the option for this version.  Only Word 2013 Document template is available, but since I don't have it installed I get an error Cannot create project because the application associated with this project type is not installed on this computer.  You must install the Microsoft Office application that is associated with this project type.  Can I use a 2010 Word template, if so how?

A: You can use the very helpful answer in the below link:
VSTO Tools: Office 2010 to 2013 upgrade
I think you can try only one of the points mentioned in the answer:

Under the
  Project\ProjectExtensions\VisualStudio\FlavorProperties\ProjectProperties
  element find the "OfficeVersion" attribute/value pair and remove it
  (so the attribute that reads OfficeVersion="14.0" -- delete that). --
  Leave all other 14.0s intact, if anything got changed to 15.0,
  downgrade it back to 14.0 (and again, if it's a reference, set
  SpecificVersion to false). -- Do not worry about changing any GUIDs,
  just leave them as they are!

Let me know if that works for you.


text:
Q: Objective-C, protocols and subclasses Let's say that I have the following protocols defined:
// basic protocol for an User Interface object:
@protocol UIObjectProtocol <NSObject>
@property (assign) BOOL touchable;
@end

// basic protocol for an User Interface object that is held by a holder object:
@protocol UIHeldObjectProtocol <UIObjectProtocol>
@property (readonly) id holder;
@end

And the following class hierarchy:
// base class for an User Interface object, which synthesizes the touchable property
@interface UIObject : NSObject <UIObjectProtocol> {
   BOOL _touchable;
}
@end

@implementation UIObject
@synthesize touchable=_touchable;
@end

At this point, everything is OK. Then I create a UIObject subclass named UIPlayingCard. Inherently, UIPlayingCard conforms to the UIObjectProtocol since it's superclass does it too.
Now suppose I want UIPlayingCard to conform to UIHeldObjectProtocol, so I do the following:
@interface UIPlayingCard : UIObject <UIHeldObjectProtocol> {
}
@end

@implementation UIPlayingCard
-(id)holder { return Nil; }
@end

Note that the UIPlayingCard conforms to UIHeldObjectProtocol, which transitively conforms to UIObjectProtocol. However I'm getting compiler warnings in the UIPlayingCard such that:

warning: property 'touchable' requires
  method '-touchable' to be defined -
  use @synthesize, @dynamic or provide a
  method implementation

which means that the UIPlayingCard superclass conformance to the UIObjectProtocol wasn't inherited (maybe because the @synthesize directive was declared in the UIObject implementation scope).
Am I obligated to re-declare the @synthesize directive in the UIPlayingCard implementation ?
@implementation UIPlayingCard
@synthesize touchable=_touchable; // _touchable now must be a protected attribute
-(id)holder { return Nil; }
@end

Or there's another way to get rid of the compiler warning? Would it be the result of bad design?
Thanks in advance,

A: You comment that _touchable would then have to be protected, but you did not include an @private compiler directive, so _touchable is already protected.
Clang does not seem to give this warning in this case, so the most straightforward solution:

*

*Change your compiler from GCC to Clang.

This will have plenty of side-benefits, as well, including much more intelligible error and warning messages.
It is a bug that GCC complains about this. The implementation is in fact inherited, as you can verify with a simple main function exercising UIPlayingCard's touchable property. So, your second solution:

*

*Ignore the warning as bogus. If none of your tests are failing, what do you care, anyway?

A:
Am I obligated to re-declare the @synthesize directive in the UIPlayingCard implementation

Although I don't see from your example, why you are doing what you are doing:
No, you don't need to re-implement methods that are already implemented in your parent class.
If the compiler warns about these methods not being present, then that is a bug:
As The Objective C Programming Language states...

When a class adopts a protocol, it must implement the required methods the protocol declares, as mentioned earlier. In addition, it must conform to any protocols the adopted protocol incorporates. If an incorporated protocol incorporates still other protocols, the class must also conform to them. A class can conform to an incorporated protocol by either:

*

*Implementing the methods the protocol declares, or

*Inheriting from a class that adopts the protocol and implements the methods.

A: I'll just throw in one other way to silence the warning: use @dynamic, and the compiler will assume that the implementation will be provided in some other way than in a declaration in the class's implementation (in this case, it's provided by the superclass).

A: A Protocol is like a contract.  What you are saying is that UIPlayingCard must implement holder and touchable.
When the compiler compiles UIPlaying card, it doesn't see anywhere that @property (nonatomic) BOOL touchable; is defined.
you can't add synthesize to playingCard since playingCard doesn't have the touchable ivar.
Change:
@protocol UIHeldObjectProtocol <UIObjectProtocol>

to
@protocol UIHeldObjectProtocol <NSObject>

Since UIPlayingCard inherits from UIObject, the protocols don't need to inherit from each other.


text:
Q: how to copy a vmware template to a given vcenter using pyVmomi module I am familiar with cloning a VM from template and copying the template within the same vcenter, but when i try to copy it to a specified vcenter i am unable to achieve this.. I am not sure whether this is possible or not using pyVmomi module
I am new to pyVmomi module, Below is my code, any help or suggestions would be greatly appreciated.
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
import ssl,time,argparse,sys

def get_obj(content, vimtype, name):
    obj = None
    container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
    for c in container.view:
        if c.name == name:
            obj = c
            break
    return obj

def main():
   parser = argparse.ArgumentParser()
   parser.add_argument('-s', '--source',dest='source', help="source vcenter of the template")
   parser.add_argument('-t', '--target',dest='target',default=False, help="target vcenter to which the template should be copied")
   parser.add_argument('-tmp', '--template',dest='template',default=False, help="the template passed by the user")
   args = parser.parse_args()
   source = args.source
   target = args.target
   template = args.template
   if source == None or target == None or template == None:
      print("please provide the source/target/template, Exiting..")
      sys.exit(1)

   # Connecting to source vcenter
   username='username'
   password='password'
   si = None
   context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
   context.verify_mode = ssl.CERT_NONE
   si = SmartConnect(host=source,user=username,pwd=password,sslContext=context)
   content = si.content

   #get template object
   template_vm = get_obj(content, [vim.VirtualMachine], template)
   print(template_vm)

   # Connecting to target vcenter
   # Disconnect(si)
   si2 = SmartConnect(host=target,user=username,pwd=password,sslContext=context)
   content2 = si2.content

   datacenter = get_obj(content2, [vim.Datacenter], 'mydatacenter')
   destfolder = datacenter.vmFolder
   datastore = get_obj(content2, [vim.Datastore], 'mydatastore')

   # Relocation spec
   relospec = vim.vm.RelocateSpec()
   relospec.datastore = datastore

   clonespec = vim.vm.CloneSpec()
   clonespec.location = relospec
   clonespec.template = True

   task = template_vm.Clone(folder=destfolder, name='template_new', spec=clonespec)

if __name__== "__main__":
   main()

When i switch connection to a target vcenter i get the below error
Traceback (most recent call last):
  File "clone_template2.py", line 74, in <module>
    main()
  File "clone_template2.py", line 70, in main
    task = template_vm.Clone(folder=destfolder, name='template_new', spec=clonespec)
  File "/home/akshay/.local/lib/python3.8/site-packages/pyVmomi/VmomiSupport.py", line 706, in <lambda>
    self.f(*(self.args + (obj,) + args), **kwargs)
  File "/home/akshay/.local/lib/python3.8/site-packages/pyVmomi/VmomiSupport.py", line 512, in _InvokeMethod
    return self._stub.InvokeMethod(self, info, args)
  File "/home/akshay/.local/lib/python3.8/site-packages/pyVmomi/SoapAdapter.py", line 1397, in InvokeMethod
    raise obj # pylint: disable-msg=E0702
pyVmomi.VmomiSupport.ManagedObjectNotFound: (vmodl.fault.ManagedObjectNotFound) {
   dynamicType = <unset>,
   dynamicProperty = (vmodl.DynamicProperty) [],
   msg = "The object 'vim.Datastore:datastore-360' has already been deleted or has not been completely created",
   faultCause = <unset>,
   faultMessage = (vmodl.LocalizableMessage) [],
   obj = 'vim.Datastore:datastore-360'
}


text:
Q: CancellationTokenSource not behaving as expected what's expected in this case, is that if the user cancels the task by hitting enter, the other task hooked by ContinueWith will run, but it's not the case, as per an AggregateException keeps thrown despite the explicit handling in the ContinueWith which is apparently not being executed.
any clarification on the below please?
class Program
{
    static void Main(string[] args)
    {
        CancellationTokenSource tokensource = new CancellationTokenSource();
        CancellationToken token = tokensource.Token;

        Task task = Task.Run(() =>
        {
            while (!token.IsCancellationRequested)
            {
                Console.Write("*");
                Thread.Sleep(1000);
            }
        }, token).ContinueWith((t) =>
        {
            t.Exception.Handle((e) => true);
            Console.WriteLine("You have canceled the task");
        }, TaskContinuationOptions.OnlyOnCanceled);

        Console.WriteLine("Press any key to cancel");
        Console.ReadLine();
        tokensource.Cancel();
        task.Wait();
    }
}

A: Let's start with a few facts:

*

*When you pass a CancellationToken as a parameter for Task.Run it only has an effect if it's cancelled before the task started running. If the task is already running it will not be canceled.

*To get a task canceled after it has started running, you need to use CancellationToken.ThrowIfCancellationRequested, not CancellationToken.IsCancellationRequested.

*If a task is canceled, its Exception property doesn't hold any exceptions and is null.

*If a continuation task does not run for some reason, that means it was canceled.

*A task contains exceptions from itself + all its child tasks (hence, AggregateException).

So this is what happens in your code:
The task starts running, because the token is not canceled. It will run until the token gets canceled. After it will end the continuation will not run because it only runs when the preceding task is canceled, and it hasn't been. When you Wait the task it will throw an AggregateException with a TaskCanceledException because the continuation was canceled (if you would remove that continuation the exception will go away).
Solution:
You need to fix the task so it would actually be canceled, and remove (or null check) the exception handling because there is no exception:
var task = Task.Run(new Action(() =>
{
    while (true)
    {
        token.ThrowIfCancellationRequested();
        Console.Write("*");
        Thread.Sleep(1000);
    }
}), token).ContinueWith(
    t => Console.WriteLine("You have canceled the task"),
    TaskContinuationOptions.OnlyOnCanceled);

A: If you pass the token as the second parameter, the task won't continue on nicely because it's really been cancelled. Instead it throws an OperationCanceledException which gets wrapped in an AggregateException. This is entirely expected. Now, if you did NOT pass the token to the task constructor then you'd see the behaviour you'd expect because because you'd only be using the token as a flag for exiting the while loop. In that case you're not really cancelling the task, you're exiting the while loop and completing the task normally.


text:
Q: unzip zip files into multiple folders with powershell I have 5 zip files and 5 folders respectively.
Files are: FranceData.zip, USAdata.zip, GermanData.zip, Italydata.zip and DanemarkData.zip. Folders are: FranceFolder, USAFolder, GermanFolder, ItalyFolder and DanemarkFolder. I would like to know how would I unzip these files into their respective folders using Array in Powershell. I am knew to Powershell and need help. Thank you

A: This can be done using the Expand-Archive cmdlet, which is available in PowerShell 5 and above. (PowerShell's version can be checked via the $PSVersionTable variable.)
To extract a zip file to a specific folder the following syntax is used:
Expand-Archive -Path 'ZipFile.zip' -DestinationPath 'ZipFolder'

or
Expand-Archive -LiteralPath 'ZipFile.zip' -DestinationPath 'ZipFolder'

If the -Path parameter is used, PowerShell will recognise characters such as *, ?, [, ], as wildcards, which can cause unexpected behaviour for file-paths that contain square-brackets.
If the -LiteralPath parameter is used, PowerShell will not treat any characters as wildcard characters.

Assuming all your zip files and folders follow the same naming pattern you could use an array like so:
$Countries = @(
    'France',
    'USA',
    'German'
    'Italy',
    'Danemark'
)

foreach ($Country in $Countries)
{
    $ZipFilePath = $Country + 'Data.zip'
    $DestinationPath = $Country + 'Folder'

    Expand-Archive -LiteralPath $ZipFilePath -DestinationPath $DestinationPath
}

If your files and folders don't follow the same naming pattern you could use a dictionary (or a collection of KeyValuePairs), like so:
$ZipFilesAndFolders = @{
    'FranceData.zip' = 'FranceFolder'
    'USAData.zip' = 'USAFolder'
    'GermanData.zip' = 'GermanFolder'
    'ItalyData.zip' = 'ItalyFolder'
    'DanemarkData.zip' = 'DanemarkFolder'
}

foreach ($KeyAndValue in $ZipFilesAndFolders.GetEnumerator())
{
    $ZipFilePath = $KeyAndValue.Key
    $DestinationPath = $KeyAndValue.Value

    Expand-Archive -LiteralPath $ZipFilePath -DestinationPath $DestinationPath
}

With PowerShell 4 (and 3)
If you have .Net Framework 4.5 installed, you can use Microsoft.PowerShell.Archive which was created by the PowerShell team.
PowerShell 4 requires .Net Framework 4.5 so this should work without any system changes needed.
The module can be found at https://github.com/PowerShell/Microsoft.PowerShell.Archive
The syntax used is identical, the function is Expand-Archive and the parameters are -Path, -LiteralPath, and -DestinationPath.
Just ensure that you have imported the module before using it, this can be done using the Import-Module cmdlet like so:
Import-Module -Name 'Microsoft.PowerShell.Archive' -Force

PowerShell 2
A solution for PowerShell 2 can be found here: https://stackoverflow.com/a/37814462/9447234


text:
Q: Firefox: How do I perform "Move to New Popup Window" on a tab? Firefox has a tab bar context menu item "Move to New Window". This will create a new window with all the default window configuration, incl. vertical tabs, location bar and whatever else one might have.
I occasionally want to move a web application from regular tab into an "app"-like window, i.e. all the window.open features removed. Also known as a popup.
Sounds like an addon, but I'm not finding any so far.
Any other tricks or suggestions in the meanwhile?

A: Building an answer here. This probably goes into the territory of pinned tabs. Couple of addons out there, that take a shot at this, but none of them want to hide the tabbar.
https://addons.mozilla.org/en-US/firefox/addon/simply-pinned/?src=search
https://addons.mozilla.org/en-US/firefox/addon/aaapptabs/?src=search
EDIT kind of sucks that Chrome application shortcuts are the closest thing to a solution. If only links could still be opened in Firefox..

A: Found this https://addons.mozilla.org/ru/firefox/addon/popvideo/ but only for video.


text:
Q: How durable is the MCU Captain America's bodysuit? In the comics it seems to be little more than cloth, but in the movies it doesn't look like it's cloth. It looks tactical and practical, almost like modern day military gear. Is there any evidence of how durable it is?
Feats and evidence are prefered over words.

A: Captain America's suit is composed of a Nomex and Kevlar fiber.  Possibly bulletproof and fireproof it can withstand blunt force trauma and energy blasts from alien weaponry.
His previous suit was made of carbon polymer and it offered a medium level of resistance to gunfire.


text:
Q: Spartacus running dev:ssr on multisite not passing requestOrigin from the NgExpressEngineDecorator I'm running a Spartacus SSR Multisite.
This works fine when I'm running yarn build:ssr and yarn serve:ssr.
The Spartacus NgExpressEngineDecorator nicely passes the original hostname to the application.
But when I run yarn dev:ssr for debugging purposes, this fails.
The SERVER_REQUEST_ORIGIN always returns localhost or 127.0.0.1.
https://github.com/SAP/spartacus/blob/develop/core-libs/setup/ssr/engine-decorator/ng-express-engine-decorator.ts#L108
So the baseSite can't be found.
Setting "host" and "publicHost" options on the "serve-ssr" in angular.json doesn't seem to help either. Any ideas how we can solve this issue?
If I have a decent way to debug the multisite SSR, I'd be very happy.

A: As @Krzysztof Platis mentioned, putting server.set('trust proxy', 'loopback'); in server.ts is what solved my problem


text:
Q: ReactJS - Clear localStorage on tab/browser close but not on refresh i want to clear local  storage on tab close not on refresh
Is there a way to detect tab close event to clear the localStorage. I need localStorage to share data across tabs. window.onbeforeunload event works fine but it has 2 issues for me:
It also fires on page refresh which I dont want.
i also try windw.onCLose but not working.

A: I think its wise to use sessionStorage(window.sessionStorage) rather than localStorage because it automatically clears the data after closing browser or tab.
And for window.onbeforeunload, you can't prevent this event on page refresh.


text:
Q: ASP.NET theme: edit by user I'm searching for a demo app that allow user to edit (change items css - color, background, etc. but also change items position and add/delete new elements on page) application theme/css in ASP.NET.
Any idea of such application?
Thank you.

A: Umbraco - a free .NET content management system - might be worth a review, though I'm not sure that this is exactly what you are looking for:
http://umbraco.com/why-umbraco
The above link is not a demo per se, so please defer to another answer if you strictly need a demo, versus an example of a tool that has the functionality you indicated. In addition to the items you menioned, Umbraco allows you to embed your own controls in the CMS, among other great features. I don't have personal experience with it, but colleagues have recommended it to me.


text:
Q: Issue with creating new variable with python I'm very new to Python but have an analysis to do.
I have created a new variable from the data set data_2015 and data 2016:
rfd_per_district_15 = data_2015[['Nom_Districte', 'Índex RFD Barcelona = 100']].groupby(['Nom_Districte'], as_index=False).sum()['Índex RFD Barcelona = 100']
rfd_per_district_16 = data_2016[['Nom_Districte', 'Índex RFD Barcelona = 100']].groupby(['Nom_Districte'], as_index=False).sum()['Índex RFD Barcelona = 100']

but the outcomes are very different. The 'rfd_per_district_16' came out exactly the way I would like it to come out. In float format, so I can carry on working with it
0     367.7
1     719.4
2     523.3
3     921.2
4     476.6
5     676.0
6     494.4
7     952.6
8     604.0
9    1054.8
Name: Índex RFD Barcelona = 100, dtype: float64

but 'rfd_per_district_15' came out very strangely. Like data from multiple lines get attached to each other:
0                                     75.8108.576.696.4
1                          104.895.8165.8128.9103.898.6
2                              111.289.0114.4106.3103.0
3          90.488.182.795.256.974.593.572.392.689.380.9
4                                       124.5109.9250.5
6     65.061.448.851.155.955.647.855.454.035.647.134...
7                          43.160.258.075.676.870.185.8
8           78.784.796.8150.295.6162.554.4102.868.357.5
9                      74.336.970.483.282.274.377.088.2
10                       151.7199.1214.1188.9205.1141.0
Name: Índex RFD Barcelona = 100, dtype: object

I see the difference as 'rfd_per_district_15' came out as object type, but why?
I had to delete index [5] in 'rfd_per_district_15' as there was some weird value, but even after that data came out strangely (not as rfd_per_district_16). I know just the basics of python so really don't know how to figure that out ...

A: Can you tell the difference between

*

*Name: Índex RFD Barcelona = 100, dtype: float64

*Name: Índex RFD Barcelona = 100, dtype: object
Problem is with the data type /dtype  of the column
Try to convert the data type of the dataframe data_2015 to match the data_2016
Use data_2015.dtypes to check the dtypes of columns.

A: data_2015["Índex RFD Barcelona = 100"] = data_2015['Índex RFD Barcelona = 100'].astype('float')

with this code, I managed to convert the type of column. Thank you @sam


text:
Q: MySQL not using index when using IN with OR Background

*

*users table has 2k rows

*relationships table has 1.5 million rows

*posts table has 2 million rows

*using mysql version 5.7.34

Structure for users:
CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `email` varchar(255) NOT NULL DEFAULT '',
  `first_name` varchar(255) NOT NULL DEFAULT '',
  `last_name` varchar(255) NOT NULL DEFAULT '',
  `password` varchar(255) NOT NULL DEFAULT '',
  `active` tinyint(1) NOT NULL,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=3263 DEFAULT CHARSET=utf8

Structure for relationships:
CREATE TABLE `relationships` (
  `user_id` int(11) unsigned NOT NULL,
  `is_following_user_id` int(11) unsigned NOT NULL,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY `user_id` (`user_id`,`is_following_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Structure for posts:
CREATE TABLE `posts` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL,
  `parent_post_id` int(11) DEFAULT NULL,
  `content` varchar(255) DEFAULT '',
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2412061 DEFAULT CHARSET=utf8

NOTE: User 922 has no relationships or posts, therefore the queries are doing a full index and/or table scan as needed.

This query takes 0.5ms:
# 0.5ms
select * from posts where user_id in (
    select id from users inner join relationships
        on users.id = relationships.is_following_user_id
        where relationships.user_id = 922
);

Explain output for above fast query:

This query takes 500ms:
# 500ms
select * from posts where user_id in (
    select id from users inner join relationships
        on users.id = relationships.is_following_user_id
        where relationships.user_id = 922
    )
or user_id = 922;

Explain output for above slow query:

Clearly for the second query it has identified the same index as the first query (users.user_id), but in the second query, as per the explain output, it's specifically avoiding using it (key = NULL).
This query takes 2.3 seconds:
# 2.3 seconds
select * from posts where user_id in (
    select id from users inner join relationships
        on users.id = relationships.is_following_user_id
        where relationships.user_id = 922
    union all
    select 922
);

Explain output for above super slow query:

Questions:

*

*Why is query #2 not using the users.user_id index like query #1?

*Why is query #3 so much slower, and also not using the users.user_id index?

A: In general, the answers to your questions are that the query optimizer will do its best but only looks for a limited number of special cases, and those typically don't include merging different sources of key values, and often do include trying to convert parts of a subquery to joins, sometimes to the detriment of efficiency.
You can likely force it to do what you want with:
select straight_join p.*
from (
    select id from users inner join relationships on users.id = relationships.is_following_user_id where relationships.user_id = 922
    union all
    select 922
) ids
join posts p on p.user_id=ids.id

A: OR and IN ( SELECT ... ) are rarely optimized well.
Flattening the structure (less nesting of SELECTs) seems to help.
( SELECT p.*
    FROM relationships AS r
    JOIN users AS u  ON u.id = r.is_following_user_id
    JOIN posts AS p  ON p.user_id = u.id
    WHERE r.user_id = 922
) UNION ALL   -- see note
( SELECT *
    FROM posts
    WHERE user_id = 922
)

Note:  UNION ALL is likely to be faster than UNION DISTINCT.  Assuming no user is following theirself, it is 'correct' to use ALL.
(I have listed the tables in the JOIN in the order that the Optimizer will decide to use.  As per ysth, I like to 'think like the optimizer'.)
Dissecting the queries, with an eye to MySQL's Optimizer...

*

*relationships will be looked at first -- because it is the only thing found in WHERE.  INDEX(user_id, ...) makes that work well.

*An added boost is that INDEX(user_id, is_following_user_id) is "covering".

*The next table will be users with PRIMARY KEY(id).

*Finally (for the first SELECT), posts via INDEX(user_id).

*The other select also uses INDEX(user_id).  (However, in many UNIONs, a different index is likely to be used.  This is why UNION is often a significant optimization over OR.)

A: I would even take the pre-query (from query) a step further.  COMPLETELY REMOVE the users join.  No need for it.  The relationships table has an ID for who is following, and the user doing the following.  That can be simplified to
select straight_join
      p.*
   from
      posts p
         JOIN ( select r.is_following_user_id
                   from relationships r
                   where r.user_id = 922
                union all
                select 922 ) ids
         on p.user_id = ids.is_following_user_id

Since the inner query you were filtering on the relationship USER_ID = 922, the "is_following_user_id" IS the other person you want.  No need to join to users table just to get the "id" column.  It's still and ID column, just longer name.  The union pulls the 922 as intended.  So now all your IDs are simplified, no JOIN.  Outer results pulls for those IDs.


text:
Q: How can I convert BigInt to float in js? Lets say I have a BigInt(66555444333222111) and I want to convert it to float loke the output will be 6.6555444E9.

A: You can use the following example:
console.log( Number( BigInt('66555444333222111') ).toExponential() )


text:
Q: Thread.GetNamedDataSlot: Confict between user sessions Related Q&A (I could update that question but then content will be totally different)
Here under GetData and SetData, it is  indecated:

The third approach is to use two methods in the Thread class: GetData
  and SetData. These store data in thread-specific "slots".
  Thread.GetData reads from a thread's isolated data store;
  Thread.SetData writes to it. Both methods require a LocalDataStoreSlot
  object to identify the slot. The same slot can be used across all
  threads and they'll still get separate values

and

In this instance, we called Thread.GetNamedDataSlot, which creates a
  named slot — this allows sharing of that slot across the application.

Question 1 Please let me understand if it is valid: "Data is hold by data slot is hold for cross threads for .net mvc web api calls."
According to my experiment in simple web api application:
public class ValuesController : ApiController
{
    public IEnumerable<string> Get()
    {
        var res1 = System.Threading.Thread.GetData(System.Threading.Thread.GetNamedDataSlot("authHeader"));

        if (res1  == null)
           System.Threading.Thread.SetData(System.Threading.Thread.GetNamedDataSlot("authHeader"), new Random().var

        res2 = Thread.GetData(System.Threading.Thread.GetNamedDataSlot("authHeader"));

        return new string[] { "value1", "value2", res2?.ToString() };
    }
}

1- If I set break point
if (res1  == null) for first call it generates random number and  for successive calls res1  == null is always false which means  res1 has value and only one time random number is generated.
2- If I don't set break points
In run mode it gives randomly one of below outputs which repeats randomly, I mean i.e. 64853109 appears more than once
<ArrayOfstring>
    <string>value1</string>
    <string>value2</string>
    <string>64853109</string>
</ArrayOfstring>

<ArrayOfstring>
    <string>value1</string>
    <string>value2</string>
    <string>1174687568</string>
</ArrayOfstring>

<ArrayOfstring>
    <string>value1</string>
    <string>value2</string>
    <string>1367595402</string>
</ArrayOfstring>

<ArrayOfstring>
    <string>value1</string>
    <string>value2</string>
    <string>1303501153</string>
</ArrayOfstring>

Question 2 I could opine that in when I set break point it uses always the same thread even though I try from different browser. But could you help me diagnose the issues
Note: Set and Get slot is source of the bug of current code, I am trying to identify exact issue. My intention is not to use  thread slots for future


text:
Q: Is nonempty intersection with every set in a base a sufficient condition to prove the closure of the set is the whole space? I've noticed in some proofs, if $A\subset B$ for $B$ a topological space, it seems that it is enough to show that $A$ intersects every set in a base of $B$ to prove that the closure $\overline{A}=B$. I noticed this for instance in the proof that the closure of $\mathbb{Q}$ is $\mathbb{R}$ in the lower limit topology.
Is this ultimately true in general, that if a subspace meets every subset of a base of the ambient space, that the closure of the subspace is the whole space? If so, why?

A: Yes, it's true. Suppose that $\langle X,\mathscr{T}\rangle$ is a space, $\mathscr{B}$ is a base for $\mathscr{T}$, and $D\subseteq X$ is such that $D \cap B \ne \varnothing$ for each $B \in \mathscr{B}$. Let $x \in X$ be arbitrary, and let $V$ be any open nbhd of $x$. By the definition of a base there is some $B\in\mathscr{B}$ such that $x\in B \subseteq V$. By hypothesis $D\cap B \ne \varnothing$, so $D \cap V \supseteq D\cap B \ne \varnothing$. Thus, every open nbhd of $x$ meets $D$, and therefore $x \in \operatorname{cl}D$. Since $x$ was an arbitrary point of $X$, $\operatorname{cl}D = X$.

A: $\bar{A}$, the closure of $A$, is equal to the intersection of all the closed sets containing $A$. Therefore, $\bar{A}^c$, the complement of $\bar{A}$ in $B$, is equal to the union of all the open sets that don't meet $A$. So showing $\bar{A}=B$ is equivalent to showing $\bar{A}^c=B^c=\varnothing$, i.e. there are no open sets in $B$ that don't meet $A$ (except $\varnothing$ itself, of course). But given a base for the topology of $B$, any open set in $B$ is a union of elements in the base, so to show $\bar{A}^c=\varnothing$, it suffices to show that every element of the base meets $A$. So, your conjecture is true!


text:
Q: How does the print statement gets executed four times here? Until the value of i remains greater than 0 the main() is called recursively. Once it becomes 0 the if condition is violated. Anyone tell me how the print statement is executed. When I run it, I get the output 0000. Thanks
void main()
{
    static int i=5;
    if(--i)
    {
        main();
        printf("%d",i);
    }
}

A: i = 4
call main()
    i = 3
    call main()
        i=2
        call main()
            i=1
            call main()
                i=0
            print 0
         print 0
    print 0
print 0

Remember that i is static, so it is common to all calls of the function.

A: local static variable will store the newest modified value. Because you invoke main() recursively, static i will change from 4 to 0, after i become 0, it will stop to call main() and return to above level, then printf 0 (i is 0 now).


text:
Q: Sublime Autocomplete that calls plugin I've create an autocomplete file that looks like that:
{
    "scope": "",

    "completions":
    [
            { "trigger": "ticket", "contents": "# ticket No.\"$1\" Status: $0" }

    ]

}
I'm working on a plugin that receives ticket number and returns status. Is it possible to enter the variable $1 when autocompleted and make the $0 variable filled by plugin function?


text:
Q: Salvar execução python como arquivo Eu estou criando uma calculadora de ganhos líquidos para motorista de Uber, ai eu gostaria de salvar os "input" como um arquivo de texto, Word ou Excel. Existe alguma maneira de fazer isso?
bruto = float(input('\033[0mQual o seu ganho bruto total? (APENAS NÚMEROS) '))

passageiro = int(input('Quantos passageiro você pegou? (APENAS NÚMEROS) '))

km = float(input('Quantos Kilometros você andou? '))

autonomia = float(input('Qual tem sido a autonomia do carro? '))

valorlitro = float(input('Qual o valor da gasolina que tem comprado? '))

gastogas = (passageiro / km) * (autonomia / valorlitro)

porcentagem = int(input('Qual a porcentagem cobrada pela Uber? (APENAS NÚMEROS) '))

por = (bruto / 100) * porcentagem

total = (bruto - gastogas) - por

print('\033[36mRetirando todas as cobranças o seu lucro total foi de R${}'.format(total))
```

A: Para armazenar todos os dados obtidos, você pode salvá-los em um arquivo JSON — utilizando o pacote json da biblioteca padrão do Python.
Arquivos JSON armazenam os dados em forma de um dicionário. Logo, você deverá inicialmente separar cada item dentro de um dict, da seguinte forma:
dados = {
    "bruto": bruto, "passageiro": passageiro, "km": km, "autonomia": autonomia,
    "valorlitro": valorlitro, "gastogas": gastogas, "porcentagem": porcentagem
}

Após isso, transforme o objeto em uma string JSON — utilizando a função json.dumps — e salve-a em um arquivo com a extensão .json, como no código abaixo:
import json

with open("banco de dados.json", "w") as file:
    string_json = json.dumps(dados)
    file.write(string_json)

No seu caso, como você disse que os dados serão armazenados mensalmente, crie uma lista para cada chave. Dessa forma, você poderá sempre adicionar novos dados.
O código completo para criar o "banco de dados" ficaria assim:
import json

dados = {
    "bruto": [bruto,],
    "passageiro": [passageiro,],
    "km": [km,],
    "autonomia": [autonomia,],
    "valorlitro": [valorlitro,],
    "gastogas": [gastogas,],
    "porcentagem": [porcentagem,]
}

with open("database.json", "w") as file:
    string_json = json.dumps(dados)
    file.write(string_json)

Já para adicionar novos dados ao banco de dados, basta ler o arquivo JSON — verifique primeiro se ele existe — e utilizar a função json.loads para obter um objeto dict da string.
Após isso, adicione à lista os novos valores, através do método append e salve os dados novamente, seguindo as etapas acima. Veja o exemplo abaixo:
with open("database.json") as file:
    string_json = file.read()
    dados = json.loads(string_json)

dados["bruto"].append(bruto)
dados["passageiro"].append(passageiro)

# ...


text:
Q: Limiting the scope of a temporary variable Without resorting to the heap, I would like a temporary variable to pass out of scope, freeing its storage on the stack.  However, I can think of no neat way to achieve the desired effect in a case like this:
#include <cstdlib>
#include <iostream>

int main()
{

    const int numerator {14}, denominator {3};

    // ...

    // The desired scope begins here.
    const std::div_t quotient_and_remainder {std::div(numerator, denominator)};
    const int x_lo {
        quotient_and_remainder.quot
    };
    const int x_hi {
        quotient_and_remainder.quot + (quotient_and_remainder.rem ? 1 : 0)
    };
    // The desired scope ends here.
    // The quotient_and_remainder should pass out of scope.

    // ...

    std::cout
        << "The quotient " << numerator << "/" << denominator
        << " is at least " << x_lo
        << " and is not more than " << x_hi << "." << "\n";

    return 0;

}

At the low machine level, one desires the following.

*

*Storage is first reserved on the stack for x_lo and x_hi.

*The quotient_and_remainder is then pushed temporarily onto the stack.

*The quotient_and_remainder is used to calculate values which are written into x_lo and x_hi.

*Having done its duty, the quotient_and_remainder is popped off the stack.
At the high programming level, one desires the following.

*The compiler enforces that x_lo and x_hi remain constant.

*The name quotient_and_remainder does not clutter the function's entire local namespace.

At both levels, one would like to avoid wasting memory and runtime.  (To waste compilation time is okay.)
In my actual program—which is too long to post here—the values of numerator and denominator are unknown at compile time, so constexpr cannot be used.
Ordinarily, I can think of various sound ways to achieve such effects using, for example, extra braces or maybe an anonymous lambda; but this time, I'm stumped.
(One should prefer to solve the problem without anti-idiomatic shenanigans like const_cast.  However, if shenanigans were confined to a small part of the program to avert maintainabilty problems, then shenanigans might be acceptable if there existed no better choice.)

A: In C++17, you can use a function and a structured binding declaration:
auto x_lo_x_hi = [](int numerator, int denominator) {
    std::div_t quotient_and_remainder {std::div(numerator, denominator)};
    return std::pair{
        quotient_and_remainder.quot,
        quotient_and_remainder.quot + (quotient_and_remainder.rem ? 1 : 0)
    };
};
const auto [x_lo, x_hi] = x_lo_x_hi(numerator, denominator);

Demo
x_lo_x_hi doesn't have to be a local lambda. It could be some function declared elsewhere or it could even be an IIFE (an anonymous lambda that you call immediately on the same line).
That said, this only serves to remove the name quotient_and_remainder from the local scope. Like MSalters said in a comment, any decent compiler will optimize that variable away in your original code. And even if it didn't, removing one variable from the stack will not improve the runtime, and if you have stack memory problems, the actual issue is somewhere else.


text:
Q: Why doesn't ri know anything about Rails? $ ri link_to
Nothing known about .link_to

Actually, it seems that ri knows nothing about Rails. But ri --list-doc-dirs shows the Rails folders are included:
/usr/share/ri/1.8/system
/usr/share/ri/1.8/site
/root/.rdoc
/usr/lib64/ruby/gems/1.8/doc/actionmailer-2.3.5/ri
/usr/lib64/ruby/gems/1.8/doc/actionpack-2.3.5/ri
/usr/lib64/ruby/gems/1.8/doc/activerecord-2.3.5/ri
/usr/lib64/ruby/gems/1.8/doc/activeresource-2.3.5/ri
/usr/lib64/ruby/gems/1.8/doc/activesupport-2.3.5/ri
/usr/lib64/ruby/gems/1.8/doc/cgi_multipart_eof_fix-2.5.0/ri
/usr/lib64/ruby/gems/1.8/doc/columnize-0.3.5/ri
/usr/lib64/ruby/gems/1.8/doc/daemons-1.0.10/ri
/usr/lib64/ruby/gems/1.8/doc/fastthread-1.0.1/ri
/usr/lib64/ruby/gems/1.8/doc/gem_plugin-0.2.3/ri
/usr/lib64/ruby/gems/1.8/doc/json-1.6.3/ri
/usr/lib64/ruby/gems/1.8/doc/linecache-0.46/ri
/usr/lib64/ruby/gems/1.8/doc/macaddr-1.0.0/ri
/usr/lib64/ruby/gems/1.8/doc/mime-types-1.17.2/ri
/usr/lib64/ruby/gems/1.8/doc/mongrel-1.1.5/ri
/usr/lib64/ruby/gems/1.8/doc/mongrel_cluster-1.0.5/ri
/usr/lib64/ruby/gems/1.8/doc/multipart-post-1.1.4/ri
/usr/lib64/ruby/gems/1.8/doc/postgres-0.7.9.2008.01.28/ri
/usr/lib64/ruby/gems/1.8/doc/rack-1.0.1/ri
/usr/lib64/ruby/gems/1.8/doc/rake-0.8.7/ri
/usr/lib64/ruby/gems/1.8/doc/rbx-require-relative-0.0.5/ri
/usr/lib64/ruby/gems/1.8/doc/rdoc-3.12/ri
/usr/lib64/ruby/gems/1.8/doc/rdoc-tags-1.2/ri
/usr/lib64/ruby/gems/1.8/doc/rest-client-1.6.7/ri
/usr/lib64/ruby/gems/1.8/doc/ruby-debug-0.10.4/ri
/usr/lib64/ruby/gems/1.8/doc/ruby-debug-base-0.10.4/ri
/usr/lib64/ruby/gems/1.8/doc/sqlite3-ruby-1.2.4/ri
/usr/lib64/ruby/gems/1.8/doc/uuidtools-2.1.1/ri

What's wrong with it?
UPDATE
I found these yaml files in the folder of /usr/lib64/ruby/gems/1.8/doc/actionpack-2.3.5/ri/ActionView/Helpers/UrlHelper/:
button_to-i.yaml  cdesc-UrlHelper.yaml  current_page%3f-i.yaml  link_to-i.yaml  link_to_if-i.yaml  link_to_unless-i.yaml  link_to_unless_current-i.yaml  mail_to-i.yaml  url_for-i.yaml

But in another system where the ri works well, the files are *.ri, not *.yaml.

A: Have you tried running:
gem rdoc rails

From the docs:
Summary:
  Generates RDoc for pre-installed gems

Description:
  The rdoc command builds RDoc and RI documentation for installed gems.  Use
  --overwrite to force rebuilding of documentation.

A: I have found that the only reliable way of installing the ri docs is this (i.e it installs the latest Rails including the ri docs):
sudo gem install rails --pre --ri


text:
Q: How to visualize a 3D scalar function? In physics, we regularly deal with observables, which are functions $f(x,y,z)$ of the position vector $\vec r = (x,y,z)$. How, do you plot such a function?
For functions $y=f(x)$ of 1 parameter, we use regular $x$-$y$ line or scatter plots. (These are sometimes called 2D plots.)
For functions $z=f(x,y)$ of 2 parameters, we can use contour/density or surface plots (and modern plotting tools render them nicely.) The latter are often called 3D plots.
For functions $f(x,y,z)$, I'm at a loss. How do I plot/visualize a three-dimensional density? The best approach I have seen so far is a set of two 2D-density plots $f(x,0,z)$ and $f(0,y,z)$ for the intersections with the $x$-$z$ and $y$-$z$ plane.
The final plot shall be printable, i.e. convey the message without relying on animation or user interaction.

A: There are a few ways to do this.
If you are visualizing it on a computer, then draw a density plot that can be rotated, like the one presented here.
Otherwise, plot color-coded dots at well-spaced intervals.
One other idea (which I use at times) is to plot the vector field $f(x,y,z)\hat k$. It's pretty easy to get the gist of a vector field by glancing at a plot like

and this idea can be extended to a scalar field.

A: There are density plots for visualizing f(x,y,z).
You might have seen plot for wave function of electron around
 So the result is a 3 dimensional gird with smeared fog as the f(x,y,z). fog is thick where f is large and thin where f is small.
ContourPlot3D or ListPointPlot3D routine in mathematica  might do the job for you.
or try this
http://www.shodor.org/cserd/Resources/Models/DensityPlot/applet.html


text:
Q: How do I close another form with a checkbox I have 2 forms MainUI and Log
I want to close Log from MainUI with a checkBox but I can't figure out how to do that.
This is my code in MainUI :
public void checkBox4_CheckedChanged(object sender, EventArgs e)
{
        if (checkBox4.Checked == true)
        {
            Log F2 = new Log();
            F2.Show();
        }
        else if (checkBox4.Checked == false)
        {
            //Here should the exit code be for the Log form.
        }
}

Log:
public partial class Log : Form
{
    public Log()
    {
        InitializeComponent();
    }
    private void Log_Load(object sender, EventArgs e)
    {
    }
    public void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
    }

}

A: You need to make the variable visible at method level for that. move it outside the if block for that:
public class MainUIForm : Form
{
  private Log F2  = null;

  public void checkBox4_CheckedChanged(object sender, EventArgs e)
  {

      if (checkBox4.Checked)
      {
        F2 = new Log();
        F2.Show();
      }
      else
      {
        F2?.Close(); // for closing which will dispose it
      }
   }
}

This assumes that when you check the checkbox, you need a new fresh window to be opened for Log and discard previous window and it's state.
If the Log window needs to be created/instantiated once and you just need to show it to user and hide depending on the checkbox either checked or not, then you would need to adjust the code like:
public class MainUIForm : Form
{
  private Log F2 = new Log();

  public void checkBox4_CheckedChanged(object sender, EventArgs e)
  {

      checkBox4.Checked ?
        F2.Show() :
        F2.Hide();

   }
}

A: Modify Your Main form should like this
///Make it as global
Log F2 = null;

public void checkBox4_CheckedChanged(object sender, EventArgs e)
    {

        if (checkBox4.Checked == true)
        {
            if(F2 == null)
                {
                  F2=new Log();
                }
            F2.Show();
        }
        else if (checkBox4.Checked == false && F2 != null)
        {
            F2.Hide();
            F2.Close();
            //Here should the exit code be for the Log form.
        }
}

A: The post was solved, I did Log.Close(); instead of Log.Hide() FIXED!


text:
Q: Blazor Components: How can I have a different ComponentBase? I would like to link a Blazor component to my own ComponentBase but I get the error
Partial declarations of 'TestComponent' must not specify different base classes
Is this actually possible? Here are my examples.
@* TestComponent.razor *@

Test Component

// TestComponent.razor.cs
public partial class TestComponent : MyComponentBase
{}

public class MyComponentBase : ComponentBase
{
   public int MyProperty { get; set; }
}

A: Yes it's possible but you need to also specify the base class in TestComponent.razor like so:
@inherits MyComponentBase;


text:
Q: When should I do decoupling for a control system? I know that Decoupling Process converts MIMO problems to SISO problems and that is helpful to design the control algorithm. But I think that with the state-space control we can design control algorithm without needing to decoupling the system. So when should I use decoupling in control problem?

A:
we can design control algorithm without needing to decoupling the system

It's true mathematics-wise. But, not computation-wise.
If the system can be divided into subsystems with little influence on each other, it is much easier to solve multiple smaller question than a single large question. Please notice that the order of state space matrices increase with $O(N^2)$ and solving the control problem could be even worse. You wouldn't feel it unless you face with really challenging systems.
For complicated control problems such as Model Predictive Control (MPC) the system dimension is very critical and each variable can add multiple rows and columns to the matrix problem. This number can be in range of 100 additional rows and columns. In such cases, Distributed MPC (DMPC) have become very popular and there are active research on them.
For small and simple problems, this is not that bad in mathematical sense. However, still decoupling is attractive as it makes the problem easier for human being to understand.

A: This is a bit of a soft-question.
From a control systems engineer point of view, decoupling is interesting if in principle you wanted the plant to be built as a decoupled system to begin with.
Say you control signal is actually a manual input, if there is a button to go up, and a button to go left, the user wants to press the "up" button and have the system go "up", not "up and a bit right", so that he now needs to press the "left" button for the system to be "centered, but not up enough". Hence you have the control systems perform all the needed compensation (i.e. decoupling) so that the operator does not need to do it himself. the principle also works if the inputs are actually given by an algorithm developed by a third party that might be oblivious to the plant dynamics (the kind of people usually referred to as "customer").
Also, some outputs may be simply undesirable, such that your goal is never to move them away from zero. Think about a flexible mechanical system, which you wanted to be rigid. Some decoupling could prevent vibration modes from getting excited (albeit this is hard in practice).


text:
Q: Update HTML meta tags inside index.html dynamically in Flutter Web I have created a website in Flutter web and added all meta tags inside index.html for SEO. The title tags get updated using the Flutter Title widget but I want to update description, keywords, og:title, og:description etc HTML tags for SEO when the webpage changes. How can I do this?

A: to append meta in header try this in main and before runApp
  html.MetaElement meta = html.MetaElement();
  meta.content = "meta-content";
  meta.name = "meta-name";
  html.document.head?.append(meta);

and don't forget to add to pubspec.yaml file in dependencies
http: ^0.13.4

and finally inspect your page to see it , it will be found before closing tag of header ,
also you can append any script or element to head or body tag


text:
Q: When having non-proportional hazards, should I use stratified Cox by time or Logrank tests within periods? My data have non-proportional hazards with clear separation. Should I handle it via stratified Cox regression or using separate Log-rank test within subsets?
I will use R only to illustrate.
I want to split the follow up into two periods, T<100 days and T>= 100 days.
For the Cox analysis I can use the survSplit(), but survdiff doesn't work with it.
lung$ph.karno_cat <- ifelse(lung$ph.karno < 100, "A", "B")
lung.split <- survSplit(Surv(time, status) ~ ., data= lung, cut=c(180, 350), episode= "tgroup", id="id")

> survdiff(Surv(tstart, time, status) ~ ph.karno_cat:strata(tgroup), data=lung.split)
Error in survdiff(Surv(tstart, time, status) ~ ph.karno_cat:strata(tgroup),  :
  Right censored data only

Having just one categorical covariate, can I just use the p-values from the coxph() per each stratum? They test whether the coefficient is non-zero and should correspond to the log-rank, isn't it?
> coef(summary(coxph(Surv(tstart, time, status)
~ ph.karno_cat:strata(tgroup), data=lung.split) ))

                                            coef exp(coef)  se(coef)           z  Pr(>|z|)
ph.karno_catA:strata(tgroup)tgroup=1  0.82367716  2.278864 0.5170404  1.59306146 0.1111464
ph.karno_catB:strata(tgroup)tgroup=1          NA        NA 0.0000000          NA        NA
ph.karno_catA:strata(tgroup)tgroup=2  0.65219820  1.919756 0.4709701  1.38479747 0.1661144
ph.karno_catB:strata(tgroup)tgroup=2          NA        NA 0.0000000          NA        NA
ph.karno_catA:strata(tgroup)tgroup=3 -0.03294059  0.967596 0.3683481 -0.08942787 0.9287419
ph.karno_catB:strata(tgroup)tgroup=3          NA        NA 0.0000000          NA        NA

Or should I use the survdiff on filtered data?
> survdiff(Surv(time, status) ~ ph.karno_cat, data=lung, subset = time < 180)
Call:
survdiff(formula = Surv(time, status) ~ ph.karno_cat, data = lung,
    subset = time < 180)

n=67, 1 observation deleted due to missingness.

                N Observed Expected (O-E)^2/E (O-E)^2/V
ph.karno_cat=A 63       57    59.17    0.0795      2.72
ph.karno_cat=B  4        4     1.83    2.5704      2.72

 Chisq= 2.7  on 1 degrees of freedom, p= 0.1

> survdiff(Surv(time, status) ~ ph.karno_cat, data=lung, subset = time >= 180 & time < 350)
Call:
survdiff(formula = Surv(time, status) ~ ph.karno_cat, data = lung,
    subset = time >= 180 & time < 350)

                N Observed Expected (O-E)^2/E (O-E)^2/V
ph.karno_cat=A 72       46     40.3      0.82      4.07
ph.karno_cat=B 13        5     10.7      3.07      4.07

 Chisq= 4.1  on 1 degrees of freedom, p= 0.04

and
> survdiff(Surv(time, status) ~ ph.karno_cat, data=lung, subset = time >= 350)
Call:
survdiff(formula = Surv(time, status) ~ ph.karno_cat, data = lung,
    subset = time >= 350)

                N Observed Expected (O-E)^2/E (O-E)^2/V
ph.karno_cat=A 63       43    43.08  0.000143  0.000839
ph.karno_cat=B 12        9     8.92  0.000689  0.000839

 Chisq= 0  on 1 degrees of freedom, p= 1

The p-values are different, but quite close to the p-values for the Cox model. Which option would you prefer and why?
EDIT: I used the statistical package only to illustrate the problem. I am not asking for anyone to write code for me and I don't ask for datasets or debugging.

A: The way you did the separate survdiff() evaluations, based on subsetting from the original lung data set, means that each evaluation was only done for those with time values within each time-period subset. It ignores all those who might have been at risk during that time period but only have event/censoring times beyond that period. That's incorrect, as it's ignoring individuals with informative right-censored survival times (from the perspective of your first 2 time subsets).
That's why survSplit() defines each tgroup to include all at risk during the corresponding time period. (Also, survSplit() uses left-open/right-closed time limits rather than the left-closed/right-open time limits you used for subsetting the data.)
I suppose you could do survdiff() on each tgroup, but what does that gain you over the Cox model? With the Cox model you can incorporate the additional covariates that typically are needed to describe a data set adequately.
Finally, although you say "My data have non-proportional hazards with clear separation," that might not necessarily be the case. It's possible for a mis-specification of the functional form of a Cox model to masquerade as non-proportionality. Omission of critical predictors or interaction terms, or improper transformations of continuous predictors, can lead to apparent violations of proportional hazards that can be fixed by fixing the model itself. Unless there's a compelling reason to believe that there is a clear separation based on your knowledge of the subject matter rather than inspection of your results, consider that possibility before you go on to time stratification.


text:
Q: Как создать цикл от одной даты до другой с интервалом в 30 минут? C помощью библиотеки Arrow сделал цикл через каждый час
from arrow import Arrow

start = datetime(2021, 3, 25, 0, 0)
end = datetime(2021, 3, 26, 0, 0)

for r in Arrow.range('hours', start, end):
    ...

А как сделать через каждые 30 мин?

A: Можно воспользоваться модулем Pandas:
import pandas as pd   #  pip install pandas

res = pd.date_range(start, end, freq="30min")

результат:
In [187]: res
Out[187]:
DatetimeIndex(['2021-03-25 00:00:00', '2021-03-25 00:30:00',
               '2021-03-25 01:00:00', '2021-03-25 01:30:00',
               '2021-03-25 02:00:00', '2021-03-25 02:30:00',
               '2021-03-25 03:00:00', '2021-03-25 03:30:00',
               '2021-03-25 04:00:00', '2021-03-25 04:30:00',
               '2021-03-25 05:00:00', '2021-03-25 05:30:00',
               '2021-03-25 06:00:00', '2021-03-25 06:30:00',
               '2021-03-25 07:00:00', '2021-03-25 07:30:00',
               '2021-03-25 08:00:00', '2021-03-25 08:30:00',
               '2021-03-25 09:00:00', '2021-03-25 09:30:00',
               '2021-03-25 10:00:00', '2021-03-25 10:30:00',
               '2021-03-25 11:00:00', '2021-03-25 11:30:00',
               '2021-03-25 12:00:00', '2021-03-25 12:30:00',
               '2021-03-25 13:00:00', '2021-03-25 13:30:00',
               '2021-03-25 14:00:00', '2021-03-25 14:30:00',
               '2021-03-25 15:00:00', '2021-03-25 15:30:00',
               '2021-03-25 16:00:00', '2021-03-25 16:30:00',
               '2021-03-25 17:00:00', '2021-03-25 17:30:00',
               '2021-03-25 18:00:00', '2021-03-25 18:30:00',
               '2021-03-25 19:00:00', '2021-03-25 19:30:00',
               '2021-03-25 20:00:00', '2021-03-25 20:30:00',
               '2021-03-25 21:00:00', '2021-03-25 21:30:00',
               '2021-03-25 22:00:00', '2021-03-25 22:30:00',
               '2021-03-25 23:00:00', '2021-03-25 23:30:00',
               '2021-03-26 00:00:00'],
              dtype='datetime64[ns]', freq='30T')

результат можно легко преобразовать в список объектов datetime:
In [190]: res.to_pydatetime().tolist()
Out[190]:
[datetime.datetime(2021, 3, 25, 0, 0),
 datetime.datetime(2021, 3, 25, 0, 30),
 datetime.datetime(2021, 3, 25, 1, 0),
 datetime.datetime(2021, 3, 25, 1, 30),
 datetime.datetime(2021, 3, 25, 2, 0),
 datetime.datetime(2021, 3, 25, 2, 30),
 datetime.datetime(2021, 3, 25, 3, 0),
 datetime.datetime(2021, 3, 25, 3, 30),
 datetime.datetime(2021, 3, 25, 4, 0),
 datetime.datetime(2021, 3, 25, 4, 30),
 datetime.datetime(2021, 3, 25, 5, 0),
 datetime.datetime(2021, 3, 25, 5, 30),
 datetime.datetime(2021, 3, 25, 6, 0),
 datetime.datetime(2021, 3, 25, 6, 30),
 datetime.datetime(2021, 3, 25, 7, 0),
 datetime.datetime(2021, 3, 25, 7, 30),
 datetime.datetime(2021, 3, 25, 8, 0),
 datetime.datetime(2021, 3, 25, 8, 30),
 datetime.datetime(2021, 3, 25, 9, 0),
 datetime.datetime(2021, 3, 25, 9, 30),
 datetime.datetime(2021, 3, 25, 10, 0),
 datetime.datetime(2021, 3, 25, 10, 30),
 datetime.datetime(2021, 3, 25, 11, 0),
 datetime.datetime(2021, 3, 25, 11, 30),
 datetime.datetime(2021, 3, 25, 12, 0),
 datetime.datetime(2021, 3, 25, 12, 30),
 datetime.datetime(2021, 3, 25, 13, 0),
 datetime.datetime(2021, 3, 25, 13, 30),
 datetime.datetime(2021, 3, 25, 14, 0),
 datetime.datetime(2021, 3, 25, 14, 30),
 datetime.datetime(2021, 3, 25, 15, 0),
 datetime.datetime(2021, 3, 25, 15, 30),
 datetime.datetime(2021, 3, 25, 16, 0),
 datetime.datetime(2021, 3, 25, 16, 30),
 datetime.datetime(2021, 3, 25, 17, 0),
 datetime.datetime(2021, 3, 25, 17, 30),
 datetime.datetime(2021, 3, 25, 18, 0),
 datetime.datetime(2021, 3, 25, 18, 30),
 datetime.datetime(2021, 3, 25, 19, 0),
 datetime.datetime(2021, 3, 25, 19, 30),
 datetime.datetime(2021, 3, 25, 20, 0),
 datetime.datetime(2021, 3, 25, 20, 30),
 datetime.datetime(2021, 3, 25, 21, 0),
 datetime.datetime(2021, 3, 25, 21, 30),
 datetime.datetime(2021, 3, 25, 22, 0),
 datetime.datetime(2021, 3, 25, 22, 30),
 datetime.datetime(2021, 3, 25, 23, 0),
 datetime.datetime(2021, 3, 25, 23, 30),
 datetime.datetime(2021, 3, 26, 0, 0)]

A: Это можно сделать и через стандартный datetime используя timedelta
Например:
import datetime as DT

start = DT.datetime(2021, 3, 25, 0, 0)
end = DT.datetime(2021, 3, 26, 0, 0)
step = DT.timedelta(minutes=30)

date = start
while date <= end:
    print(date)
    date += step

Результат:
2021-03-25 00:00:00
2021-03-25 00:30:00
2021-03-25 01:00:00
...
2021-03-25 23:00:00
2021-03-25 23:30:00
2021-03-26 00:00:00

A: Ещё вариант для разнообразия. Не очень эффективный (генерируются лишние объекты datetime и потом выбрасываются), но зато на основе кода из вопроса, с небольшим дополнением в виде функции islice:
from arrow import Arrow
from datetime import datetime
from itertools import islice

start = datetime(2021, 3, 25, 0, 0)
end = datetime(2021, 3, 26, 0, 0)

for r in islice(Arrow.range('minute', start, end), None, None, 30):
    print(r)

Вывод:
2021-03-25T00:00:00+00:00
2021-03-25T00:30:00+00:00
2021-03-25T01:00:00+00:00
...


text:
Q: How "safe" is it to put a higher voltage into a small DC motor? The main board in my old rechargeable philoshave failed.  Not wanting to give up easily, I soldered direct onto the DC motor (as pictured).  The motor is rated for 3.6V (pictured), but I get a much better cut if I "overclock" the motor by about 20% in terms of voltage - i.e. 4.5V rather than 3.6V.  Is this safe to do ?  The motor doesn't seem to be running hot after a few minutes under load (in this case a shave).  What are the general guidelines / tolerances allowed for this sort of thing ?

A: It will probably last for ever. Thats not much over and for the short time of a shave. would not worry it the least.

A: The voltage for a given dc motor is the nominal or average voltage for it based on n number of hours of operation, number of wire loops in the coil, construction, etc. The operating voltage is actually a range from minimum to turn on, minimum to stay on, and maximum voltage, just like any inductor. You can see the specs if you can find the data sheet from the motor's part number. There is no general guideline for it because there's no "general" type of combination of motor parameters.
That said, +20% (more like 25%) is likely the most you want to run through it or it might overheat and burn itself out, over time since you are just running it for short periods.

A: I had a 2.4V shaver that when the batteries failed, rather than replace them, I built a 12V to 3V converter to power it. ( I had also discovered that it worked better at the higher voltage. ) I kept both in the car for several years until the blades got too dull to use. So it should be safe and last as long for you.


text:
Q: Bitmasks vs if..then in JavaScript I am working on an app that contains quite a lot of flags checks in different places, like
if (a && b && c) { func1() }
else if (a && !b && c) { func2() }
else if (!a && b && !c) { func3() }
...

Sometimes it happens that there can be 10 checks in one sequence.
This looks quite bulky when there are more than 3 checks to me.
I read about bitwise operations and bitmasks technique which I think can give me an elegant solution.
Though, I wonder if it's a good practice to use these practices in a real-world project where programmers of different level work. Trying not to be a smartass, but to make the code more elegant though easily readable, should I keep using if...else or should I start using bitwise operations?

A: Yes I think bitwise is a better solution.
const ACTIONS = {
  0: func0,
  1: func1,
  2: func2,
  3: func3,
  4: func4
  // ...
}

ACTIONS[a | b | c]()

A: You might find it clearer to use a switch block with binary literals as the case labels:
switch (foo){
case 0b111: /*corresponds to true-like a, b, and c*/
    func1();
    break;
case 0b101: /*corresponds to true-like a and c*/
    func2();
    break;

etc., where foo is an appropriate function of a, b, and c, generated perhaps using something like 4 * a + 2 * b + c.


text:
Q: "Will [arming/armed] teachers make schools safer?"
"Will arming teachers make schools safer?"

I think that the author should have used armed teachers in this sentence.
If it is grammatically correct, what is the difference between the two usages, concerning the means.
Here is the news link;
http://www.npr.org/sections/ed/2017/06/25/534230962/colorado-teachers-get-gun-training-as-first-responders

A:
"Will arming teachers make schools safer?"

This question is about the decision / process to provide guns / weapons / arms to teachers, for the purpose to make schools safer.

"Will armed teachers make schools safer?"

This question is about the teachers which carry guns / arms, again for the purpose of ensuring safety.

Both ways are grammatically correct and both can be used, having ultimately similar meanings - the result of arming teachers is armed teachers.

A: Either-or. It just depends on whether you want to convey an action or a state/quality. However, I agree with the author's choice to use "arming", because it implies that teachers are not yet armed. If you were to say "Will armed teachers make schools safer?", it could carry with it an implication that some teachers are presently (presumably) breaking the law and possessing firearms in .
But to answer your question succinctly, yes, both the author's and your wording is correct.


text:
Q: How to make parametrized update statement I want to make update query with Parameters , the code I have doesn't work as I took the insert statement and made some changes to it
Dim db As DAO.Database
    Dim qdf As DAO.QueryDef
    Dim strUpdate As String
    strUpdate = "Update tblClients set [Client Name] = [Client Name],[Client Address] = [Client Address], [Client National ID] = [Client National ID], [phone1] = [phone1], [phone2] = [phone2], [phone3] = [phone3]"
    Set db = CurrentDb
    Set qdf = db.CreateQueryDef("", strUpdate)
    qdf.Parameters("Client Name").Value = txtName
    qdf.Parameters("Client Address").Value = txtAddress
    qdf.Parameters("Client National ID").Value = txtNationalID
    qdf.Parameters("phone1").Value = txtPhone1
    qdf.Parameters("phone2").Value = txtPhone2
    qdf.Parameters("phone3").Value = txtPhone3
    qdf.Execute dbFailOnError
    Set qdf = Nothing
    Set db = Nothing

and the error i get is : Error 3265 Item not found in this collection


text:
Q: weird behaviour of eclipse osgi bundle I'm trying to deploy a few bundles I implemented along all the required bundles from Eclipse in order to run my own. Let's say, include the Equinox container also with my bundles so it is like an executable old-school JAR.
That said, when I try to run
java -jar org.eclipse.osgi_3.8.1.v20120830-144521.jar

Nothing happens...it just stays there doing nothing...even if I copy just that bundle to some other place and try the same, nothing happens...is this usual? I mean, I have done this successfully with older versions of this bundle (3.6) and it worked flawlessly.
Alas, I tried -debug flag to see if I could get some output, but only a complain about mission .options file is happening, nothing else.
Thanks,
Alex

A: Just in case someone has the same problem...having checked this link: http://docs.codehaus.org/spaces/flyingpdf/pdfpageexport.action?pageId=82903240, I created the configuration folder, a config.ini in it with the following contents:
osgi.bundles=org.eclipse.equinox.common@start, org.eclipse.update.configurator@start,
org.eclipse.core.runtime@start, org.eclipse.core.jobs@start,
org.eclipse.equinox.registry@start, org.eclipse.equinox.preferences@start,
org.eclipse.core.contenttype@start, org.apache.felix.gogo.runtime@start,
org.apache.felix.gogo.shell@start,
org.eclipse.equinox.app@start,org.eclipse.equinox.console@start,
eclipse.ignoreApp=true
osgi.noShutdown=true

This seems to work. I believe this is the minimum set of bundles required to run the Equinox OSGi container...from there, you can use the osgi shell to play with your bundles

A: You havent included -console option, that is the one that will open up the console view right?


text:
Q: counterexample of reflexive space not hilbert We know that all Hilbert spaces are reflexive. My problem is to show that the reciproque is not true: But I can't find a counterexample. An idea please.

A: $\ell^{p}, L^{p}([0,1])$ with $1 <p <\infty$ are reflexive spaces which are not inner product spaces.


text:
Q: CDI conditional Bean with Instance I have the necessity to provide the correct Bean implementation at runtime.
The common interface:
public interface MyInterface { ... }

The implementations:
@Named("one")
class MyInterfaceImpl1 implements MyInterface { ... }

@Named("two")
class MyInterfaceImpl2 implements MyInterface { ... }

@Named("three")
class MyInterfaceImpl3 implements MyInterface { ... }

Notice these classes are package-private.
I then wrote a @Produces method:
@Produces
@Singleton
MyInterface getMyInterface(
        final Instance<MyInterface> myInterfaceImplementations,
        final Configuration configuration) {
    // Might be one, two or three.
    final String parameter = configuration.getString("value");
    return myInterfaceImplementations.select(new NamedLiteral(parameter)).get();
}

Is this the correct way to go, or is there a better solution?

A: Your solution would work fine, here are my 0.02$ just to make sure you intended it that way:
What Nikos Paraskevopoulos meant in his comment is that your are effectively creating four beans to inject one. MyInterfaceImpl1, MyInterfaceImpl2, MyInterfaceImpl3 are all legitimate beans for injection anywhere in the app. If these beans are heavy, creation may take some time, also the ability to inject them anywhere might not be intended? And then there is your producer method - the fourth bean - which I assume is ultimately the only one you are after.
Secondly, the three implementation beans have different scope from the producer method. If they are eligible for injection, in your case it seems logical that they share same scope perhaps?
Thirdly, using @Singleton. I would also advice for @ApplicationScoped, there is no harm and no overhead by having a proxy. You won't be able to tell the difference and can easily avoid some unpleasant surprises with CDI singleton (which doesn't behave like EJB singleton).

A: I think a more elegant solution would be to let the CDI do all the magic ;-)
Something like:
import javax.enterprise.inject.spi.CDI;

@Produces
@Singleton
MyInterface getMyInterface(final Configuration configuration) {
    // Might be one, two or three.
    final String parameter = configuration.getString("value");
    Set<MyInterface> candidates = CDI.current().getBeanManager().getBeans(parameter);
    return ( candidates.size()>0 ? candidates.get(0) : null);
}

You could also use the alternate signature of getBeans() signature to play with qualifiers when looking for a particular impl of your interface:
cfr https://docs.oracle.com/javaee/7/api/javax/enterprise/inject/spi/BeanManager.html#getBeans-java.lang.reflect.Type-java.lang.annotation.Annotation...-