text:
Q: Product-consumer with semaphores and forks Don't know why is consumer doing all the work?
I create a semaphor for the prodcut-consumer with an array of 10 integers, the array fills with names and it is return in ones and zeros (binary).The consumer is called even when the producer is unsing the semaphor.
Why does this happens?
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
#define SIZE 10
#define KEY 1234
int *Memory;
int i, j;
sem_t *sem;
char *name = "Hello";
int main(int argc, const char *argv[])
{
    int shmid;
    if ((shmid = shmget(KEY, sizeof(int) * SIZE, IPC_CREAT | S_IRWXU)) < 0)
    {
        perror("Error while creating shmget");
        return 1;
    }
    pid_t pid;
    sem = sem_open(name, O_CREAT, S_IRUSR | S_IWUSR, 1);
    if ((pid = fork()) != 0)
    {
        if ((shmid = shmget(KEY, sizeof(int) * SIZE, S_IRWXU)) < 0)
        {
            perror("error in shmget");
            return 1;
        }
        Memory = (int *)shmat(shmid, NULL, 0);
        if (Memory == NULL)
        {
            perror("error in shmat");
            return 1;
        }
        for (i = 0; i < 10; i++)
        {
            sem_wait(sem);
            Memory[j] = i;
            printf("Produced %i in box %i\n", i + 1, i + 1);
            sem_post(sem);
            sleep(1);
        }
        int status;
        wait(&status);
        sem_unlink(name);
        sem_destroy(sem);
        struct shmid_ds shmid_ds1;
        if (shmctl(shmid, IPC_RMID, &shmid_ds1) < 0)
        {
            perror(
                "Error in the father while executing shmctl when it was "
                "elimnating the segment of shared memory");
        }
    }
    else
    {
        if ((shmid = shmget(KEY, sizeof(int) * SIZE, S_IRWXU)) < 0)
        {
            perror("error in the producer with the shmget");
            return 1;
        }
        Memory = (int *)shmat(shmid, NULL, 0);
        if (Memory == NULL)
        {
            perror("error in the producer with the  shmat");
            return 1;
        }
        for (i = 0; i < 10; i++)
        {
            sem_wait(sem);
            Memory[i] = -1;
            printf("Consume and now it is %i in box %i\n", Memory[i], i + 1);
            sem_post(sem);
        }
    }
    return 0;
}

And the output is:
Produced 1 in box 1
Consume and now it is -1 in box 1
Consume and now it is -1 in box 2
Consume and now it is -1 in box 3
Consume and now it is -1 in box 4
Consume and now it is -1 in box 5
Consume and now it is -1 in box 6
Consume and now it is -1 in box 7
Consume and now it is -1 in box 8
Consume and now it is -1 in box 9
Consume and now it is -1 in box 10
Produced 2 in box 2
Produced 3 in box 3
Produced 4 in box 4
Produced 5 in box 5
Produced 6 in box 6
Produced 7 in box 7
Produced 8 in box 8
Produced 9 in box 9
Produced 10 in box 10

A: #include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
const int max = 5;
int arr[5], f = 0, r = -1;
sem_t s1, s2, sm;
void* eprod(void* pv)
{
    int i, x;
    printf("Producer Welcome\n");
    // sleep(10);
    while (1)
    {
        x = rand() % 100;
        printf("producer going to add:%d\n", x);
        sem_wait(&s2);
        sem_wait(&sm);
        // down s2 //buffer may be full
        // lock sm
        r = (r + 1) % max;
        arr[r] = x;
        sem_post(&sm);
        sem_post(&s1);
        sleep(10);
    }
    // unlock sm
    // up s1
}
void* econs(void* pv)
{
    int i, x;
    printf("Consumer Welcome\n");
    while (1)
    {
        sem_wait(&s1);
        sem_wait(&sm);
        // down s1
        // lock sm
        x = arr[f];
        f = (f + 1) % max;
        printf("Consumer removed element:%d\n", x);
        sem_post(&sm);
        sem_post(&s2);
        // unlock sm
        // up s2
        // sleep(5);
    }
}
int main()
{
    pthread_t pt1, pt2;
    sem_init(&s1, 0, 0);    // 3rd Parameter ival=1
    sem_init(&s2, 0, max);  // 3rd Parameter ival=1
    sem_init(&sm, 0, 1);    // 3rd Parameter ival=1
    pthread_create(&pt1, NULL, eprod, (void*)0);
    pthread_create(&pt2, NULL, econs, (void*)1);
    printf("Main Thread is Running\n");
    pthread_join(pt1, NULL);
    pthread_join(pt2, NULL);
    printf("Main -- - - Thanks..!\n");
    return 0;
}

Hope this helps..

A: Your output is consistent with your program code.
Both of your processes use the semaphore to gain access to the shared memory block, so they work by mutual exclusion, i.e. only one of them is allowed to use the Memory[] array at any given time.
But there is nothing in your program that would constrain the behaviour of the processes further, so it is possible for the consumer to proceed without the producer doing anything.
You need to introduce more bookkeping into your program to handle reserved/free slots in the Memory[] array, and two more semaphores for synchronising the progress of the producer and consumer. See any standard solution to the problem, e.g. http://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem#Using_semaphores


text:
Q: Open fancybox onclick using jQuery I have  structure like this:

Lorem ipsum dolor sit amet, consectetur adipisicing elit. .

how to open fancybox after click on  ?

A: Simple way (if you use jQuery): You can make a click on "fancybox-button" (it will open fancybox), when you will click on i element.
For example:
$("i.fa-search-plus").click( function() {
    $(this).parent().parent().find('a.fancybox-button').click();
});

A: This might help you understand how it works "under the hood"

$('i.fa-search-plus').click(function(){
  $('a.fancybox-button').click();
});

$('a.fancybox-button').click(function(){
   //fancybox internal code would do this part for you
   $('#lightbox').html('New message inserted here').fadeIn();
});
#lightbox{position:fixed;top:10%;left:20%;padding:100px;background:wheat;display:none;}

.fancybox-button{padding:5px 10px;background:dodgerblue;color:white;font-family:arial;text-align:center;text-decoration:none;}
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>

  This is a lightbox

Open LB

redpajama_set_name: RedPajamaStackExchange


text:
Q: Что такое node.js, react.js и тд? Все привет, я начинающий фронтенд разработчик. Было бы интересно узнать что такое node.js, react.js, vue.js(если правильно написал) и тд. И как они относяться к JavaScript , так же зачем они нужны?(с примерами). Зарание спасибо!

A: Так-с, начнём.
Node.js - javascript фреймворк, работающий на стороне Вашего ПК(что-то типа python с синтаксисом js). Для фронтенда используется как автоматический сборщик для других фреймворков(vue.js, react.js, sass), но также не один а с пакетами типа webpack, gulp, vite (очень рекомендую vite).
Vue.js - javascript фреймворк для, непосредственно, фронтенда. Максимизирует возможности языка javascript для фронтенд разработки. Попробовав его, Вы будете вспоминать то, что делали до этого момента как страшный сон)
React.js - также js фреймворк для фронтенда. Не могу сказать, чем он отличается от Vue и прочих.
Для правильной разработки это всё очень хорошие вещи(совмещать vue и react в одном проекте не надо, выберите что-то одно). Могу уверить, что Вам понравятся)
От себя могу порекомендовать использовать Vue + Sass + Vite для хорошего фронтенда. Подробнее Вы можете узнать в очень хорошей документации к vue https://vuejs.org/guide/introduction.html Гайды на ютубе смотреть не рекомендую, лучше изучайте документацию. Также vue предоставляет шаблон, в котором Вы сможете покопаться и разобраться, как всё устроено. Постарайтесь не бросить программирование, если Вы что-то не понимаете. А продолжайте кропотливо искать информацию в гугл. Также не рекомендую постоянно писать вопросы на стэковерфлоу, ведь тогда Вы не станете хорошим программистом и не сможете нормально программировать, ожидая ответа на Ваш вопрос. Enjoy!


text:
Q: OAuth2 : How to generate client id and client secret? Let's say I have a simple application.
How to set up OAuth2 to allow another application to access to some parts of my application.
For example, when devs want to use the Facebook API, they use the Facebook API User interface that generate Client id, client secret etc.
So, this is what i want my website do. provide client credentials when they request them.Not necessary by building an UI but programmatically (JAVA).
In other words, what is the stack behind the facebook API OAuth UI ? Is there a simple framework to set it up quickly and easily ?
thank you

A: There are lots of frameworks for setting up OAuth in a Java application. I would recommend having a look at Spring Boot, for example.


text:
Q: NIC MAC address is different than it should be I have cheap Tenda W150M router that is working as a WLAN card in Client+AP mode. The router MAC Address and WLAN BSSID are xx:xx:xx:xx:xx:68(those are listed in the router admin page). Now on my main DLINK router 192.168.2.2 is listed as xx-xx-xx-xx-xx-69. Also Windows arp -a shows: 192.168.2.2 xx-xx-xx-xx-xx-69. But if I call netsh wlan show all BSSID of this network is xx:xx:xx:xx:xx:68.
Now to compare that to my DLINK router:
WLAN MAC Address is: xx:xx:xx:xx:xx:54
netsh wlan show all: BSSID is xx:xx:xx:xx:xx:54
arp -a: xx:xx:xx:xx:xx:54

Now why this happens?

A: On many Wi-Fi routers, the wireless and wired LAN ports are all bridged together and presented to the AP's IP stack as a single virtual interface. That single interface needs a single MAC address, so the software engineers have to pick one to use. Often they choose to use the wired LAN port's MAC address for that purpose. So it's quite common to see a Wi-Fi router's IP address resolve to a MAC address that's different than the MAC address of the radio you're associated to (that is, the BSSID).
If you're saying that the router admin page says that the wired Ethernet MAC address ends in 68, I think that's probably just a bug in the UI.


text:
Q: how to change css to show two products in mobile mode? how to change css to show two products in mobile mode?
my website is designed with wordpress CMS and the theme is aloshop and i use 7up-theme plugin to show the bestselling and the newest and the most popular products . but when is mobile mode only one product is shown per column.how can i change it to show two products per column in mobile mode?
my web site url is -> URL
i tried CSS below:

@media(max-width:960px){
 .tab-content {
  width:50%;
  float:left;
  }
  }

A: Change your js like this
 var owl = $("#owl-demo");

 owl.owlCarousel({
  items : 10, //10 items above 1000px browser width
  itemsDesktop : [1000,4], //4 items between 1000px and 901px
  itemsDesktopSmall : [900,3], // betweem 900px and 601px
  itemsTablet: [600,2], //2 items between 600 and 0
  itemsMobile : false // itemsMobile disabled - inherit from itemsTablet option
});

Reference : http://www.landmarkmlp.com/js-plugin/owl.carousel/demos/custom.html


text:
Q: How to Add a new Key and Merge the array values in multidimemsional array PHP here's the result of my first function:
Array
(
[0] => Array
    (
        [MaidID] => 13
        [Stores] => Array
            (
                [0] => 14
                [1] => 5
            )
    )

  [1] => Array
     (
        [MaidID] => 3
        [Stores] => Array
            (
                [0] => 4
            )

    )

[2] => Array
    (
        [MaidID] => 41
        [Stores] => Array
            (
                [0] => 14
            )

    )
 )

Then, here's the result of my second function:
  Array
 (
 [1] => Array
    (
        [MaidID] => 14
        [Cash] => 10000
        [Debit] => 0
        [Credit] => 0
    )
  )

and here's should be the result:
   Array ([0] => Array (

        [MaidID] => 14
        [Cash] => 10000.00
        [Debit] => 0
        [Credit] => 0
        [MaidsID] => Array(
                       [0] => 13
                       [1] => 41
     )
   )
 )

Is it possible to make it?I need to a new key name MaidsID pointing to the list of MaidID owned by more than one Stores.Please help me, Please be patience in my question, im just a beginner.Thank you so much.

A: this code work ok. $a is your first array $b is the second,  $c is result
$a = array (array('Maid' => 1, 'Stores' => array (1,5) ), array('Maid' => 3, 'Stores' => array (4) ), array('Maid' => 4, 'Stores' => array (1) ));
$b = array (array('Maid' => 1,  'Cash' => 10000, 'Debit' => 0, 'Credit' => 0));
$MaidsID=array();

foreach ($a as $aa ){
    if (count($aa['Stores']>1)){
        array_push($MaidsID, $aa['Maid']);
    }
}
$MaidsID=array('MaidsID' => $MaidsID);

$c = array_merge($b, $MaidsID);`

A: I tested it here and it was ok. (Just replace $a with your first array and $b with seccond ).
Are you sure that the structure of your arrays is exactly as you have written above?? Maybe there is any problem with that.
You have puted array inside another array? (its not needed i think)
Howerver: For this code:
`$a = array (array('Maid' => 1, 'Stores' => array (1,5) ), array('Maid' => 3, 'Stores' => array (4) ), array('Maid' => 4, 'Stores' => array (1) ));
    $b = array (array('Maid' => 1,  'Cash' => 10000, 'Debit' => 0, 'Credit' => 0));
print_r($a);
echo "

================================================

";
print_r($b);
echo "

================================================

";

$MaidsID=array();

foreach ($a as $aa ){
    if (count($aa['Stores']>1)){
        array_push($MaidsID, $aa['Maid']);
    }
}
$MaidsID=array('MaidsID' => $MaidsID);

$c = array_merge($b, $MaidsID);

print_r($c);
echo "

================================================

";`

The output is:
Array ( [0] => Array ( [Maid] => 1 [Stores] => Array ( [0] => 1 [1] => 5 ) ) [1] => Array ( [Maid] => 3 [Stores] => Array ( [0] => 4 ) ) [2] => Array ( [Maid] => 4 [Stores] => Array ( [0] => 1 ) ) )
================================================
Array ( [0] => Array ( [Maid] => 1 [Cash] => 10000 [Debit] => 0 [Credit] => 0 ) )
================================================
Array ( [0] => Array ( [Maid] => 1 [Cash] => 10000 [Debit] => 0 [Credit] => 0 ) [MaidsID] => Array ( [0] => 1 [1] => 3 [2] => 4 ) )
================================================
Isn't this how you want the result?

A: Have a look at this. Maybe this can help you.
$result = array_merge($array1, $array2);


text:
Q: Delegate not being set (set correctly) I'm having trouble figuring out why I'm getting a nil delegate for this call. It seems like I'm setting the delegate just fine.
LogoutViewController.h
@protocol SomeNewDelegate <NSObject>

@required
- (void)someMethod;
@end

@interface LogoutViewController : UIViewController

@property (nonatomic, weak) id<SomeNewDelegate> delegate;

LogoutViewController.m
- (IBAction)logoutButtonTapped:(id)sender {
    NSLog(@"logout tapped");
    [self.delegate someMethod];
    [self dismissViewControllerAnimated:YES completion:nil];
}

MainViewController.m
@interface MainViewController () <UIScrollViewDelegate, SomeNewDelegate>

@property (nonatomic, strong) LogoutViewController *logoutVC;

@end

@implementation MainViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.logoutVC.delegate = self;
}

- (void)someMethod {
    NSLog(@"someMethod");
}

someMethod never gets called and I don't see why the delegate is nil. Any help?

A: Use below code in viewDidload
LogoutViewController *logoutVC = [[LogoutViewController alloc]init];
logoutVC.delegate = self;

Remove LogoutViewController from property.
I have used this and its working fine.
Hope its working for you.
Edited code in .h file
@protocol syncDataDelegate <NSObject>
@required
- (void) offlineSyncProcess;
@end

@interface LoginViewController : UIViewController
{
    id <syncDataDelegate> syncDelegate;
}
@property (retain) id syncDelegate;

in .m file
@implementation LoginViewController
{
  // your code
}
@synthesize syncDelegate;

- (IBAction)logoutButtonTapped:(id)sender {
    NSLog(@"logout tapped");
    [syncDelegate offlineSyncProcess];
}

You can call delegate method from here in LoginViewController.m file from any method.
in My Delegate implementation
in .m file
@interface MainViewController ()<syncDataDelegate>

@end
@implementation MainViewController

- (void)viewDidLoad
{
     [super viewDidLoad];
     LoginViewController *LVC = [[LoginViewController alloc]init];
     LVC.syncDelegate = self;
}

now use the delegate methode here
- (void) offlineSyncProcess
{
    // your code here
}

this code is working in my project, check this in your project.

A: Make sure your logoutVC is not nil when you try to set the delegate property for it.
You can implement the setDelegate method in your LogoutViewController.m. Then use break point to make sure it is invoked.

A: Delegate is nil because your logoutVC is nil, you haven't allocated memory to the logoutvc property.
Just before  self.logoutVC.delegate = self
 Add following code
self.logoutVC = [[LogoutViewController alloc]init];
Everything will start working automatically.


text:
Q: Count number of columns using firstRecord.size() in CSV? how to find number of columns in CSV?
Code to read CSV:
        CSVParser parser = new CSVParser(
                new FileReader(CSV_IMPORT_PATH), CSVFormat.DEFAULT
                .withFirstRecordAsHeader()
                .withIgnoreHeaderCase()
                .withTrim()
        );
        List<CSVRecord> list = parser.getRecords();
        System.out.println(firstRecord.size()); //NOT WORKING

i want to use this size to declare 2 dimensional array within CSVRecord loop...
Please help,
Jacek

A: Use List headers = parser.getHeaderNames();
headers.size() will be count of headers
This method is available Since: 1.7 make sure your lib version is greater than this


text:
Q: Applet - Serialport communication I'm trying to create a simple Java applet that reads data coming in through a serial port.
Is it possible?

A: By default, Java has no support for communicating with serial ports. There are libraries like RXTX that allow you to do that, but unfortunately RXTX requires a platform-specific native library in order to use the serial ports.
Further complication is that Java applets run in a very restricted sandbox by default, which means you need to a) sign the applet and b) manually install the necessary RXTX libraries on the host computer, which is not that user-friendly.
An alternative solution is discussed in this SO question (in short: use Java Web Start, not an applet, and everything gets a lot easier).

A: Yes, it is possible.  Having said that, I think @andri pointed out the best path to a solution.

A: For that you can use jSSC lib (Java Simple Serial Connector). Page on google code: http://code.google.com/p/java-simple-serial-connector/
Also see this page: http://code.google.com/p/java-simple-serial-connector/wiki/jSSC_Terminal
This is jSSC based serial port terminal applet. Source code of jSSC-Terminal you can download on "Downloads" page.
Best regards, Sokolov Alexey.


text:
Q: ASP.NET data binding multiple format I have a ASP.NET 4.5 web forms site using EF 5.
One of the object of my data model is a 'medical file' with a DateTime property (among the others):
public partial class MedFile {
    public System.Guid MedFileId { get; set; }
    public string Name { get; set; }
    public Nullable<System.DateTime> MedDate { get; set; }
    ...
}

Here it is the snippet of the web form for editing:
<asp:ListView ID="MedFilesForm" runat="server"
    ItemType="MedFile" DataKeyNames="MedFileId"
    SelectMethod="GetFiles"
    UpdateMethod="UpdateFile">
    ...
    <EditItemTemplate>
        <asp:Label ID="Label1" runat="server" AssociatedControlID="TextBox1">Name</asp:Label>
        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>' />

        <asp:Label ID="Label2" runat="server" AssociatedControlID="TextBox2">Data</asp:Label>
        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("MedDate", "{0:d}") %>' />

        <asp:LinkButton ID="UpdateButton" runat="server"
            CausesValidation="true" CommandName="Update"
        </asp:LinkButton>
    </EditItemTemplate>
</asp:ListView>

Note the UpdateMethod="UpdateFile" and the TextBox2 with the Bind("MedDate", "{0:d}").
Finally here it is the UpdatedFile in the code behind:
public void UpdateFile(Guid medFileId) {
    // get the current med file from DB
    MedFile medfile = _cartellaBLL.GetMedFileByFileId(medFileId);
    // update it with values taken from the web form
    TryUpdateModel(medfile);
    // save the updated med file
    if (ModelState.IsValid) {
       _cartellaBLL.UpdateFile(medfile);
    }
    ...
}

As known, the above TryUpdateModel(medfile) auto-magically validates, parses and converts the fields in the web form updating the passed medfile variable.
In particular, it validates and converts the value of the TextBox2 according to the date format of the application's culture possibly set in the web.config file:
<globalization culture="it-IT" uiCulture="it-IT" />

My problem is that I'd like the user would be able to set the date in the webform using one of two possible formats: the one of the default culture, in my case dd/MM/yyyy (Italy), and the international yyyy-MM-dd (ISO 8601).
Is it possible to instruct TryUpdateModel(TModel) to 'accept' both the format?


text:
Q: Custom CSS attributes for Angular components I have an Angular component that encapsulates a picture carousel.  If uses the :host selector to make itself a flexbox and ngFor to repeat an img tag for each picture in an array of pictures passed in to it through an @Input property.
I have two, related problems.
1) I want to allow the pictures to be styled to a fixed height or width.
2) I want to set the margin-right and margin-bottom on the imgs to allow spacing the pictures.
The tricky part is that I want these settings to be determined in the host template, not the carousel template so that they can be vary based on the needs of a particular page.
I've got it working using custom css properties like this:
image-list css:
:host {
    display: flex;
    flex-flow: row wrap;
    justify-content: flex-start;
    align-items: flex-start;
}

img {
    height: var(--pictureMaxHeight,-1);
    margin-right: var(--pictureSpacing,0);
    margin-bottom: var(--pictureSpacing,0);
}

calling template css:
image-list {
   --pictureMaxHeight: 300px;
   --pictureSpacing: 0.5em;
   justify-content: center;
}

I'm getting the following warning:

Custom property ignored: not scoped to the top-level :root element (image-list { ... --pictureMaxHeight: ... })

Full text:

WARNING in
  ./src/app/pages/image-list-test/image-list-test.component.css (Emitted
  value instead of an instance of Error) postcss-custom-properties:
  /home/username/wwwroot/src/app/pages/image-list-test/image-list-test.component.css:2:5:
  Custom property ignored: not scoped to the top-level :root element
  (image-list { ... --pictureMaxHeight: ... }) NonErrorEmittedError:
  (Emitted value instead of an instance of Error)
  postcss-custom-properties:
  /home/username/wwwroot/src/app/pages/image-list-test/image-list-test.component.css:2:5:
  Custom property ignored: not scoped to the top-level :root element
  (image-list { ... --pictureMaxHeight: ... })
      at Object.emitWarning (/home/username/wwwroot/node_modules/webpack/lib/NormalModule.js:117:16)
      at result.warnings.forEach (/home/username/wwwroot/node_modules/postcss-loader/lib/index.js:149:49)
      at Array.forEach (native)
      at postcss.process.then (/home/username/wwwroot/node_modules/postcss-loader/lib/index.js:149:27)
  @ ./src/app/pages/image-list-test/image-list-test.component.ts
  48:21-62  @ ./src/app/app.module.ts  @ ./src/main.ts  @ multi
  webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts

I tried declaring the variable in the app.component.css file but it made no difference to the error received.
Besides, declaring custom properties for every component in the project would completely break the encapsulation.
The interesting thing is that it works, even with the warning.
I know I could declare a custom html attribute but since this is nothing to do with the structure of the component and is purely visual styling, that seems smelly to me.
Have I missed something here or is there some better way to address this requirement?

A: Angular (or you) are using the postcss-custom-properties plugin (as you can see in the message) for custom properties that require you to declare @custom-properties to the :root selector for each component. You can disable the warning by passing the option.
I suggest you, if you can, to use postcss-css-variables that follow the css spec. So, starting from your snippet you can have this, that is much better and decoupled:
:host {
  --pictureMaxHeight: var(--public-var);
  --pictureSpacing: var(--public-var);

  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
  align-items: flex-start;
}

img {
  height: var(--pictureMaxHeight,-1);
  margin-right: var(--pictureSpacing,0);
  margin-bottom: var(--pictureSpacing,0);
}


text:
Q: Python broke, AttributeError: 'module' object has no attribute 'python_version' I am running 2.7 on Windows. I had no problems until yesterday when I tried to run a few jobs using the multiprocessing library, got a bunch of memory errors, and everything crashed.
This is what happens when I try to run pip:
Traceback (most recent call last):
  File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_ma
    "__main__", fname, loader, pkg_name)
  File "C:\Python27\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "C:\Python27\Scripts\pip.exe\__main__.py", line 5, in <mod
  File "C:\Python27\lib\site-packages\pip\__init__.py", line 13,
    from pip.utils import get_installed_distributions, get_prog
  File "C:\Python27\lib\site-packages\pip\utils\__init__.py", lin
e>
    from pip._vendor import pkg_resources, six
  File "C:\Python27\lib\site-packages\pip\_vendor\__init__.py", l
_module
    __import__(name)
  File "C:\Python27\lib\site-packages\pip\_vendor\pkg_resources\_
ne 1316, in <module>
    class MarkerEvaluation(object):
  File "C:\Python27\lib\site-packages\pip\_vendor\pkg_resources\_
ne 1320, in MarkerEvaluation
    'python_full_version': platform.python_version,
AttributeError: 'module' object has no attribute 'python_version'

I get the same thing when I try to import pandas from the python shell. Oddly enough, when instead of import pandas i try to run import pandas as pd, I get this error:
In [3]: import pandas as pd
cannot import name hashtable
------------------------------------------
ImportError
<ipython-input-3-af55e7023913> in <module>
----> 1 import pandas as pd

C:\Python27\lib\site-packages\pandas\__ini
      5
      6 try:
----> 7     from . import hashtable, tslib
      8 except Exception:  # pragma: no co
      9     import sys

ImportError: cannot import name hashtable

Any idea how I can fix this without completely reinstalling Python and all my libraries?

A: Python 3.8 removed some stuff. I solved my problems with pip (specifically pip install) by installing pip with curl

What worked for me was:
cd ~/Downloads
Downloading get-pip.py
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then running it with python 3.8:
python3.8 get-pip.py
Solved it for me.
Source: https://pip.pypa.io/en/stable/installing/

A: You can find platform.pyc in your python folder, and delect it. OK, you will see it worked(because it will have a new platform.pyc right).


text:
Q: Reading messages for specific timestamp in kafka I want to read all the messages starting from a specific time in kafka.
Say I want to read all messages between 0600 to 0800
Request messages between two timestamps from Kafka
suggests the solution as the usage of offsetsForTimes.
Problem with that solution is :
If say my consumer is switched on everyday at 1300. The consumer would not have read any messages that day, which effectively means no offset was committed at/after 0600, which means offsetsForTimes(< partitionname > , <0600 for that day in millis>) will return null.
Is there any way I can read a message which was published to kafka queue at a certain time, irrespective of offsets?

A: offsetsForTimes() returns offsets of messages that were produced for the requested time. It works regardless if offsets were committed or not because the offsets are directly fetched from the partition logs.
So yes you should be using this method to find the first offset produced after 0600, seek to that position and consume messages until you reach 0800.


text:
Q: Printf does not print the correct values after scanf (ex. 5 is printed as 6618624) I wrote up a simple calculator that utilizes functions.
#include<stdio.h>

void operation_menu();
int getNumber(int,int);
int sum(int,int);
int diff(int,int);
int mult(int,int);
double quot(double,int);
int choice,num1,num2;

int main(){

    getNumber(num1,num2);
    operation_menu();

return 0;

}

int getNumber(int num1,int num2){

    printf("Welcome to Simple Calculator!\n");
    printf("Please input a number to begin:\n");
    scanf("%d", &num1);
    printf("Great! Now input the second number:\n");
    scanf("%d", &num2);

}
void operation_menu(){

    printf("Select an operation: \n");
    printf("1. Addition\n");
    printf("2. Subtraction\n");
    printf("3. Multiplication\n");
    printf("4. Division\n");
    scanf("%d", &choice);

    switch(choice){
        case 1:
            printf("The sum of %d and %d is %d.", num1,num2,sum(num1, num2));
        break;
        case 2:
            printf("The difference of %d and %d is %d.", num1,num2,diff(num1, num2));
        break;
        case 3:
            printf("The product of %d and %d is %d.", num1,num2,mult(num1, num2));
        break;
        case 4:
            printf("The quotient of %d and %d is %.2lf.", num1,num2,quot(num1, num2));
        break;
        default:
            printf("Please try again.");
    }
}

    int sum(int num1,int num2){
        int answer;
        answer=num1+num2;
        return answer;
    }
    int diff(int num1,int num2){
        int answer;
        answer=num1-num2;
        return answer;
    }
    int mult(int num1,int num2){
        int answer;
        answer=num1*num2;
        return answer;
    }
    double quot(double num1,int num2){
        double answer;
        answer=num1/num2;
        return answer;
    }

The program worked correctly without breaking up my main() into several smaller functions, but after creating functions for each operation, input, and menu, I receive the wrong outputs. I figured this by printing num1 and num2 after using scanf and sure enough, I get the wrong outputs.

A: The function getNumber changes its local variables (parameters) num1 and num2. After exiting the function these local variables are not alive. The global variables with the same names stay unchanged.
You need to pass the global variables by reference through pointers to them. For example
int getNumber(int *num1,int *num2){

    printf("Welcome to Simple Calculator!\n");
    printf("Please input a number to begin:\n");
    scanf("%d", num1);
    printf("Great! Now input the second number:\n");
    scanf("%d", num2);

}

The function is called like
getNumber( &num1, &num2 );

Pay attention to that there is no need to declare the variables num1, num2 and choice as global. You should declare them in the scope where they are used for example within the function operation_menu.
Also the both parameters of the function quot should have the type int. The function can be defined like
double quot( int num1,int num2){
    double answer;
    answer = ( double )num1/num2;
    return answer;
}


text:
Q: UITableViewCell doesn't change its alpha/opacity I have a regular tableview and I want its cells to begin being partially transparent (alpha = 0.85). However, when I set the alpha in the cellForRowAt function, the cells begin as being fully opaque. To specify, I want the entire cell (including its contents) to be alpha = 0.85, not just the background color.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! customTableCell

    cell.textLabel?.text = "\(indexPath.section)"

    cell.backgroundColor = UIColor.white
    cell.isOpaque = false
    cell.alpha = CGFloat(0.85)

    return cell
}

A: For some reason, the tableView modifies/resets the cell's alpha and frame to some degree after cellForRowAt. There's another UITableViewDelegate method called tableView(_:willDisplay:forRowAt:) which gets triggered right before the cell is shown. Accordingly, I added the following code and it worked:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.alpha = 0.85
}

A: Try set the layer opacity:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! customTableCell

cell.textLabel?.text = "\(indexPath.section)"

cell.backgroundColor = UIColor.white
cell.isOpaque = false
cell.layer.opacity = 0.85

return cell

}


text:
Q: setOnClickListener is not showing in intellij setOnClickListener is not showing in intellij even the textview names I can't write them without R.id.the_name.

What is going wrong?

A: This is not how android works. It seems you miss the very basics.
R.id.button is just an Int, the id of a view. To get the view you can do findViewById(id) for example.
So then in your case maybe:
val button: Button = findViewById(R.id.button)
button.setOnClickListener {
    //on click
}

A: You should implement view binding to your projects.
https://developer.android.com/topic/libraries/view-binding
So instead of val btn = findViewById<Button>(R.id.yourbuttonId) you can val btn = binding.yourbuttonId


text:
Q: Junit string comparison failure This is the source code for the class that has to be tested.
When i run the junit class it gives me two failures
although the expected and actual output are identical
why?
It is also true that both are strings,
so that should not be an issue?
I see in the junit console org.opentest4j.AssertionFailedError: expected: java.lang.String@4d5b6aac but was: ss.week2.Setting@3e84448c

    private ThreeWayLamp testLamp;

    @BeforeEach
    public void setUp() {
        testLamp = new ThreeWayLamp();
    }

    @Test
    public void testState() {
        assertEquals("OFF",testLamp.getStatus());
    }

    @Test
    public void testSequence() {
        testLamp.setNextStatus();
        assertEquals("LOW", testLamp.getStatus());
    }

}
.............................................

    /**
     * @requires String userInput OFF,LOW,MEDIUM or HIGH
     * @ensures currentSetting=userInput
     * **/
    public void setStatus(String userInput) {
        if(userInput.equals("OFF")) {
            currentSetting=Setting.OFF;
        }
        if(userInput.equals("LOW")) {
            System.out.println("Setting lamp to low");
            currentSetting=Setting.LOW;
        }
        if(userInput.equals("MEDIUM")) {
            currentSetting=Setting.MEDIUM;
        }
        if(userInput.equals("HIGH")) {
            currentSetting=Setting.HIGH;
        }

    public void setNextStatus() {
        switch(currentSetting) {
        case OFF:
            currentSetting=Setting.LOW;
            break;
        case LOW:
            currentSetting=Setting.MEDIUM;
            break;
        case MEDIUM:
            currentSetting=Setting.HIGH;
            break;
        case HIGH:
            currentSetting=Setting.OFF;
            break;
        }

        }
    }

    ```

A: You don't show the code for getStatus() but the error message implies that it returns a Setting, not a String. Hence you need to do
assertEquals(Setting.OFF, testLamp.getStatus());


text:
Q: 2d multidimensional array to 1d array in php Just wondering if anyone has transformed a 2 dim array to a one dim array in php. I've yet to come across a clear explanation in php. Any suggestion would be appreciated.

A: Try this:
function array_2d_to_1d ($input_array) {
    $output_array = array();

    for ($i = 0; $i < count($input_array); $i++) {
      for ($j = 0; $j < count($input_array[$i]); $j++) {
        $output_array[] = $input_array[$i][$j];
      }
    }

    return $output_array;
}

A: This might be helpful to you if you fetching values from Query here you can use array function which will support in PHP 5.5+
$myfield_arr = array_column($query_result, 'myfield_name');

Say Good bye to loop! Enjoy Smart Code.

A: It depends on what you need but if you want to reduce your 2d array to a 1d curve that completley fills the 2d plane you probably looking for a spatial index or a space-filling-curve. There are some famous and not so known like the z-curve, the hilbert curve, the peano curve or the moore curve. You can write such a curve with a L-system.

A: Try this one:
function array_to1d($a) {
    $out = array();
    foreach ($a as $b) {
        foreach ($b as $c) {
            if (isset($c)) {
                $out[] = $c;
            }
        }
    }
    return $out;
}

Notice that it includes a test to see if the value is set (non-null). An array that's a transposition of an array with rows of varying length will have null values in some cells, and this check can be helpful if you're trying to linearize such a beast.

A: Your first thought should be array_reduce() whenever you have lots of something in an array and you just want one something by itself which represents them all in some way.
From the PHP docs:

array_reduce — Iteratively reduce the array to a single value using a callback function

In the case of 2D => 1D array conversion, the something is array;  we have lots of them in an array but we just want one of them by itself.
function array2dTo1d($array2d)
{
    return array_reduce($array2d, function($carry, $array) {
        return array_merge($carry, $array);
    }, []);
}

var_dump(array2dTo1d(
    [
        [23423, 5454, 567],
        [4565, 687],
    ]
));

Result:
array(5) {
  [0] =>
  int(23423)
  [1] =>
  int(5454)
  [2] =>
  int(567)
  [3] =>
  int(4565)
  [4] =>
  int(687)
}

A: The solution for rectangular 2D array is simple indeed, but I had a problem. My 2D-array consisted of 1D arrays of different lengths :
$myArray = [
    [1, 2, 3, 4],
    [5, 6, 7],
    [8, 9]
];

I came up with more generalized solution to turn any 2D array into 1D:
function array2DTo1D($arr2D) {
    $i = 0; $j = 0;
    $arr1D = [];
    while (isset($arr2D[$i][0])) {
        while (isset($arr2D[$i][$j])) {
            $arr1D[] = $arr2D[$i][$j];
            $j++;
        }
        $i++; $j = 0;
    }
    return $arr1D;
}

A: After PHP 5.3 there have a new function called arrray_walk_recursive
$data = [1,2,[3,4],5,[6,7,8],9];
$output = [];
array_walk_recursive($data, function($val) use (&$output) {
    $output[] = $val;
});

Notice that the $output is passed by reference
The $output will result in [1,2,3,4,5,6,7,8,9]


text:
Q: How to solve include include errors detected. Please update your includePath with  VsCode I get
#include errors detected. Please update your includePath. Squiggles are disabled for this translation unit (/Users/idoamit/Desktop/ProjectSoftware/SP Project 020822/spkmeansmodule.c).C/C++(1696)
cannot open source file "python.h"C/C++(1696)
Some one knows how to solve this?
I have Mac!
Thanks.


text:
Q: Installing facebook sdk for android, installation procedure, gen folder missing I am trying to use the facebook sdk for android, available here. I  have two questions:
Problem 1: From the instructions...
Step 1.Pull the repository from GitHub:
git clone git://github.com/facebook/facebook-android-sdk.git
Does this simply mean download the files?
Problem 2:
I downloaded the files and opened the samples as a New Android Project (from existing source).  The project files do not have anything in the gen folder.
I have tried

*

*Choosing Project >Build

*Choosing Project > Clean

*editing Java file (Example.java) and resaving it

*checking the Java commpliance level is 1.6 (Project > Properties > Java Compiler)

*deleting the gen folder and rebuilding (Project > Build)

*putting my Facebook App ID in the example.java file

Any help would be appreciated.

A: *

*cloning the repository means using the Git version control system to a local copy of the repository which you can update and get the latest code changes at any time. If you are not concerned with having the latest changes in the sdk then you can simply download the zip or tar file (which I think you did)

*The contents of the gen folder are automatically generated when you build an android project. If there is an error in the build process then the gen folder maybe empty. Please check the console (Menu -> Window -> Show view -> Console" in Eclispe and see if there are any build errors.


text:
Q: Matplotlib plot bad resolution when zooming I am using matplotlib to plot hierarchical clusterings,
import numpy as np

from scipy.cluster.hierarchy import dendrogram

def plot_dendrogram(model, **kwargs):

    # Children of hierarchical clustering
    children = model.children_

    # Distances between each pair of children
    # Since we don't have this information, we can use a uniform one for plotting
    distance = np.arange(children.shape[0])

    # The number of observations contained in each cluster level
    no_of_observations = np.arange(2, children.shape[0]+2)

    # Create linkage matrix and then plot the dendrogram
    linkage_matrix = np.column_stack([children, distance, no_of_observations]).astype(float)

    # Plot the corresponding dendrogram
    dendrogram(linkage_matrix, **kwargs)

plt.figure(figsize=(100,100))
plt.title('Hierarchical Clustering Dendrogram')
plot_dendrogram(clustering, labels=liste_tags)
plt.show()

I can visualize the hierarchical clustering, however the quality and resolution of the plot is not good. Especially, when I save the plot and try to zoom in to see the labels for example.
I get this image :

A: MatPlotLib Figure object has a dpi parameter. Just set something like plt.figure(figsize=(100,100), dpi=300).


text:
Q: Need hint: Determine whether the series $\sum_{n=1}^{\infty}(\frac{n}{n+1})^{n^2}$ is convergent or divergent. Determine whether the series $\sum_{n=1}^{\infty}(\frac{n}{n+1})^{n^2}$ is convergent or divergent.
I've tried applying all the basic tests to no avail. I need to find out what the "trick" for this particular series is.

A: Let $u_n$ = $ \Big ( \frac {n}{n+1} \Big)^{n^2}$ , then since $ \ \lim_{n \to \infty}\sqrt[n]{({\frac{n}{n+1}})^{n^2}} = \lim_{n \to \infty}(\frac{n}{n+1})^n = \lim_{n \to \infty}(\frac{1}{1+\frac{1}{n}})^n$ = $\frac1e$ $ < 1 $ , so by Cauchy's root test the series  is convergent .

A: Note the following:
$$\Big(\frac{n}{n+1}\Big)^{n}=\Big(\frac{m-1}{m}\Big)^{m-1}=(1-1/m)^{m-1}$$
That formula/function seems familiar, doesn't it?
Thereafter, note that:
$$\Big(\frac{n}{n+1}\Big)^{n^{2}}={\Big(\Big(\frac{n}{n+1}\Big)^{n}\space\Big)}^{n}$$
Hint: Simple comparison test with a sequence you know well.

A: Hint: Try with Cauchy's root test.


text:
Q: link-to doesn't fire transitions, and doesn't do anything I've got a link-to, built by current position, that for some reason doesn't do anything.
I've turned on logging Transitions, and all I get is:
Attempting transition to customer.goodie-pack, which is the route name.
I've defined a transition in app/transitions.js, but nothing seems to happen, when I click the link. I've confirmed, that the  actually has the correct href-tag. I just cannot figure out, why the click doesn't do anything. It is almost as if, something returns false, but doesn't log it (Which I believe could be some hook returning false or alike, but I'm unaware of anything firing.. The beforeModel/Model/afterModel-hooks, are AFAIK logged, when happening?)
I'm using the almost exact same script between two other routes, that works just fine, and logs as follows:
Attempting transition to customer.index
Preparing to transition from 'customer.goodie-pack' to 'customer.index'
Transition #1: customer.index: calling beforeModel hook
Transition #1: customer.index: calling deserialize hook
Transition #1: customer.index: calling afterModel hook
Transition #1: Resolved all models on destination route; finalizing transition.
Transitioned into 'customer.index'
Transition #1: TRANSITION COMPLETE.

Thus calling the hooks in the "transition-to"-route. I'm not even seeing the "preparing"-call?
I'm not enough into ember, to know when which log is called in the source-code.
More info from Ember-Inspector:

*

*Ember    2.9.0

*Ember Data   2.9.0

*jQuery   3.1.1


text:
Q: Error in file(file, "rt") : cannot open the connection ' I need to execute some R scripts in c# .So I write the code below including R.net package to do interaction between R and c#. It's about importing  csv files.
    using RDotNet;

namespace ConsoleApp11
{
    class Program
    {
        static void Main(string[] args)
        {
            REngine engine = REngine.GetInstance();
            DataFrame testData = engine.Evaluate("DataIns<-read.table('C:/Users/isalah/Desktop/Fichiers_CRM/Fichier_csv/Diagnostic.csv', header=TRUE, sep = ';')").AsDataFrame();
            DataFrame DataAch = engine.Evaluate("DataAch=read.table('C:/Users/isalah/Desktop/Fichiers_CRM /Fichier_csv/Achats1.csv',header=TRUE,sep = ';')").AsDataFrame();
            DataFrame DataDia = engine.Evaluate("DataDia=read.table('C:/Users/isalah/Desktop/Fichiers_CRM/Fichier_csv/Diagnostic.csv',header =TRUE,sep = ';')").AsDataFrame();
            DataFrame DataCad = engine.Evaluate("DataCad=read.table('C:/Users/isalah/Desktop/Fichiers_CRM/Fichier_csv/CADEAUX.csv',header =TRUE,sep = ';')").AsDataFrame();

            double v = new double();
            v = testData.ColumnCount;
        }
    }
}

It seems that the program read the first file but It's stopped in the next one showing in the console this error :

Error in file(file, "rt") : cannot open the connection '

How could I solve this problem please?


text:
Q: Kinematic equation as infinite sum I'm not sure exactly how to phrase this question, but here it goes:
$v=\dfrac{dx}{dt}$ therefore $x=x_0+vt$
UNLESS there's an acceleration, in which case
$a=\dfrac{dv}{dt}$ therefore $x=x_0+v_0t+\dfrac{1}{2}at^2$
UNLESS there's a jerk, in which case
$j=\dfrac{da}{dt}$ therefore $x=x_0+v_0t+\dfrac{1}{2}a_0t^2+\dfrac{1}{6}jt^3$
Are you picking up on the pattern? Velocity is the first derivative of position with respect to time, acceleration is the second, jerk is the third, and the formula just gets longer and longer.
Let's say that, hypothetically, and object was moving such that $\dfrac{d^{500}x}{dt^{500}}$ was a constant greater than zero. Is there some formula for an object's position  that implements an infinite summation of time derivatives of position? maybe following the form
$$x=\sum_{n=0}^{\infty}\dfrac{1}{n!}\dfrac{d^nx}{dt^n}t^n$$

A: Any "reasonable" function $f$ (such functions are called analytic) has such an expansion, known as a Taylor expansion involving the derivatives of the function itself, which converges to it. Consider a position $x(t)$ of a particle:
\begin{aligned}
x(t) = x(t_0 + \Delta t) &= x(t_0) + x'(t_0)\Delta t + \tfrac{1}{2}x''(t_0)\Delta t^2 + \tfrac{1}{6}x'''(t_0)\Delta t^3 + \dotsb \\
&= \sum_{n=0}^\infty \tfrac{1}{n!}x^{(n)}(t_0)\Delta t^n.
\end{aligned}
As you mention, we expand the function to higher orders depending on the influence of the higher-order derivatives. However, note that in this expansion, the powers of $\Delta t$ increase with each additional term we add to the expansion. For small values of $\Delta t$, these terms have less and less influence. A small term cubed is smaller than a small term squared is less than a small term to the first power.
For that matter, this kind of series expansion is ubiquitous in physics, for example in the potential energy of a particle near a point of stable equilibrium $x_0$:
\begin{aligned}
U(x) = U(x_0 + \Delta x) &= U(x_0) + U'(x_0)\Delta x + \tfrac{1}{2}U''(x_0)\Delta x^2 + \dotsb \\
&= U(x_0) + \tfrac{1}{2}U''(x_0)\Delta x^2 + \dotsb
\end{aligned}
since the term involving the first derivative of $U$ is zero when $U$ is at a point of stable equilibrium (derivative zero at a minimum). If we rewrite this equation ignoring the higher order terms that contribute less and less, and define $U(x) - U(x_0) = \Delta U$ we have
\begin{aligned}
U(x) &= U(x_0) + \tfrac{1}{2}U''(x_0)\Delta x^2 \\
\Delta U &= \tfrac{1}{2}U''(x_0)\Delta x^2,
\end{aligned}
which you may see is suspiciously similar to the potential energy of a harmonic oscillator like a mass on the spring:
$$
\Delta U = \tfrac{1}{2}k\Delta x^2.
$$
It is the harmonic oscillator that is a special case of the more general expansion we are seeing above.

A: All you are doing is $$x = \int \int a(t)\, {\rm d}t$$ and when you have linearly varying acceleration (w/ jerk) you end up with a cubic function.
The key to all of this is the fact that $$ \frac{{\rm d}^i x^n}{{\rm d}x^i} = \frac{n!}{(n-i)!} x^{n-i} $$
and you are solving the equations $$ \begin{aligned} v(t) =& \frac{{\rm d} x(t)}{{\rm d}t}\\a(t) =& \frac{{\rm d}^2 x(t)}{{\rm d}t^2} \\ j(t) =& \frac{{\rm d}^3 x(t)}{{\rm d}t^3} \\ \ldots \end{aligned} $$


text:
Q: How to keep two decimal place correct? In my test, when I use NSString's stringWithFormat:@"%.2f" method to keep two decimal place.

*

*[NSString stringWithFormat:@"%.2f", 9999.999];
result is:
10000.00

*[NSString stringWithFormat:@"%.2f", 9999.99];
result is:  9999.99

*[NSString stringWithFormat:@"%.2f", 9999.9912];
result is:  9999.99
My requirement is no matter the float is whatever, I just want to keep two decimal place, such 9999.999 -> 9999.99, not the result we saw the first example, how to do with this?

A: Try this code
1) In Objective-c:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundDown];

NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:99.9999]];
NSLog(@"numberString - %@",numberString);

2) In swift:
let formatter:NumberFormatter = NumberFormatter.init()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.roundingMode = .down
let numberString = formatter.string(from: NSNumber.init(value: 99.9999))
print("numberString - \(numberString!)")


text:
Q: margin and padding are not showing any effect when Text is so lengthy
Below is the style for each list item,
itemStyle: {
   flexDirection: 'row',
   marginHorizontal: 24,
   paddingBottom: 25,
},

There is no margin applied right side of the screen and Text occupied all available space.
How to render the Text with in the margin or padding boundaries?

A: Put each Text component inside its own View component. The either give the View a padding or give the Text a margin.

A: Try something like this:
itemStyle: {
   flex: 1,
   flexDirection: 'row',
   marginHorizontal: 24,
   paddingBottom: 25,
},


text:
Q: Need To Assign My Vendor's ID To InvoiceTable - One To Many Relationship I'm using Laravel 5.7 & VueJs 2.5.* ...
I have a TicketInvoice and each TicketInvoice is related to a Vendor. Like a Vendor hasMany() TicketInvoices and a TicketInvoice belongTo() a Vendor.
Now the issue i'm getting is when i create my invoice, i have a list of Vendors, i need to select the vendor from the list, and assign vendor_id in the TicketInvoiceTable, I have a column vendor_id in TicketInvoicetable, I don't know how to do that but i'm doing like:
Here is my HTML code:

  Select Vendor
  <select id="vendor_id" name="vendor_id" type="text" class="form-control" :class="{ 'is-invalid': form.errors.has('vendor_id')}">
    <option disabled selected>Please Select Vendor</option>
    <option v-for="vendor in vendors" :key="vendor.id" :value="vendor.vendor_id">{{ vendor.vendor_company_name }}</option>
  </select>
  <has-error :form="form" field="vendor_id"></has-error>

Here is my VueJs Code:

Here is an image for better understanding:

A: Yeah ! I got my answer:
The v-model tag needs to refer to the object in my data in the Vue Component:
<select id="vendor_id" name="vendor_id" v-model="form.vendor_id" type="text" class="form-control" :class="{ 'is-invalid': form.errors.has('vendor_id')}">
  <option disabled selected>Please Select Vendor</option>
  <option v-for="vendor in vendors" :key="vendor.id" :value="vendor.id">{{ vendor.vendor_company_name }}</option>
</select>


text:
Q: Ansible known_hosts module with a loop I am trying to run a task executing the known_hosts module with a list of key entries. The problem is that I keep getting the following error, even though the variable has data when using debug.
The task includes an option with an undefined variable. The error was: 'item' is undefined

I have the following task which registers a variable of the ssh-keyscan output
- name: keyscan platform hosts
  shell: "ssh-keyscan ssh.{{ item }}"
  register: "platform_ssh_host_keys"
  loop:
    - "one.example.com"
    - "two.example.com"

When I run the following debug, I get the stdout which contains the key
- name: debug
  debug:
    var: item.stdout
  with_items: "{{platform_ssh_host_keys.results}}"

But as soon as I run it with known_hosts it says item is undefined.
- name: configure known_hosts
  known_hosts:
    path: "~/.ssh/known_hosts"
    name: "ssh.{{ item.item }}"
    key: "{{ item.stdout }}"
    state: present
    loop: "{{ platform_ssh_host_keys.results }}"

I don't get how item can be defined in debug but not known_hosts task.

A: ♂ Well, after I posted this I immediately realized the problem was due to the fact I had loop as a property for known_hosts and not the tasks. So the problem was indentation.
This fixed it all.
- name: configure known_hosts
  known_hosts:
    path: "~/.ssh/known_hosts"
    name: "ssh.{{ item.item }}"
    key: "{{ item.stdout }}"
    state: present
  loop: "{{platform_ssh_host_keys.results}}"


text:
Q: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: [object Object] error express 4.16 I'm implementing a password reset and when clicking on the generated link I'm getting the following error,
Thu Jan 25 2018 16:54:38 GMT+0000 (GMT): GET /users/reset/d590c54753abc449cfcd8aefceb8d519fce4b627
express deprecated res.redirect(url, status): Use res.redirect(status, url) instead routes/users.js:297:9
events.js:136
      throw er; // Unhandled 'error' event
      ^

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: [object Object]
    at ServerResponse.writeHead (_http_server.js:193:11)
    at ServerResponse.writeHead (/Users/benbagley/Code/poetry-out-loud/node_modules/on-headers/index.js:55:19)
    at ServerResponse._implicitHeader (_http_server.js:184:8)
    at write_ (_http_outgoing.js:644:9)
    at ServerResponse.write (_http_outgoing.js:629:10)
    at writetop (/Users/benbagley/Code/poetry-out-loud/node_modules/express-session/index.js:290:26)
    at ServerResponse.end (/Users/benbagley/Code/poetry-out-loud/node_modules/express-session/index.js:338:16)
    at ServerResponse.redirect (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/response.js:947:10)
    at /Users/benbagley/Code/poetry-out-loud/routes/users.js:297:9
    at model.Query.<anonymous> (/Users/benbagley/Code/poetry-out-loud/node_modules/mongoose/lib/model.js:4056:16)
    at /Users/benbagley/Code/poetry-out-loud/node_modules/kareem/index.js:273:21
    at /Users/benbagley/Code/poetry-out-loud/node_modules/kareem/index.js:131:16
    at process._tickCallback (internal/process/next_tick.js:150:11)
[nodemon] app crashed - waiting for file changes before starting...

Here are my routes
// Token URL :get
router.get('/users/reset/:token', (req, res) => {
  User.findOne({
    resetPasswordToken: req.params.token,
    resetPasswordExpires: { $gt: Date.now() }
  }, function(err, user) {
    if (!user) {
      req.flash('error', 'Password reset token is invalid or has expired.');
      res.redirect('/users/forgot');
    }

    res.redirect('reset.hbs', {
      pageTitle: 'Reset Your Password',
      user: req.user
    });
  });
});

// Token URL :post
router.post('/users/reset/:token', (req, res, next) => {
  if(req.body.password === req.body['password-confirm']) {
    next();
    return;
  }

  req.flash('error', 'Passwords do not match!');
  res.redirect('back');

  User.findOne({
    resetPasswordToken: req.params.token,
    resetPasswordExpires: { $gt: Date.now() }
  }, function(err, user) {
    if(!user) {
      req.flash('error', ' Password reset is invalid or has expired');
      res.redirect('/login');
    }

    const setPassword = promisify(user.setPassword, user);
    setPassword(req.body.password);
    user.resetPasswordToken = undefined;
    user.resetPasswordExpires = undefined;
    const updatedUser = user.save();
    req.login(updatedUser);
    req.flash('success_msg', 'Your password has been reset successfully! You are now logged in!');
    res.redirect('/dashboard');
  });
});

I think, I'm close to getting this to work, just a few errors I'm running into. This being one of them. I have checked the documentation and I'm not seeing anything mentioning status codes, I believe this is a change in the recent framework, seems quite odd having to define a status code for every redirect or render.

A: You have to use res.render instead of res.redirect:
res.render('reset.hbs', {
  pageTitle: 'Reset Your Password',
  user: req.user
});

res.redirect method accept the route string as arguement while res.render accept a string that represent the file path of the view to render


text:
Q: After login button is pressed, redirect to web page in typescript I am trying to redirect to page after login. Once the login is done, it should redirect to server address. I have tried the preceding codes.
var serveraddress = "http://" + server + "/token"/*"/Account/LoginMobile"*/;

   doLogin(): void {

                var username = $("#username").val();
                var password = $("#password").val();
                var server = $("#server").val();
                //TODO do validation

                var serveraddress = "http://" + server + "/token"/*"/Account/LoginMobile"*/;

ApiHelper.post(serveraddress, { username: username, password: password, client_id: "VoltPMS.Mobile", client_secret: "voltrun", grant_type: "password" })
                    .done((data) => {
                        Volt.App.clearLoading();
                        if (data) {
                            if (data.access_token) {
                                SessionManager.setSessionItem("loginstatus", "true");
                                SessionManager.setSessionItem("username", username);
                                //SessionManager.setSessionItem("server", server);
                                SessionManager.setSessionItem("access_token", data.access_token);
                                SessionManager.setSessionItem("refresh_token", data.refresh_token);

                                 $("#username").val("");
                                 $("#password").val("");
                                 //$("#server").val("");
                                 Volt.Navigation.navigate("Home", "Home");
                            } else {
                                //TODO Login Error

                            }
                        } else {
                            //TODO Login ERROR
                        }
                    }).error((er) => {
                    Volt.App.clearLoading();
                    });

How can I redirect this address?

A: For navigation according to the https://angular.io/docs/ts/latest/guide/router.html the best is the The Angular Router component which can by passed in constructor
import { RouterModule, Routes } from '@angular/router';

and then used:
constructor( private router: Router){}
 this.router.navigate(['/home']);


text:
Q: Powershell script execution failure in Windows I have written a powershell script, but when i try to run it, i get an error saying .ps1 file cannot be loaded and It is not digitally signed.
Powershell.exe -ExecutionPolicy Unrestricted -File script.ps1
Please help me out to solve this issue.

A: try using:
powershell.exe -ExecutionPolicy Bypass -File script.ps1

A: Unrestricted will prompt you with a warning for downloaded files. Try using the executionpolicy Bypass. As an alternative, you could go into the properties of the file and unblock the file.

-- Unrestricted: Loads all configuration files and runs all scripts. *If you run an unsigned script that was downloaded from the Internet, you are prompted for permission before it runs.
-- Bypass: Nothing is blocked and there are no warnings or prompts.

Source: Set-ExecutionPolicy


text:
Q: How can i fix the issue of anchor attribute in safari I have an issue with an anchor tag.I am using 619-618-1660 in my website , and the problem is when i check my website on safari browser or an iPhone the text written in (href="tel:619-618-1660") is showing.You can check the image in below link.

A: Add this meta tag to the top of your html
<meta name="format-detection" content="telephone=no">
Previously asked here

A: The Issue has been resolved , there is a file with the name of print.css with this code.
body{background:white !important;color:black !important;}#nav,#sidebar,.sidebar,#skip{display:none;}#content{width:100%;float:none;background:transparent;}a:not(.logo a){font-weight:bold;text-decoration:underline;color:#06c;}a:not(.logo a):after{content:" [" attr(href) "] ";}p{font-size:14px;}#printOnlyMessage{display:block !important;}
and in this code that produces an error is
a:not(.logo a):after{content:" [" attr(href) "] ";}
so I remove this code and the error is resolved.


text:
Q: svg rounded-corner clipping in firefox (works fine in ie9 and chrome) I would really appreciate it if someone could help me with the following problem:
When rounded corners are added to svg canvas, both chrome and ie9 perform the clipping correctly. Firefox (v13.0), however, ignores the rounded corners. I could do the clipping manually in svg, but I wonder if there is a better solution.
Here is the code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <svg id="paper" version="1.1" width="300" height="300" style="border-radius: 20px; background-color: red;">
        <rect x="0" y="0" width="400" height="400" fill="blue">
    </svg>
</body>
</html>

Thanks!

A: You could also just make the svg rect have the same rounded corners.
<svg id="paper" version="1.1" width="300" height="300" style="border-radius: 20px; background-color: red;">
  <rect id="background" width="100%" height="100%" rx="20" fill="red"/>
</svg>

Or if you need the clipping, something like what you suggested:
<!DOCTYPE html>
<html>
<body>
<svg id="paper" version="1.1" width="300" height="300" clip-path="url(#clip)">
    <defs>
        <clipPath id="clip">
            <rect id="background" width="100%" height="100%" rx="20" fill="red"/>
        </clipPath>
    </defs>
    <rect width="100%" height="100%" fill="red"/>
</svg>
</body>
</html>


text:
Q: Using Visual Studio for Ubuntu?
Possible Duplicate:
What IDEs are available for Ubuntu?

I would like to make programs in C++ for Ubuntu and Windows. I will be using visual studio on a Windows PC for the programming. I know how to make the install files for Windows.
I just need to know how to make the files Linux uses for programs in Visual Studio?
If you don't know visual studio could some one tell be the extensions used on install files or runnable executable(for Linux).

A: I have had some experience in cross platform programming. To begin with Visual Studio, code built on visual studio will not run inherently as the binaries compiled from Visual Studio wont be supported. You might try to develop in C# using Visual studio and then can use mono libraries to run that code on linux but wont recommend it at all. Another way would be to use gcc and compile ur code using mingw of cygwin on windows and use that compiled code on  windows and use gcc compiler to get binaries in linux. As for ide which is available for both the operating systems I would suggest Eclipse.
But if you want a good suggestion for cross platform development, then you should focus on all the operating systems independently as each have major differences.
Further with respect to qt, they again use mingw/cygwin (for windows) and generic linux libraries so you can consider them too (they give some good functional libraries too). Its just depends on what you are building!

A: Visual c++ is not cross platform, If you prefer cross platform application creation from visual studio try qt plugin for visual studio

A: Or look at the Eclipse IDE for C/C++ Developers.  http://www.eclipse.org/downloads/packages/eclipse-ide-cc-developers/junosr1


text:
Q: how to print a string with numbers in r I have two vectors that i am calculating mean and sd for and i want to print the results in a separate line for each vector
t1<-c(37.96, 37.67,  32.29, 37.67, 38.52, 38.52, 37.67, 38.24, 36.54, 41.07, 38.81, 33.71, 37.11, 45.89)
t2<-c(51.84, 49.57, 46.45, 50.14, 50.42, 52.4, 49, 49, 49.57, 53.54, 49.57, 46.17, 50.14, 57.22)
mean(t1)
sd(t1)
mean(t2)
sd(t2)

The result should be

37.97643±3.127839
50.35929±2.801649

A: You can use sprintf:
sprintf("%f±%f", mean(t1), sd(t1))
# [1] "37.976429±3.127839"

sprintf("%f±%f", mean(t2), sd(t2))
# [1] "50.359286±2.801649"

A: You can also use cat:
cat (mean(t1),"±",sd(t2),"\n")
# [1] 37.97643 ± 2.801649

cat (mean(t2),"±",sd(t2),"\n")
# [1] 50.35929 ± 2.801649


text:
Q: Simple onclick page loader I made this really basic startup page in HTML that has images that reference websites. Is there a way to add a loader after the user clicks on the image then the loader goes away when the website comes up? I am trying to give users something to look at while a website loads. Below is a sample href line that I use.

I found this onclick script online but I do not know how to add it to my startup page. Can anyone help me put these together? Where should I place the line 'onclick="myFunction()?"'Thank you!
 onclick="myFunction()"

A: Here is an example of something you need,.
A loader will be displayed when you click on the button, and disappears after the website loads.

<!DOCTYPE html>

Click me

This is a loader

Here is a working DEMO

A: You may refer to the following link, it properly explains, how it is too be done.
http://blog.teamtreehouse.com/learn-asynchronous-image-loading-javascript


text:
Q: Uninitialized constant in Ruby I'm trying to work through this tutorial for Ruby, on CodeAcademy. The following code is giving me the error
"uninitialized constant List::Task (NameError)
    from to_do.rb:2:in main"
I understand that this may be related to the List class not being able to access the Task class, but I can't see where this would be breaking down? The code is below.
   #list class

   class List
    attr_reader :all_tasks
    if __FILE__ == $PROGRAM_NAME
      my_list = List.new
      puts 'You have created a new list'
      my_list.add(Task.new('Make Breakfast'))
      puts 'You have added a task to the Todo List'
   end

   def initialize
    @all_tasks = []
   end

 def add(task)
  @all_tasks << task
 end

 end

 #class task

 class Task
  attr_reader :description

  def task_item(desription)
   @new_item = description
  end
end

A: At the moment you run this line
my_list.add(Task.new('Make Breakfast'))

Task hasn't been defined. That happens a few lines later.
Just swap the definitions of the Task and the List class.

A: When you run that file from the command line as a script, order of declaration is important. If you move the declaration of Task above List you'll find that it will fix the error in question.


text:
Q: .NET Html viewer/web browser control alternatives I m currently using the IE ActiveX (web browser) control in .NET to show HTML inside my application, but it is VERY SLOW (loads of virtual memory eating), and very limited and I would like to swop this out with a fully managed HTML viewer.
This is a different request to Is there any better web browser control in C# (.NET)? as that is about other embedded browsers (Firefox/Gecko). I do not want to embed a browser, I want a  properly managed control.

Update (13 Apr 2011): This post by Jeff Atwood explains part of the reasoning, for those unclear why this is important/needed.

A: After finding Jeff's post I scrolled through the mess of comments and found HTMLRenderer, which is a codeplex solution. It has CSS 2.1 support plus HTML 4.1 support and is free & OSS (BSD LIcense). The code is a mess unfortunately, but there is only one part which is really worrisome the rest can be cleaned up.

A: I think that good way to go is to use Webkit port for .NET
http://webkitdotnet.sourceforge.net/
More info about Webkit itself:
http://en.wikipedia.org/wiki/WebKit

A: You just arent going to find one.
The complexity of writing a browser, especially in this competative market, is massive.
What you could possibly try, is running a pure Java web browser in .Net, by using iKVM
Ideally, one of these browsers, ported to .net would be great, but I cant find any reference to that either.
Two pure Java browsers:

*

*HotJava

*Lobo


text:
Q: Why can I not mutably borrow a variable in two different map functions? I have an iterator in Rust that loops over a Vec<u8> and applies the same function at two different stages. I do this by chaining a couple of map functions together. Here is the relevant code (where example, example_function_1, and example_function_2 are stand-in variables and functions respectively):
NOTE: example.chunks() is a custom function! Not the default one on slices!
let example = vec![0, 1, 2, 3];
let mut hashers = Cycler::new([example_function_1, example_function_2].iter());

let ret: Vec<u8> = example
        //...
        .chunks(hashers.len())
        .map(|buf| hashers.call(buf))
        //...
        .map(|chunk| hashers.call(chunk))
        .collect();

Here is the code for Cycler:
pub struct Cycler<I> {
    orig: I,
    iter: I,
    len: usize,
}

impl<I> Cycler<I>
where
    I: Clone + Iterator,
    I::Item: Fn(Vec<u8>) -> Vec<u8>,
{
    pub fn new(iter: I) -> Self {
        Self {
            orig: iter.clone(),
            len: iter.clone().count(),
            iter,
        }
    }

    pub fn len(&self) -> usize {
        self.len
    }

    pub fn reset(&mut self) {
        self.iter = self.orig.clone();
    }

    pub fn call(&mut self, buf: Bytes) -> Bytes {
        // It is safe to unwrap because it should indefinietly continue without stopping
        self.next().unwrap()(buf)
    }
}

impl<I> Iterator for Cycler<I>
where
    I: Clone + Iterator,
    I::Item: Fn(Vec<u8>) -> Vec<u8>,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<I::Item> {
        match self.iter.next() {
            next => next,
            None => {
                self.reset();
                self.iter.next()
            }
        }
    }

    // No size_hint, try_fold, or fold methods
}

What confuses me is that the second time I reference hashers it says this:
error[E0499]: cannot borrow `hashers` as mutable more than once at a time
  --> libpressurize/src/password/password.rs:28:14
   |
21 |         .map(|buf| hashers.call(buf))
   |              ----- ------- first borrow occurs due to use of `hashers` in closure
   |              |
   |              first mutable borrow occurs here
...
28 |         .map(|chunk| hashers.call(chunk))
   |          --- ^^^^^^^ ------- second borrow occurs due to use of `hashers` in closure
   |          |   |
   |          |   second mutable borrow occurs here
   |          first borrow later used by call

Shouldn't this work because the mutable reference is not used at the same time?
Please let me know if more info/code is needed to answer this.

A:         .map(|buf| hashers.call(buf))

You're probably thinking that in the above line, hashers is mutably borrowed to call it. That's true (since Cycler::call takes &mut self) but it's not what the compiler error is about. In this line, hashers is mutably borrowed to construct the closure |buf| hashers.call(buf), and that borrow lasts as long as the closure does.
Thus, when you write
        .map(|buf| hashers.call(buf))
        //...
        .map(|chunk| hashers.call(chunk))

you are constructing two closures which live at the same time (assuming this is std::iter::Iterator::map) and mutably borrowing hashers for each of them, which is not allowed.
This error is actually protecting you against a side-effect hazard: it's not obvious (in a purely local analysis) what order the side effects of the two call()s will be performed in, because the map()s could do anything they like with the closures. Given the code you wrote, I assume you're doing this on purpose, but the compiler doesn't know that you know what you're doing.
(We can't even predict what the interleaving will be just because they're iterators. Inside of your //... there could be, say a .filter() step which leads to hashers.call(buf) being called several times between each call to hashers.call(chunk), or something else that produces a different number of outputs than inputs.)
If you know that you want the interleaving of side-effects that is "whenever either map() decides to call it", then you can gain that freedom with a RefCell or other interior mutability, as dianhenglau's answer demonstrates.

A:
Shouldn't this work because the mutable reference is not used at the same time?

No. The rules of references stated that "At any given time, you can have either one mutable reference or any number of immutable references", no matter if it is or isn't used at the same time. See this answer for the reason behind the rules.
As for workaround, since you're sure that the mutations do not occur simultaneously, you can use std::cell::RefCell as explained in this chapter. Modify the code into:
use std::cell::RefCell;

let example = vec![0, 1, 2, 3];
// Remove the "mut", wrap Cycler in RefCell.
let hashers = RefCell::new(Cycler::new([example_function_1, example_function_2].iter()));

let ret: Vec<u8> = example
    //...
    .chunks(hashers.borrow().len())
    // Borrow hashers as immutable inside the closure, then borrow the Cycler as mutable.
    .map(|buf| hashers.borrow_mut().call(buf))
    //...
    .map(|chunk| hashers.borrow_mut().call(chunk))
    .collect();


text:
Q: Get all the rows from query result I have a stored procedure that returns a boolean. (0 or 1). It returns multiple rows. my question is how to iterate through all the result.
  using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBReader"].ConnectionString))
  {
       using (SqlCommand com = new SqlCommand("Reader.usp_CheckerIsStopped", con))
       {
           com.CommandType = CommandType.StoredProcedure;
           com.Parameters.Add("@fld_UserID", SqlDbType.Int).Value = this.UserID;

           con.Open();
           SqlDataReader dr = com.ExecuteReader();

           if (dr.Read() == 1)
           {
               return true;
           }
           else
           {
               return false;
           }
      }
  }

It has a error in dr.Read() == 1
Error:

Operator == cannot be applied to type bool to int"

My stored procedure returns multiple rows containing 0 or 1,I want to get those values because I want to do a checking if it is equals to true of false (0 or 1)
   if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //if (e.Row.Cells[11].Text == "In Progress")
            //{
            //    System.Web.UI.WebControls.ImageButton StartImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[1].FindControl("StartImageButton");
            //    StartImageButton.Visible = false;
            //}
            gvfunct.UserID = Convert.ToInt32(Session["UserID"]);
            gvfunct.CheckIsStopped();
            if (gvfunct.CheckIsStopped() == true)
            {
                System.Web.UI.WebControls.ImageButton StartImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[2].FindControl("StartImageButton");
                StartImageButton.Visible = true;
                System.Web.UI.WebControls.ImageButton StopImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[1].FindControl("StopImageButton");
                StopImageButton.Visible = false;
            }
            else
            {
                System.Web.UI.WebControls.ImageButton StopImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[1].FindControl("StopImageButton");
                StopImageButton.Visible = true;
                System.Web.UI.WebControls.ImageButton StartImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[2].FindControl("StartImageButton");
                StartImageButton.Visible = false;
            }

        }

A: You'll need to continue to Read() and do something with those results.
while (dr.Read())
{

}

You see, the Read() method returns a bool. So, now if you wanted to get to the results of each row you might do something like this:
while (dr.Read())
{
    var val = dr.GetInt32(0);
}

and that would get the value of the first column, from the row you're currently on in the Read(), and cast it as an int. Of course that line could throw an error if you're trying to cast a string or something. Consider the fact that a DataReader is a read-only, forward-only, buffer of data. It literally only pulls one row of data at a time from the server, thus leaving the connection open during the duration of the Read() operation and until it goes out of scope.

A: As dr.Read() returns bool thus you are getting error when comparing with int
It will return true if SqlDataReader has rows otherwise false.
So change you code as
return dr.Read();

instead of
if (dr.Read() == 1)
{
   return true;
}
else
{
   return false;
}

A: Replace
if (dr.Read() == 1)
{
    return true;
}

with
 if (dr.Read())
 {
    return true;
 }

A: you need to explicitly cast it or just use it's proper Boolean type
so instead of if (dr.Read() == 1), you may use if (dr.Read() == true) or if (dr.Read())
there isn't a direct cast that i am aware of, for instance (bool)1 is not going to work, but you may always use Convert.ToBoolean(1) or some other methods to convert it
you may also create your own custom casting method
IntToBool (int bool)
{
  if(bool == 1) return true;
  return false;
}

A: It's not really clear what your stored procedure returns, but if the first row and first column contains for example an integer, you could also forget the reader and use SqlCommands ExecuteScalar-method like so:
return com.ExecuteScalar() == 1;

A: If you need to iterate through all the rows, try this
if(dr.Read()){
 if(dr.Read()) return true;
 else return false;
}
else return false;

This will read dr twice and return true if it finds 2 rows. False if it finds 0 or 1 row.


text:
Q: What does this quote about the four dimensional divergence of an antisymmetric tensor mean?
In the beginning, God said that the four dimensional divergence of an antisymmetric second rank tensor equals zero and there was light.

Can someone explain what is the meaning of this quote by Michio Kaku?

A: The antisymmetric second-rank tensor being referenced is the electromagnetic field tensor. It is defined as follows. Let $\varphi$ be the electrostatic potential (a scalar field), and let $\underline{A}$ be the magnetic potential (a 3-vector) from classical E&M. Concatenate them into a 4-vector $\vec{A}$. Now define the tensor of interest as the exterior derivative of $\vec{A}$:
$$ \mathbf{F} = \mathrm{d}\vec{A}. $$
We can write this component-wise with partial derivatives:
$$ F_{\mu\nu} = \partial_\mu A_\nu - \partial_\nu A_\mu. $$
You can see that if thought of as a matrix, the components $F_{\mu\nu}$ of $\mathbf{F}$ are antisymmetic.
Now the use of this is that the four equations that govern classical electromagnetism (and hence light) are equivalent to:
$$ \partial_\nu F^{\mu\nu} = J^\mu $$
($\vec{J}$ is the 4-current composed of electric charge concatenated with 3-current) and
$$ \partial_{[\alpha} F_{\mu\nu]} = 0 $$
(the brackets denote the summing all permutations of indices with a sign given by the parity of the permutation).

Note that depending on your unit system there may be constants like $c$ or $\mu_0$ floating around in these equations.

A: From this transcript, the full quote is

And so, if you go to Berkley, where I got my PhD, you can buy a t-shirt which says, "In the beginning God said, the four-dimensional divergence of an antisymmetric, second rank tensor equals zero, and there was light, and it was good.  And on the seventh day he rested."  Ladies and gentlemen, this is the equation for light.

A rank two tensor is commonly known as a matrix, and a rank one tensor is commonly known as a vector.
An anti-symmetric tensor is a tensor in which exchanging two indices negates the tensor; for example $a_{ji}=-a_{ij}$.
According to Wikipedia, the divergence of a second order (rank) tensor is a first order (rank) tensor (I've extrapolated the result there to four dimensions)
$$
\nabla\cdot\epsilon=\begin{bmatrix}
\frac{\partial\epsilon_{xx}}{\partial x}+\frac{\partial\epsilon_{yx}}{\partial y}+\frac{\partial\epsilon_{zx}}{\partial z}+\frac{\partial\epsilon_{wx}}{\partial w}\\
\frac{\partial\epsilon_{xy}}{\partial x}+\frac{\partial\epsilon_{yy}}{\partial y}+\frac{\partial\epsilon_{zy}}{\partial z}+\frac{\partial\epsilon_{wy}}{\partial w}\\
\frac{\partial\epsilon_{xz}}{\partial x}+\frac{\partial\epsilon_{yz}}{\partial y}+\frac{\partial\epsilon_{zz}}{\partial z}+\frac{\partial\epsilon_{wz}}{\partial w}\\
\frac{\partial\epsilon_{xw}}{\partial x}+\frac{\partial\epsilon_{yw}}{\partial y}+\frac{\partial\epsilon_{zw}}{\partial z}+\frac{\partial\epsilon_{ww}}{\partial w}
\end{bmatrix}
$$
As for the physical meaning, that is more a topic for physics.

A: It is similar to the t-shirt designs of a couple decades ago with Maxwell' Equations in place of "Let there be light" in the famous biblical quote, except this time some designer decided to use the slick spacetime tensor way of describing electromagnetic fields.  In relativity, the electromagnetic field is described by a 4D antisymmetric tensor.  Its divergence, meaning the antisymmetrized derivative, is zero in vacuum.  (It's nonzero at charges and currents, but I guess God didn't invent charge until the next day.)


text:
Q: Error in using accuracy_score from sklearn I am doing planar data classification using logistic regression. An error is occured after importing accuracy score. Why didnt it work? This answer suggested that accuracy score is used to estimate accuracy.The last line and third last line of code must give same answer. But third last line of code only gave actual answer(i.e 47% accurate LR). I also applied this code
    score= accuracy_score(Y,LR_predictions)
But i got an error: too many indices
 import numpy as np
import matplotlib.pyplot as plt
from testCases_v2 import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
from sklearn.metrics import accuracy_score

X, Y = load_planar_dataset()

plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);

plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")

# Print accuracy
LR_predictions = clf.predict(X.T)
print(LR_predictions)
print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
       '% ' + "(percentage of correctly labelled datapoints)")
score= accuracy_score(Y,LR_predictions)
print(score)

ValueError                                Traceback (most recent call last)
<ipython-input-8-0f3a55d2e963> in <module>()
      8 print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
      9        '% ' + "(percentage of correctly labelled datapoints)")
---> 10 score= accuracy_score(Y,LR_predictions)
     11 print(score)

/opt/conda/lib/python3.6/site-packages/sklearn/metrics/classification.py in accuracy_score(y_true, y_pred, normalize, sample_weight)
    170
    171     # Compute accuracy for each possible representation
--> 172     y_type, y_true, y_pred = _check_targets(y_true, y_pred)
    173     if y_type.startswith('multilabel'):
    174         differing_labels = count_nonzero(y_true - y_pred, axis=1)

/opt/conda/lib/python3.6/site-packages/sklearn/metrics/classification.py in _check_targets(y_true, y_pred)
     70     y_pred : array or indicator matrix
     71     """
---> 72     check_consistent_length(y_true, y_pred)
     73     type_true = type_of_target(y_true)
     74     type_pred = type_of_target(y_pred)

/opt/conda/lib/python3.6/site-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
    179     if len(uniques) > 1:
    180         raise ValueError("Found input variables with inconsistent numbers of"
--> 181                          " samples: %r" % [int(l) for l in lengths])
    182
    183

ValueError: Found input variables with inconsistent numbers of samples: [1, 400]

A: Change the shape of Y to (n_samples,) that is required for accuracy_score method. Just try a code as follows:
Y = Y.reshape(1,-1)


text:
Q: Can we assign custom Query Hints to JPA NamedQueries We are required  to append query numbers to each and every query our application executes.
EX:  SELECT * FROM ... WHERE ... QUERYNO 123456;
OpenJPA supports query hints, but only for specific hints on specific implementations.
...
Query q = em.createQuery("select m from Magazine m where ... ");
q.setHint("openjpa.hint.OptimizeResultCount", new Integer(2));
q.setHint("openjpa.FetchPlan.ReadLockMode","WRITE");
List r = q.getResultList();
...

But according to the JPA spec, and openjpa "Invalid hints or hints which can not be processed by a particular database are ignored. Otherwise, invalid hints will result in an ArgumentException being thrown."
SO specifycing "QUERYNO" as a hint seems to have no impact.
How do I create a custom Query Hint to specify at runtime?
...
Query q = em.createQuery("select m from Magazine m where ... ");
q.setHint("com.me.CustomQueryNoHint", new Integer(2234));
List r = q.getResultList();
...

A:
specifying "QUERYNO" as a hint seems to have no impact.

Correct. Per the doc that you quoted, "QUERYNO" is an invalid hint so it is ignored. The doc is somewhat confusing, but I believe if can be interpreted to support the behavior that you observed. :-)

How do I create a custom Query Hint to specify at runtime?

That is a much taller task. I don't believe that OpenJPA was designed to allow writing custom query hints.
I thought some more about your actual problem of wanting to append a specific string to EVERY SQL and I don't think it would be very easy to do in OpenJPA. Perhaps you could write a wrapper for your JDBC driver and have that append your string to every SQL?

A: Not complete answer but just a pointer...
QueryCounter
public class QueryCounter {
    private static long COUNTER = 0;

    private static long next() {
        return ++COUNTER;
    }

    private static String getHintValue() {
        return "/*Query No. " + next() + " */";
    }

    public static void setQueryCount(Query query) {
        /* EclipseLink */
        //query.setHint(QueryHints.HINT, getHintValue());
            query.setHint("eclipselink.sql.hint", getHintValue());

        /* OpenJPA + Oracle */
        //query.setHint("openjpa.hint.OracleSelectHint", getQueryHint());

        /* OpenJPA + MySQL */
        //query.setHint("openjpa.hint.MySQLSelectHin", getQueryHint());
    }
}

Usage
Organization sun = new Organization("Sun");
        em.persist(sun);
        tx.commit();
        Assert.assertNotNull(sun.getEntityId());

        Query query = em.createQuery("SELECT org.entityId FROM Organization org WHERE org.entityId = " + sun.getEntityId());
        QueryCounter.setQueryCount(query);
        query.getResultList();

        /*ServerSession does NOT log ReadObjectQuery??*/
        query = em.createQuery("SELECT org FROM Organization org WHERE org.entityId = " + sun.getEntityId());
        QueryCounter.setQueryCount(query);
        query.getResultList();

        query = em.createQuery("SELECT org.entityId FROM Organization org WHERE org.entityId = " + sun.getEntityId());
        QueryCounter.setQueryCount(query);
        query.getResultList();

Console
[EL Finest]: 2010-11-20 19:06:16.45--UnitOfWork(717879615)--Thread(Thread[main,5,main])--Execute query ReportQuery(referenceClass=Organization sql="SELECT entity_id FROM organization_tt WHERE (entity_id = ?)")
[EL Fine]: 2010-11-20 19:06:16.475--ServerSession(699542937)--Connection(1949550475)--Thread(Thread[main,5,main])--SELECT /*Query No. 1 */ entity_id FROM organization_tt WHERE (entity_id = ?)
    bind => [1]
[EL Finest]: 2010-11-20 19:06:23.372--UnitOfWork(717879615)--Thread(Thread[main,5,main])--Execute query ReadObjectQuery(referenceClass=Organization sql="SELECT entity_id, name FROM organization_tt WHERE (entity_id = ?)")
[EL Finest]: 2010-11-20 19:06:35.916--UnitOfWork(717879615)--Thread(Thread[main,5,main])--Execute query ReportQuery(referenceClass=Organization sql="SELECT entity_id FROM organization_tt WHERE (entity_id = ?)")
[EL Fine]: 2010-11-20 19:06:35.92--ServerSession(699542937)--Connection(1949550475)--Thread(Thread[main,5,main])--SELECT /*Query No. 3 */ entity_id FROM organization_tt WHERE (entity_id = ?)
    bind => [1]

OpenJPA has similar concept 1.8.7. Database-Specific Hints.
See if these specific hints can solve your purpose.
UPDATED ANSWER
@Eddie, see if this can help you...........
CustomLogFactory
    public class MyLogFactory extends org.apache.openjpa.lib.log.LogFactoryImpl {

    /* copied from LogFactoryImpl.NEWLINE */
    private static final String NEWLINE = J2DoPrivHelper.getLineSeparator();

    private boolean sqlLogger;

    @Override
    public Log getLog(String channel) {
        if("openjpa.jdbc.SQL".equals(channel)) { // OR equalsIgnoreCase(channel) ???
            sqlLogger = true;
        }
        return super.getLog(channel);
    }

    @Override
    protected LogImpl newLogImpl() {
        if(sqlLogger) {
            sqlLogger = false; /* once an SQL Logger is created, we dont't need any more instances */
            return new LogImpl() {
                private long sqlCounter = 0;

                @Override
                protected String formatMessage(short level, String message, Throwable t) {
                    if(isSQLString(message)) {
                        StringBuffer formattedMessage = new StringBuffer(super.formatMessage(level, message, t));
                        StringBuffer queryNo = new StringBuffer();
                        queryNo.append("  [Query # ").append(++sqlCounter).append("]").append(NEWLINE);
                        formattedMessage.delete(formattedMessage.length() - NEWLINE.length(), formattedMessage.length());
                        formattedMessage.append(queryNo);
                        return formattedMessage.toString();
                    }
                    return super.formatMessage(level, message, t);
                }

                /* just a sample implementation; checks whether message contains the word "executing"
                 * more concrete implementation should check the message for SELECT, UPDATE, INSERT INTO, ALTER.... clauses */
                private boolean isSQLString(String message) {
                    if(message.contains("executing")) {
                        return true;
                    }
                    return false;
                }

            };
        }
        return super.newLogImpl();
    }

}

peristence.xml
<property name="openjpa.Log" value="org.opensource.logger.MyLogFactory(DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE)"/>

Test
EntityManager em = Persistence.createEntityManagerFactory("default").createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Person person = new Person();
person.setName("Bond-OO7");
person.setAge(22);
em.persist(person);
tx.commit();
em.close();

Console
............
2084  default  TRACE  [main] openjpa.jdbc.SQL - <t 346613126, conn 1551158018> executing prepstmnt 556472773 SELECT SEQUENCE_OWNER AS SEQUENCE_SCHEMA, SEQUENCE_NAME FROM ALL_SEQUENCES  [Query # 1]
2136  default  TRACE  [main] openjpa.jdbc.SQL - <t 346613126, conn 1551158018> [52 ms] spent
2305  default  TRACE  [main] openjpa.jdbc.SQL - <t 346613126, conn 2026561073> executing prepstmnt 6637010 INSERT INTO Person (id, age, name) VALUES (?, ?, ?) [params=?, ?, ?]  [Query # 2]
2306  default  TRACE  [main] openjpa.jdbc.SQL - <t 346613126, conn 2026561073> [1 ms] spent
............

Reference

A: Rather than use JPQL and try to force vendor-specific stuff into the query, have you considered writing a native query that is mapped to an entity return type?
em.createNativeQuery(YOUR_DB2_NATIVE_SQL_QUERY_STRING, Magazine.class)

It will be more work for you since your native query needs to select column values that match up with the mapped columns in the entity class, but it should work. When you use native SQL the query engine must not parse and interpret vendor-specific
SQL, so your DB2-specific clause at the end should be passed through to the underlying database at runtime.


text:
Q: C# Getting methods with attribute in abstract class I'm trying to get methods from which have a specific Callback attribute inside the constructor of an abstract class. The challenge here is that I also want the methods from the concrete class which have this attribute.
My abstract class:
public abstract class BaseScript
{
    protected readonly CallbacksDictionary Callbacks;

    protected BaseScript(CallbacksDictionary callbacks)
    {
        // Get all methods with the [Callback] attribute including the concrete instance
        var methodsWithCallbackAttr = // ?
    }
}

public class SomeScript : BaseScript {
    public SomeScript(CallbacksDictionary callbacks) : base(callbacks) { }

    [Callback("transaction")]
    internal Task<bool> Transaction(int amount) {
       // I need to get this method
    }

    internal Task<bool> GetBalance(int accountId) {
         // But not this method
    }
}

In the example above I want methodsWithCallbackAttr to be a list containing the Transaction method if the concrete instance is SomeScript i.e. I don't want all the methods from all the classes that inherit from BaseScript and have the Callback attribute.
I've tried the following. Which does not work. This only returns the methods from BaseScript which have the Callback attribute, but not the methods from SomeScript.
var callbackMethods = GetType().GetMethods()
    .Where(m => m.GetCustomAttributes(typeof(CallbackAttribute), true).Length > 0);

A: As @Dai mentioned in their comment. I needed to specify some additional binding flags because the methods I was looking for are internal and instance specific. The code now looks as follows:
var callbackMethods = GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
    .Where(m => m.GetCustomAttributes(typeof(CallbackAttribute), true).Length > 0);