text:
Q: how can JVM use more than 4gb of memory I have a request to install a Linux server (preferably Ubuntu 64bit server),
and Java (64 bit) on the following machine:

*

*Intel Core2Quad Q8200 - 2.33 GHz

*8gb DDR2 ram

*2x 320GB SATA HDD in soft RAID1 mirror (mirror)

The problem is how to configure  system and Java  because I need JVM  to use more than 4gb of memory.
It cannot be distributed on many virtual machines. There is data more than 4GB large
and it has to be in memory because HDD is slow and performance is critical.
This is a  configuration and performance question and I am  interested in comments if anyone has experience?
thank you very much for helping me on this...

A: A 64 bit JVM should have no problem at all with giant heaps, certainly much larger than your available RAM. Just increase the heap size when you start the JVM, for example:
java -Xmx6g

You used to have to specify the 64bit flag (with -d64), but I don't think this is necessary any more.
32bit JVMs can manage something like 3GB of heap.

A: skaffman's answer which provides the required flag for allocating 6GB of memory is correct. If the 'g' does not do the trick you might want to try 6000m (check the link below for details on flags/platform)
For other options you can find useful information on all available options for the Java HotSpot VM here.
http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp
(Behavioral and performance options are available. Platform specific links also available on this page)

A: JVM (especially 64bit) does not hesitate taking all the memory, and 4Gb is not a problem. Just install 64-bit Ubuntu and default-jre package will also be 64 bit.
Also take special care about how your data is stored in memory. Again, 64-bit JDK is very hungry for memory due to higher overhead for pointers etc. so if you distribute these 4Gb in small chunks in some data structure, 8Gb will not be enough.

A: If you install a 64-bit Ubuntu, I believe that
sudo apt-get install sun-java6-jdk

gives you a 64-bit Java.

EDIT:  The 64 bit Java can give you as much memory as you need with the appropriate switches.  The limit is with the 32-bit JVM's which cannot go over 2-4 Gb depending on operating system.


text:
Q: Server socket file transfer I have used server socket concept in java to transfer files like images and videos. But when i receive at the client side, i am customizing the file names. Can i get the original name of the file as it is?
For Example:
If the file from server end for transfer is "abc.txt", i need this same name to be reflected in the client end(without passing the name separately).
In the server end:
public class FileServer {
  public static void main (String [] args ) throws Exception {
    // create socket
    ServerSocket servsock = new ServerSocket(13267);
    while (true) {
      System.out.println("Waiting...");

      Socket sock = servsock.accept();
      System.out.println("Accepted connection : " + sock);
      OutputStream os = sock.getOutputStream();
    new FileServer().send(os);
      sock.close();
      }
    }

  public void send(OutputStream os) throws Exception{
      // sendfile
      File myFile = new File ("C:\\User\\Documents\\abc.png");
      byte [] mybytearray  = new byte [(int)myFile.length()+1];
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(mybytearray,0,mybytearray.length);
      System.out.println("Sending...");
      os.write(mybytearray,0,mybytearray.length);
      os.flush();
  }
}

In the client end:
    public class FileClient{
  public static void main (String [] args ) throws Exception {

    long start = System.currentTimeMillis();

    // localhost for testing
    Socket sock = new Socket("127.0.0.1",13267);
    System.out.println("Connecting...");
    InputStream is = sock.getInputStream();
    // receive file
    new FileClient().receiveFile(is);
       long end = System.currentTimeMillis();
    System.out.println(end-start);

    sock.close();
  }

  public void receiveFile(InputStream is) throws Exception{
      int filesize=6022386;
      int bytesRead;
      int current = 0;
      byte [] mybytearray  = new byte [filesize];

        FileOutputStream fos = new FileOutputStream("def");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = is.read(mybytearray,0,mybytearray.length);
        current = bytesRead;

        do {
           bytesRead =
              is.read(mybytearray, current, (mybytearray.length-current));
           if(bytesRead >= 0) current += bytesRead;
        } while(bytesRead > -1);

        bos.write(mybytearray, 0 , current);
        bos.flush();
        bos.close();
  }
}

A: For the receiver to know the file name, either:
a) it must assume it knows the name because it asked for it,
b) the server sends the name first as part of the stream.
If you invent a way to send information without actually sending it, let me know and we can become billionaires. We can call it 'computer telepathy'.

A: Yes, simply transfer the metadata (in your case myFile.getName()) before the actual file contents, and make client and server read and emit that metadata. It's a good idea to use established protocols, for example HTTP and its Content-Disposition header.

A: see this references,May be helpful...
http://www.rgagnon.com/javadetails/java-0542.html
http://www.java2s.com/Code/Java/Network-Protocol/TransferafileviaSocket.htm
http://www.artima.com/forums/flat.jsp?forum=1&thread=34857

A: There is a simpler way to do this. Just wrap your input stream inside DataInputStream and use methods like .writeUTF(myFile.getName()). Similarly, you can read file name at receiver by applying .readUTF on DataInputStream. Here is a sample code:
Sender:
FileInputStream fis = new FileInputStream(myFile);
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream(bis);
    OutputStream os;
    try {
        os = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF(myFile.getName());
.............////// catch exceptions

Receiver:
InputStream in;
    try {
        bufferSize=socket.getReceiveBufferSize();
        in=socket.getInputStream();
        DataInputStream clientData = new DataInputStream(in);
        String fileName = clientData.readUTF();
        System.out.println(fileName);
................../////// catch exceptions

redpajama_set_name: RedPajamaStackExchange


text:
Q: Function being called multiple times in React functional component Below is the component file SinglePostBySearch.js
import React, { useState } from 'react'
import Post from './Post'
const axios = require('axios')

const getElt=({loading},{isThereQuery},{posts})=>{
    console.log(posts)
    if(!loading && isThereQuery)
    {
        return(
            <Post post={posts} id={posts.id} />
        )
    }
    if(loading)
    {
        return
Loading

    }
    if(!(loading && posts))
    {
        return
No post from the user

    }
}

function SinglePostBySearch(props) {
    const [posts, setPosts] = useState({})
    const [isThereQuery,setIsThereQuery]=useState(false)
    const [loading,setIsLoading]=useState(false)
    const fetchPost = (event) => {
        const postId = event.target.value
        if (postId) {
            setIsThereQuery(false)
            setIsLoading(true)
            axios.get(`https://jsonplaceholder.typicode.com/posts/${postId}`).then(res => {
                setPosts(res.data)
                setIsThereQuery(true)
                setIsLoading(false)
            }).catch(err => {
                console.log(err)
                setIsLoading(false)
                setPosts({})
            })
        }
        else{
            setPosts({})
            setIsThereQuery(false)
        }

    }
    return (

            Hello {props.username}, enter a userId below
            <input type="text" onChange={fetchPost} />
            {getElt({loading},{isThereQuery},{posts})}

    )
}
export default SinglePostBySearch

Problem/Question: Within the functional component's return, in the third line, I'm making a call to a another function getElt. It seems to be called around 4 or 5 times, which I figured from the console.log I inserted in the first line of the getElt function. I would like to know why it's being called so many times when it should be called just once.
I would like to point out that I do not have any console log statements in the child component Post that is being returned by the function getElt

A: This is a misconception in React today. Many think that the function component won't be called if the props and state don't change. The truth is, your function may be called many times as the parent component re-renders, and React checks the old Shadow DOM to see if it matches the new Shadow DOM. What we can say, is that the JSX returned won't be updated in the real DOM if props and state haven't been changed.
What you can do to reduce the times the React engine calls you function component, is to try to keep your components from updating unnecessarily (including your parent components). Here are several things I see looking at your code:

*

*A new instance of fetchPost is created each time your function is called. This means on each execution, it will have a different memory address. It's then passed to child components as a props, meaning that every time your SinglePostBySearch component is executed, the children will be forced to render. You might have similar situations in your parent component which are causing this component to be called excessively. To avoid this, any function you pass to children as a prop should be wrapped in a useCallback so that it gets correctly memoized, and doesn't recreate a new instance each time.

*You are calling your getElt function every time your component function executes, even if the data hasn't changed. If you needed to prevent the function from executing so many times, it can be useful to either useMemo or useCallback (depending on the use case) and specify the dependencies (loading, isThereQuery, posts) in the hook's deps array. This way, the function will only be recalculated when the any of those dependencies are modified.

*You are wrapping loading, isThereQuery, and posts in an anonymous object {} each time you pass them around. This is instantiating a new object each time it sees this, which means it has a new memory address -- and will cause any children you pass it to as a prop to re-render. The useState hook already maintains the memory address of the value, so by wrapping it in a new object, you could potentially cause problems.
In React, whenever you use interpolation to bind data directly in the JSX ({getElt({loading},{isThereQuery},{posts})}), React considers this a child element. I'm not sure how the anonymous object will affect this, but it doesn't hurt to get rid of the superfluous objects wrapping each parameter, especially since you're destructuring them again in the getElt function anyway.

A: It's being rendered so many times because the variables you are passing {loading},{isThereQuery},{posts} are changing that many times. If you want to limit how many times it's called you could shortcircuit on one of the values, e.g. loading && getElt({loading},{isThereQuery},{posts}).


text:
Q: bidirectional binding on value passed as @Input to a Child I have 2 components : Parent and Child.The Child receive a Filter type as @Input from the Parent.
The Filter look like this :
export class FilterModel {
    name: string;

    constructor(name: string){
        this.name = name;
    }
}

In the Parent template I have this (the filter has been initialized in the .ts file) :
<app-child [filter]="filter"></app-child>

In the Child :
@Input() filter:FilterModel;

The values of filter are ok in the ngOnInit of the Child
  ngOnInit() {
    console.log(this.filter);
  }

I can see the value of filter in the Child template when I do this {{filter.name}}
I can see the value in the input when I do this :
<input type="text" [(value)]="filter.name" >

But when I tried to do a bidirectional data binding with [(ngModel)]:

I got this error:
Can't bind to 'ngModel' since it isn't a known property of 'input'.
The FormsModule is imported.
Do you know how solve this ?
Later in the Parent I'll subscribe to filter value to call a function when the value change.
Thanks for your help,
Update 1
/src
|
|   /app
|   |
|   |   /models (where filter is)
|   |   /pages
|   |   |
|   |   |   /Myfolder
|   |   |   |
|   |   |   |   /Child
|   |   |   |   /Parent
|   |   |   |   myfolder.module.ts
|   |   |
|   |   /services
|   |   /theme (I bought a theme)
|   |   |
|   |   |   /compononents (of the theme
|   |   |   |
|   |   |   |   /applications
|   |   |   |   /sidebar
|   |   |   |   /menu
|   |   pages.module.ts
|   |   pages.compononent.ts
|   app.modules.ts
|   app.compononent.ts

import { FormsModule } from '@angular/forms'; is present in all .module.ts
Update 2
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';

import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { DirectivesModule } from '../../theme/directives/directives.module';
import { ChildComponent } from './myfolder/child.component';
import { ParentComponent } from './myfolder/parent.component';

export const routes = [
  { path: '', redirectTo: 'XXXXX', pathMatch: 'full'},
  { path: 'parent', component: ParentComponent, data: { breadcrumb: 'XXXXX' } }
];

@NgModule({
  imports: [
    CommonModule,
    NgxDatatableModule,
    DirectivesModule,
    RouterModule.forChild(routes)
  ],
  declarations: [
    ParentComponent,
    ChildComponent
  ]
})
export class MyFolderModule { }

A: Add FormsModule into imports array.
@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    NgxDatatableModule,
    DirectivesModule,
    RouterModule.forChild(routes)
  ],
 ...
)

A: ngModel is a directive in FormsModule, to use the module you need to add it in the imports array of your NgModule, not just importing it into your script.
@NgModule({
    imports: [
    CommonModule,
    FormsModule, // add this line
    NgxDatatableModule,
    DirectivesModule,
    RouterModule.forChild(routes)
    ],
)


text:
Q: How to speed up the ftp upload process? So why are FTP uploads soo slow? I am using filezila as a client.
I have like 10 mb in 1000 files and I can upload each individual file with 300-500kb/s yet the whole upload is incredibily slow due to the queueing process that occurs as files are uploaded. For every singe file the client performs all kind of commands and connection operations before actually uploading.
Is there no way to skip over these commands? I am new to ftp clients/uploads/websites etc Is this standard practice? Is this just the way ftp uploads work? Don't you get bored waiting like 20 minutes for 8-10 mb?
How can I efficiently upload 100 mb or more?

A: Have you tried compressing the files locally then uncompressing them on the server? Then you'd only have to transfer one small(er) file.
If it's applicable, you could also only copy files that have changed since your previous upload. Tools like rsync (if you have ssh access) and robocopy (if it's a windows server) could help you do this.

A: I know this is an old post, and there isn't a lot you can do at the application layer since FTP relies on TCP for sending the bytes. There are few things though

*

*Enable simultaneous uploads as mentioned above (this helps utilize more of your bandwidth since it takes time for TCP to "ramp up" each connection, so doing it in parallel is more efficient)

*Archive the file as mentioned above (again, because it allows TCP to ramp up over time instead of individually for each file)

*Check out SuperTCP: it's a new product that (full disclosure) I'm helping build that will optimize TCP upload, which can help FTP go faster in a lot of cases. We're launching a Beta soon and would love to have you help us test it!

A: Sadly, this is the way that FTP functions. To efficiently transfer lots of small files, either archive them locally, transmit the entire archive via ftp, and then unarchive the files on the remote machine, or turn on simultaneous uploads, where the client is uploading 10 files at once. This will help to fully saturate your upload link.

A: I use Auto FTP Manager. It runs multiple simultaneous FTP transfers so the entire bandwidth link can be used:

Auto FTP Manager makes it easy to schedule and automate your FTP
  transfers.  Use Auto FTP Manager to connect to any FTP server and
  automatically upload and download files.  Plan and automate your
  workflow.  Let your PC move or synchronize files between PC to FTP
  Server, PC to PC, and FTP Server to FTP Server, automatically
  according to a schedule...
... Auto FTP Manager is multi-threaded, allowing you to open
  connections to multiple FTP servers at the same time.  The program can
  transfer files in the background while you work on other tasks.


text:
Q: Genexus 18 Upgrade 1. Gradle installation from IDE I am having difficulty downloading Gradle due to the use of an enterprise level proxy server. How is the GeneXus IDE instructed to use a proxy (explicit proxy)?
I'm using Genexus 18 Upgrade 1 with Java web generator
Regards,
Leonardo Silvestri
I tried configuring the GeneXus.Exe.config file with no favorable result. Attached here the settings used.
imagen1
imagen2


text:
Q: Subject Verb Agreement for of-phrase Four meters of cloth is/are required.
Which one is appropriate? I think it's are but I ain't sure...
I got confused because the discussion regarding the SV Agreement commonly talks about the fraction before of-phrase (like "one-half of the cake").

A: The previous answers on this topic are of limited help in that they are somewhat-confused and often contradictory.  Look to the meaning of your sentence.  If you consider your subject a collective thing that you think of as a unit, then use a singular verb.  If you consider your subject a multiple with separate identifies, then use a plural verb:

Twenty miles is the distance to the nearest city.

The twenty act together as a measure, so the verb is singluar.

The last twenty miles were increasingly difficult to travel.

Each mile was more difficult than the last and thus distinguishable from the previous, so the verb is plural.

Three milliliters is the dose the doctor prescribed.

Three milliliters is one amount that makes up a single dose, so the verb is singular.
The doctor prescribed for him one-milliliter doses of medication to be taken three times a day.  The first three milliliters were enough to cure him.
The three milliliters came separately, one at a time, so the verb is plural.


text:
Q: How can I use css for Vaadin 7 components? I've set the styleName for my component, but it doesn't appear to have any effect:
Label  label=new Label("this is test");
label.setStyleName("mytheme");

My CSS:
@import "../reindeer/styles.css";

.test{
    color: cornflowerblue;
}

.mytheme {
    font-family: 'Cabin Sketch';
    font-size: 24px;
    font-weight: bold;
    padding-top: 10px;
    padding-left: 10px;
    line-height: 30px;
}

.v-label {
    background: cyan;
}

My directory in intellij IDE: web/VAADIN/themes/mytheme
I've already seen this question, but the solution doesn't work for me.

A: input in main class:
@Theme("mytheme")

 and use in all project by component.setStyleName("Logo");


text:
Q: excel wrong date calculating I have this weird excel problem where excel won't calculate dates correctly.
I had these dates in a column A:
10/12/2012
11/12/2012
12/12/2012
13/12/2012
14/12/2012
and so on.

In column B I wanted excel to calculate the next date. Everything was fine up to 12/12/2012. After that it shows #VALUE. I thought it was a date format problem and tried every available option, but it simply won't work.

A: I find it a bit suspicious that your problem starts beyond "12".
I would not be surprised at all, if your Excel interprets what you mean as a "day" as a "month". That might be depending on your locale or the assiciated settings in Windows.
US vs. UK
MDY vs. DMY
http://en.wikipedia.org/wiki/Date_format_by_country

A: Excel might be interpreting 13/12/2012 as a string because it expects dates to be entered in the US d/m/yyyy format (12/13/2012 for 2012-Dec-13).  Try entering your dates using the three-letter abbreviation for the month instead.  Then Excel knows what you mean and you can set the format how ever you want.

A: I am able to get the values in Excel with the formula =A1+1
Click here


text:
Q: How to set up custom block in layout file? I can't setup block in advancedSearch.xml layout. My extension has name Rockstar_Chatattributes.
Here is my config.xml(just necessary nodes):
<?xml version="1.0"?>
<config>
<modules>
    <Rockstar_Chatattributes>
        <version>1.0.0</version>
    </Rockstar_Chatattributes>
</modules>
<global>
    <blocks>
        <chatattributes>
            <class>Rockstar_Chatattributes_Block</class>
        </chatattributes>
    </blocks>
</global>
<frontend>
    <routers>
        <chatattributes>
            <use>standard</use>
            <args>
                <module>Rockstar_Chatattributes</module>
                <frontName>advancedSearch</frontName>
            </args>
        </chatattributes>
    </routers>
    <layout>
        <updates>
            <chatattributes>
                <file>advancedSearch.xml</file>
            </chatattributes>
        </updates>
    </layout>
</frontend>

Here is advancedSearch.xml:
<layout version="0.1.0">
<chatattributes_index_index>
<reference name="content">
<block type="chatattributes/john" name="john" as="john" template="chatattributes/john/view.phtml" />
</reference>
</chatattributes_index_index>

here /app/design/frontend/default/mytemplate/template/chatattributes/john/view.phtml is locating my template
here is my block(app/code/local/Rockstar/Chatattributes/Block/John.php):

class Rockstar_Chatattributes_Block_John extends Mage_Core_Block_Template
{
public function logic() {
    echo 'block has been included';
}
}

So now my block just ignoring.
but when i type core/template instead chatattributes/john in advancedSearch.xml, the text in template displaying fine.

A: Check your layout version's value. It is of 0.1.0 in advancedSearch.xml and config.xml's version is of 1.0.0. I think here might be the mistake. The versions of these two files must have to be same. Change those valuesin any one of the file.


text:
Q: How to control the number of messages processing simultaneously in a single worker/consumer machine in amazon SQS? Below are the configuration of my SQS and description of my use case

*

*I am pushing ~1000 messages per minute to AWS SQS and worker machine needs ~30 seconds to process a single message and uses significant amount of RAM to process that message.

*worker machine poll the SQS for every 10 Seconds and each time it may get 10 messages.

*Since for every 10 seconds a dameon in the worker, polls the SQS, so large number of messages are end up getting parallely processed and throwing memory errors.

*SQS Queue type is, Standard.

My question how to control the number of parallel messages processed by the consumer, like at any given time only 3 message should be processed parallely?
Also even if i increase the number of consumers, some consumer may end up processing a lot of messages right? because of the worker polling SQS for every 5 seconds.
I am new to this AWS SQS, kindly correct me if i am wrong.


text:
Q: How to calculate age with years or months or days base on todays date and date of birth field in rdlc? I'm working with Registration Certificate which needed the age of the baby it could be years,months,or days. I used = DateDiff("YYYY",Fields!IssuedOnORNo.Value, Fields!CertificationDate.Value) but it only produces years same when i change it to month or day. What I want is it will compute the age of the child whether when it is a month old or a days old.

A: kindly try the t-sql code below if it works:
CREATE TABLE dbo.RegistrationCertificate (IssuedOnORNo DATETIME, CertificationDate DATETIME)

INSERT dbo.RegistrationCertificate (IssuedOnORNo, CertificationDate)
SELECT GETDATE(), DATEADD(MONTH, 13, GETDATE())
UNION ALL
SELECT GETDATE(), GETDATE() + 1
UNION ALL
SELECT GETDATE() - 2, GETDATE()
UNION ALL
SELECT GETDATE(), DATEADD(YEAR, 3, GETDATE())
UNION ALL
SELECT GETDATE(), DATEADD(MONTH, 4, GETDATE())

SELECT t.*
    , YEARS = DATEDIFF(YEAR, t.IssuedOnORNo, t.CertificationDate)
    , MONTHS = (DATEDIFF(MONTH, t.IssuedOnORNo, t.CertificationDate) - ((DATEDIFF(MONTH, t.IssuedOnORNo, t.CertificationDate) / 12) * 12))
    , DAYS = ((DATEDIFF(DAY, t.IssuedOnORNo, t.CertificationDate) - ((DATEDIFF(DAY, t.IssuedOnORNo, t.CertificationDate) / 365) * 365))
        - (((DATEDIFF(MONTH, t.IssuedOnORNo, t.CertificationDate) - ((DATEDIFF(MONTH, t.IssuedOnORNo, t.CertificationDate) / 12) * 12))) * 30) - 1)
FROM dbo.RegistrationCertificate  t WITH(NOLOCK)

btw roger, in case you're wondering how to use that code in your report, you may create a stored procedure for your report data using the code above.
EDIT:
in that case the code below should be a close enough translation for your report code:
YEARS = DateDiff("YYYY",Fields!IssuedOnORNo.Value, Fields!CertificationDate.Value)
MONTHS = (DateDiff("m", Fields!IssuedOnORNo.Value, Fields!CertificationDate.Value)
    - ((DateDiff("m", Fields!IssuedOnORNo.Value, Fields!CertificationDate.Value) / 12) * 12))
DAYS = ((DateDiff("dd", Fields!IssuedOnORNo.Value, Fields!CertificationDate.Value) - ((DateDiff("dd", Fields!IssuedOnORNo.Value, Fields!CertificationDate.Value) / 365) * 365))
        - (((DateDiff("m", Fields!IssuedOnORNo.Value, Fields!CertificationDate.Value) - ((DateDiff("m", Fields!IssuedOnORNo.Value, Fields!CertificationDate.Value) / 12) * 12))) * 30) - 1)


text: Q: Windows time runs slow I am using VPS from a web hosting provider Godaddy(windows server 2008 r2). In my VPS I found that time was running slow.The windows time clock has noticeably "losing time" as much as 8 to 10 sec within an minute.I can also notice the second hand on the analogue clock ticking longer seconds sporadically between every 5-10 seconds. Support agents informed me that there is no problem with the parent server. But a simple search in Google for "windows time runs slow" shows so many results and all state that it's problem with CMOS battery. But they are assuring that every hardware is proper. So I want to know is there any case which will cause same problem.


text:
Q: How to add code to the standard signal handler? I have a C application running on Linux where I need to add some code to the standard signal handler. The idea was to setup my handler saving the pointer to the standard one and call the saved handler from my code. Unfortunately, neither signal() nor sigaction() return pointer to the standard handler. Both of them return NULL instead.
Is there any way of doing custom handling and continuing with the standard handling without removal of the custom handler and sending the same signal again?

A: There is no "standard signal handler"; instead, there's a default action performed by the kernel when a signal is unhandled. If you want to do something when the signal is received, then defer to the default action, you can do the following at the end of your signal handler:
sigset_t set;
signal(sig, SIG_DFL);
raise(sig);
sigemptyset(&set);
sigaddset(&set, sig);
sigprocmask(SIG_UNBLOCK, &set, 0);

This is assuming you used sigaction to install your signal handler, and did not specify the SA_NODEFER or SA_RESETHAND flags. It's also possible to achieve what you want using those flags and simply calling raise, but this has ugly race conditions if the signal is delivered twice in rapid succession, so you should not do it; instead use the method I suggested.
Edit: Actually you don't have to do any of the signal mask stuff, since returning from the signal handler will restore the old signal mask. Just this should work:
signal(sig, SIG_DFL);
raise(sig);
return;

A: When the call to signal() or sigaction() returns NULL, it implies SIG_DFL (i.e. default signal handler)
If you're using signal(), the handler is supposed to be reset when the handler is called, you can issue raise(SIGNAL) as
the last line in the signal handler and it should invoke the default handler.
If you're using sigaction() then you should pass in SA_RESETHAND as one of the flags, which will allow you to use the raise(SIGNAL) call in that handler.
The vast majority of default signal handlers will terminate the application, so this 'one shot' replacement will work. You can add
a sigaction() call after the raise call to store the new handler again e.g.
void sighandler(int signum)
{
    // Do my stuff
    raise(signup);
    signal(signum, sighandler);
}


text:
Q: How to read 5 lines from text file then save the remaining lines back to this same file I have a text file with 200 lines like the following:
google
yahoo
bing
msn
soso
baidu

I want to read that text file and and get first 5 lines to array and save all remaining lines back to same text file.

A: It's pretty simple. You can exactly implement like the following code.
<?php

    $lines = file('text.txt', FILE_IGNORE_NEW_LINES);
    $five_line_array = array_splice($lines, 0, 5);

    $data = implode("\n", array_values($lines));

    $file = fopen('text.txt', "w+");
    fwrite($file, $data);
    fclose($file);

    print_r($five_line_array); // output as Array ( [0] => google [1] => yahoo [2] => bing [3] => msn [4] => soso )


text:
Q: Difference between Graphics object of getGraphics and paintComponent If I'm working with a JPanel, what's the difference between the Graphics object returned by getGraphics, and the Graphics object that is passed in paintComponent method?

A: getGraphics

*

*Can be null

*Is a "snap shot" of the last paint process

*Anything painted to it will be lost on the next paint cycle

You should avoid using getGraphics and simply use what is past to the paintComponent method.
In theory, there is no difference between them, but if you want what you have painted to survive between repaints, then you should be using paintComponent
Updated with example
Without an example code to go by I'm guessing...but...

Basically, this has a JPanel that acts as the primary "canvas" that draws an image and, when set, a Rectangle which acts as the selection.
It uses a second class as the MouseListener to actually make the decisions about what to paint
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MouseSelection {

    public static void main(String[] args) {
        new MouseSelection();
    }

    public MouseSelection() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                ImagePane imgPane = new ImagePane();
                new MouseHandler(imgPane);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(imgPane);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MouseHandler    extends MouseAdapter {

        private ImagePane imgPane;

        private Point clickPoint;

        public MouseHandler(ImagePane imgPane) {
            this.imgPane = imgPane;
            imgPane.addMouseMotionListener(this);
            imgPane.addMouseListener(this);
        }

        @Override
        public void mousePressed(MouseEvent e) {
            imgPane.clearSelection();
            clickPoint = e.getPoint();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            clickPoint = null;
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            if (clickPoint != null) {
                Point dragPoint = e.getPoint();

                int x = Math.min(clickPoint.x, dragPoint.x);
                int y = Math.min(clickPoint.y, dragPoint.y);
                int width = Math.max(clickPoint.x, dragPoint.x) - x;
                int height = Math.max(clickPoint.y, dragPoint.y) - y;

                imgPane.setSelection(new Rectangle(x, y, width, height));

            }
        }

    }

    public class ImagePane extends JPanel {

        private BufferedImage img;
        private Rectangle selection;

        public ImagePane() {
            try {
                img = ImageIO.read(new File("C:\\hold\\thumbnails\\issue459.jpg"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (img != null) {
                int x = (getWidth() - img.getWidth()) / 2;
                int y = (getHeight() - img.getHeight()) / 2;
                g2d.drawImage(img, x, y, this);
            }
            if (selection != null) {

                Color color = UIManager.getColor("Table.selectionBackground");
                g2d.setColor(color);
                Composite comp = g2d.getComposite();
                g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
                g2d.fill(selection);
                g2d.setComposite(comp);
                g2d.draw(selection);

            }
            g2d.dispose();
        }

        protected void clearSelection() {
            selection = null;
            repaint();
        }

        protected void setSelection(Rectangle rectangle) {
            selection = rectangle;
            repaint();
        }
    }

}


text:
Q: Where to get offline documentation/descriptions of individual sysctl kernel tunable parameters? The NOTES section of $ man 5 sysctl.conf states: The description of individual parameters can be found in the kernel documentation.
But is there a way for me to find this kernel documentation offline? Is it a package that I'd need to install?
For example, I came across the kernel.panic parameter, which on my system is set to 0 by default. Looking it up online here, it's described to be:
panic:

The value in this file represents the number of seconds the kernel
waits before rebooting on a panic. When you use the software watchdog,
the recommended setting is 60.

But there is no reasonable way I'd guessed that the 0 there referred to 0 seconds till auto reboot without searching it up online.

A:
But is there a way for me to find this kernel documentation offline? Is it a package that I'd need to install?

Yes, most distributions provide the kernel documentation for their kernel in a package. On Debian, this is linux-doc, which is a meta-package pulling in the default kernel's documentation for whichever release you're using (version-specific packages are available too, *e.g. linux-doc-4.19). On RHEL, CentOS etc. it's kernel-doc.
You'll find the file you're looking for in this case in /usr/share/doc/kernel-doc-*/Documentation/sysctl/kernel.txt on RHEL. In newer versions the file has been converted to ReSTructured text and can be found in .../Documentation/admin-guide/sysctl/kernel.rst (which is also where you can find the current kernel sysctl documentation on the kernel web site).
Checking the packaged version gives you a better chance to get the documentation matching your running kernel; in some cases though the current documentation is more accurate, even for older kernels, and this is the case here — I improved the documentation following Linux Kernel.org misleading about kernel panic /proc/sys/kernel/panic, and that ended up in version 5.7 of the kernel.


text:
Q: Making of the electricity I'm interested if there are actually some new electrons created in the process of Making of the electricity (turbine-generator-electricity)?
I guess (flow of the electrons in the wire - electricity) is like a chain reaction once it's started, yes?
If so, where does the electron that starts that process come from?

A: No electrons are generated. They are just set in motion.
When the wings of a turbine are set in motion, the axis combined with the generator spins. If (very simply speaking to make the logic clear) you place a magnet on this spinning axis and hold a coil of wires close, this moving magnet causes inductive forces on the wire and the electrons start moving.
No electrons are created or removed. They are simply set in motion in some way depending on how you gather and transfer your energy from the outside world and into the electrons in the wire (like the turbine you mention). The wires, wherein you want the electricity to flow, are a part of a circuit. So in some sense the electrons while moving along the wire simply go through a loop forever as long as they are kept in motion by the external force.


text:
Q: Identical Android admob unit only showing in one of two apps I have released two android apps weeks ago, each containing the same admob unit.
However, only one is showing ads, while the other does not.
I tried to create new ads units and put them on the app that not showing ads, but it was still not working. What could be a reason?

A: This is because when you set up admob ads, you can use only one app associated with admob app.

When you initialize ads, you do this:

MobileAds.initialize(this, "Your App ID");

This instructs AdMob that this app is the app which should be linked with admob and show ads, other apps with the same unit but registered after the first app will not be able to get ads available!

So, the conclusion is: you can use only one app with one admob registered app!


text:
Q: how can I collect the array heroes in my android studio project below my function is
public String[] loadIntoListView(String json) throws JSONException {
    JSONArray jsonArray = new JSONArray(json);
    String[] heroes = new String[3];
    for (int i = 0; i < 3; i++)
    {
        JSONObject obj = jsonArray.getJSONObject(i);
       // heroes[i] = obj.getString("name");
        heroes[i]= "https://static.pexels.com/photos/1543/landscape-nature-man-person-medium.jpg";
    }
    return heroes;
}

this is where i called it but it is returning null array for me
String s="";
try {
    items= loadIntoListView(s);
} catch (JSONException e) {
    e.printStackTrace();
}

A: The line JSONArray jsonArray = new JSONArray(json); may be crashing due to json not being a valid json array. This would cause the array to be null, as it hasn't been initialized yet.

A: Your exception handler out of for. If you catch exceptions in for body, you can parse verified json items. If a item not correct, you can pass.
For example,
public String[] loadIntoListView(String json) {
    JSONArray jsonArray = new JSONArray(json);
    ArrayList<String> heroes = new ArrayList();
    for (int i = 0; i < jsonArray.length; i++)
    {
        try{

           JSONObject obj = jsonArray.getJSONObject(i);
           heroes.add(obj.getString("name"));

       }catch(JSONException ignore_errors){

       }
    }
    return heroes.toArray(new String[0]);;
}


text:
Q: Embed Sawyer widget code for React component I am working on embed Sawyer widget code for one of the web page.
I have tried to put it in index.html and wrap it in Helmet inside components.
In the console, it logs "Sawyer Widget Loaded -> Hi!" but the expected UI does not show up.
Where should I put this script tag to see the preview?
<script
type='application/javascript'
data-sawyertools='sawyertools'
async
id='xyz'
src='https://hisawyer.com/embed/xyz'>
</script>```


text:
Q: Белый шум (зернистость) на черном фоне Как можно оптимизировано сделать белый шум на черном фоне?

Пробовал взять кусок изображения, background-repeat и его анимировать (как шум на старом телевизоре). Получилось то, что нужно, но сайт начинает виснуть. Есть ли более лаконичные и оптимизированные способы, чтобы такое реализовать? Возможно, с помощью js?

A: Сделал пример на js, но думаю лучше обычную гифку сделать и не нагружать браузер.

const canvas = document.getElementById('white-noise');
const ctx = canvas.getContext('2d');

ctx.canvas.height = canvas.offsetHeight;
ctx.canvas.width = canvas.offsetWidth;

render();

function render() {
  const image = ctx.createImageData(ctx.canvas.width, ctx.canvas.height);
  for (let i = 0; i < image.data.length; i += 4) {
    const color = Math.random() * 255;
    image.data[i] = color;
    image.data[i + 1] = color;
    image.data[i + 2] = color;
    image.data[i + 3] = 255;
  }
  ctx.putImageData(image, 0, 0);
  requestAnimationFrame(render);
}
#white-noise {
  width: 100%;
  height: 300px;
}
<canvas id="white-noise"></canvas>

A: Можно подготовить анимированный gif. Можно подготовить набор фоновых изображений и использовать css-анимацию.
Хорошая рекомендация выше про WebGL, есть уже готовые шейдеры:
Еще видел подобные штуки на SVG-фильтрах.
Но если уж очень хочется ограничиться JS и CSS, и использовать background, то могу предложить такое извращение (берегите глаза):

var canvas = document.createElement("canvas");
var sheet = document.getElementById('tv-css').sheet;
var ctx = canvas.getContext("2d");

let tileSize = 256;

canvas.width = tileSize;
canvas.height = tileSize;

let cssKeyFrames = [];
let frames = 16;
let array = ctx.createImageData(tileSize, tileSize);

for (let i = 0; i < frames; i++) {
  for (let j = 0; j < array.data.length;) {
    const c = ~~(Math.random() * 2) * 255;
    array.data[j++] = c;
    array.data[j++] = c;
    array.data[j++] = c;
    array.data[j++] = 255;
  }
  ctx.putImageData(array, 0, 0);

  let img = canvas.toDataURL("image/jpeg", 0.1);
  cssKeyFrames.push(~~(100 / (frames - 1) * i) +
    '% { background: url(' + img + ') repeat top left/512px 512px; }'
  );
}

let styles = '@keyframes tvShow { ' + cssKeyFrames.join('') + '}';
sheet.insertRule(styles, 1);
<style id="tv-css">
  body {
    animation: tvShow 1s infinite steps(2, end);
  }
</style>

Т.е. генерируем кадры и CSS-правила для анимации. Если сложить все изображения в файлы и самому прописать CSS, то и JS не нужен.


text:
Q: Upsert INVALID_FIELD I have a custom object which is a child object of Account.  Account has an external ID field called Customer_ID__c.  I have the following C# code which worked fine as a regular "create" when I was just inserting fields and not worrying about lookup fields.
            ChurchHist__c[] ChurchHist = new ChurchHist__c[endRecord - startRecord + 1];
            Account[] parentAccountRef = new Account[endRecord - startRecord + 1];
            Debug.WriteLine("{0} - {1}", startRecord, endRecord);
            sObject[] s = new sObject[endRecord - startRecord + 1];

            for (int i = startRecord; i <= endRecord; i++)
            {
                DataRow dr = table.Rows[i];
                int rec = i - startRecord;

                ChurchHist[rec] = new ChurchHist__c();
                ChurchHist[rec].ChurchId__c = dr["ChurchId"].ToString();
                ChurchHist[rec].ChurchName__c = dr["ChurchName"].ToString();
                ChurchHist[rec].ReportYear__c = Convert.ToInt32(dr["ReportYear"]);
                ChurchHist[rec].ReportYear__cSpecified = true;
                ChurchHist[rec].ReportMonth__c = Convert.ToInt32(dr["ReportMonth"]);
                ChurchHist[rec].ReportMonth__cSpecified = true;
                ChurchHist[rec].RegisteredMembers__c = Convert.ToInt32(dr["RegisteredMembers"]);
                ChurchHist[rec].RegisteredMembers__cSpecified = true;
                ChurchHist[rec].ActiveMembers__c = Convert.ToInt32(dr["ActiveMembers"]);
                ChurchHist[rec].ActiveMembers__cSpecified = true;
                ChurchHist[rec].InactiveMembers__c = Convert.ToInt32(dr["InactiveMembers"]);
                ChurchHist[rec].InactiveMembers__cSpecified = true;
                ChurchHist[rec].UsersForMonth__c = Convert.ToInt32(dr["UsersForMonth"]);
                ChurchHist[rec].UsersForMonth__cSpecified = true;
                ChurchHist[rec].ContribForMonth__c = Convert.ToDouble(dr["ContribForMonth"]);
                ChurchHist[rec].ContribForMonth__cSpecified = true;
                ChurchHist[rec].ContribYTD__c = Convert.ToDouble(dr["ContribYTD"]);
                ChurchHist[rec].ContribYTD__cSpecified = true;
                ChurchHist[rec].AchContrib__c = Convert.ToDouble(dr["AchContrib"]);
                ChurchHist[rec].AchContrib__cSpecified = true;
                ChurchHist[rec].CcContrib__c = Convert.ToDouble(dr["CcContrib"]);
                ChurchHist[rec].CcContrib__cSpecified = true;
                ChurchHist[rec].AchToCc__c = Convert.ToDouble(dr["AchToCc"]);
                ChurchHist[rec].AchToCc__cSpecified = true;
                DateTime eom = Convert.ToDateTime(dr["EndOfMonth"]);
                ChurchHist[rec].EndOfMonth__c = eom;
                ChurchHist[rec].EndOfMonth__cSpecified = true;
                ChurchHist[rec].MonthName__c = eom.ToString(@"MMM \'yy");

                // NEW for UPSERT
                parentAccountRef[rec] = new Account();
                parentAccountRef[rec].Customer_ID__c = dr["ChurchId"].ToString();
                ChurchHist[rec].AcctLookup__r = parentAccountRef[rec];

                s[rec] = ChurchHist[rec];
            }
            try
            {
                UpsertResult[] results = _sfConn.upsert("Customer_ID__c", s);
            }
            catch (SoapException e)
            {
                Console.WriteLine(e.ToString());
            }

I am getting error

INVALID_FIELD: Field name provided, AcctLookup__c does not match an
  External ID, Salesforce Id, or indexed field for ChurchHist__c.

Any idea what I could be doing wrong?

A: It seems like what you're trying to do is resolve the FK to account, rather than upsert your ChurchHist__c record itself, in which case you don't need to use upsert. The ability to resolve foreign keys by using the related objects external id works in create, update & upsert calls, you don't need to specicially call upsert. You seem to be setting up the FK reference ok,so you can just change your code to call create instead of upsert and you should be all set.

A: Make sure that Customer_Id__c is checked as an External ID field (Setup > Create > Objects > ChuchHist > Customer_Id__c (Edit).

A: The problem is that your external field, Customer_ID__c is on the Account, not ChurchHist__c. Your code would work for upserting Accounts, but that isn't the object you're working on. You either need to mark ChurchHist__c.Customer_ID__c as an external id or change the field being used in your upsert to one that is an external id.
** Update **
Based on @eyescream's comment, maybe your upsert field should be AcctLookup__r.Customer_Id__c?


text:
Q: setter function is being invoked seemingly every render but its not causing an infinite loop const YTPlayer = ({playlist}) => {
      const [player,setPlayer] = useState(false)
      const loadPlaylist = playlist => {
        player.loadPlaylist(playlist);
      };
      const play = () => {
        loadPlaylist(playlist);
        player.playVideo();
      };
      const pause = () => {
        player.pauseVideo();
      };

      const onReady = event => setPlayer(event.target)
      return <YoutubeIFrame onReady={onReady} />
}

The YouTube Iframe calls the onReady argument once it has loaded, which calls setPlayer. So YTPlayer should rerender, destroying the previous Iframe and creating a new one that also does the same thing. Shouldn't this cause an infinite loop?
Thats what I expected, but it doesn't behave that way. It rerenders 5 times, then stops. The play,pause,loadPlaylists functions all work fine. So What is the mistake in my thinking?


text:
Q: How to sync firebase with react functional components I would like to sync my component React  with Firebase but i use a functional component i found somes answers in internet but it's seems complicated and doesn't worked for me
and i can't use this : useEffect(() => { base.syncState('/', { context: this, state: 'messages' }) });
my code  is
import React,{useEffect, useState} from 'react'
import Formulaire from './component/Formulaire'
import Message from './component/Message'
import {useParams} from 'react-router-dom'
import database from './Base'
import { getDatabase, ref, set,onValue } from "firebase/database";

function App() {
  const [state , setState] = useState({
    messages : {},
    pseudo : useParams().pseudo,
  })
  const addMessage = (message) =>{
    state.messages[`message-${Date.now()}`] = message
    setState({pseudo : state.pseudo ,messages : state.messages})
  }

    const msg = Object.keys(state.messages)
    const lastMessages = msg.map(key=>{
      return <Message key={key} pseudo={state.messages[key].pseudo} message = {state.messages[key].message} />
    })
  return (

        {lastMessages}

      <Formulaire length={150} addMessage ={addMessage} pseudo={state.pseudo} />

  )
}

export default App

And my firebaseApp code :
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";

// TODO: Replace with your app's Firebase project configuration
const firebaseConfig = {
  apiKey: "AIzaSyB2CFjr32PoNdsnfvEgt_AijgE18lNKz2c",
  authDomain: "chat-app-42ed5.firebaseapp.com",
  projectId: "chat-app-42ed5",
  storageBucket: "chat-app-42ed5.appspot.com",
  messagingSenderId: "880643875911",
  appId: "1:880643875911:web:9d04114b45bb40c2627d62",
  measurementId: "G-MP1VZCGRDP"
};

const app = initializeApp(firebaseConfig);

// Get a reference to the database service
const database = getDatabase(app);

export default database

A: When you mount the App component, you can open a snapshot listener to RTDB, see docs. You do that in useEffect and also return a function from useEffect to destroy the listener when your component gets unmounted. It's called a "cleanup function", see React docs
It would look something like that:
function App() {
 useEffect(() => {
    const unsubListener = onValue(ref(rtdb_instance, '/YOUR_PATH'), (snapshot) => {
      // Probably iterate over `snapshot.val()` and store it in your state
    })

    // Return cleanup function
    return unsubListener;
 }, [])
}

Note that the dependency array is empty here, meaning it won't change. Hence, it will only be executed on inital mount.
Also please note that the code above is not tested, so your milage might vary.

A: I use my function writeUserData() in AddMessage function after submit message to send to REALTIME DATABASE not in UseEffect() and after to get message after refresh page i use onValue() as you say in UseEffect() and in the same time i update my state with setState()  ex:   if (data) {
setState({messages : data.messages , pseudo : state.pseudo})
} return
import React,{useState,useEffect} from 'react'
import Formulaire from './component/Formulaire'
import Message from './component/Message'
import {useParams} from 'react-router-dom'
import database from './Base'
import { ref, set,onValue } from "firebase/database";

function App() {

  const [state , setState] = useState({
    messages : {},
    pseudo : useParams().pseudo,
  })

  useEffect(()=>{
  const resultDb = ref(database);
  onValue(resultDb, (snapshot) => {
  const data = snapshot.val();
  if (data) {
    setState({messages : data.messages , pseudo : state.pseudo})
  } return
})
   return resultDb
  },[])

  function writeUserData(message) {
    set(ref(database), {
      messages :message
    });
  }

  const addMessage = (message) =>{
    state.messages[`message-${Date.now()}`] = message
    setState({pseudo : state.pseudo ,messages : state.messages})
    writeUserData(state.messages)
  }

  const msg = Object.keys(state.messages)
  const lastMessages = msg.map(key=>{
    return <Message key={key} pseudo={state.messages[key].pseudo} message = {state.messages[key].message} />
    })
  return (

        {lastMessages}

      <Formulaire length={150} addMessage ={addMessage} pseudo={state.pseudo} />

  )
}

export default App


text:
Q: Multiple-Partition Batch in Cassandra with Golang and Gocqlx I'm trying to perform a multiple-partition BATCH in Cassandra using Golang and Gocqlx.
My problem is that I can't get my BATCH statements to work properly.
My goal is as follows:
1. Perform an INSERT to second_table.
2. Perform an UPDATE to first_table.
3. Batch the above 2 operations because they need to be all-or-nothing.

I have the following table structure in Cassandra:
keyspace: mykeyspace

first_table:
    uuid
    second_table_uuid  <-- serves as a link to second_table
    create_timestamp
    update_timestamp

second_table:
    uuid
    first_table_uuid   <-- serves as a link to first_table
    create_timestamp
    update_timestamp

Below is my code:
func InsertToSecondTable(payload payload.SecondTable, session *gocql.Session) (string, error) {
    // Make sure payload UUID exists on `first_table`.
    firstTableSelectStmt, firstTableSelectNames := qb.Select("mykeyspace.first_table").
        Where(qb.Eq("uuid")).
        ToCql()

    var firstTableRow table.FirstTable

    q := gocqlx.Query(session.Query(firstTableSelectStmt), firstTableSelectNames).BindMap(qb.M{
        "uuid": payload.UUID,
    })

    // Will return a `not found` error if no matches are found.
    if err := q.GetRelease(&firstTableRow); err != nil {
        return "", err
    }

    // Prepare INSERT to `second_table` query
    now := time.Now()

    uuid, _ := gocql.RandomUUID()

    var secondTableRow table.SecondTable
    secondTableRow.UUID = uuid
    secondTableRow.CreateTimestamp = now
    secondTableRow.UpdateTimestamp = now

    // Handle UUIDs.
    secondTableRow.FirstTableUUID, _ = getUUIDFromString(payload.UUID)

    secondTableInsertStmt, secondTableInsertNames := qb.Insert("mykeyspace.second_table").
        Columns("uuid", "first_table_uuid", "create_timestamp", "update_timestamp").
        ToCql()

    // Prepare UPDATE on `first_table` query.
    firstTableUpdateStmt, firstTableUpdateNames := qb.Update("mykeyspace.first_table").
        Set("second_table_uuid", "update_timestamp").
        Where(qb.Eq("uuid")).
        ToCql()

    // Start a Batch.
    // This is because we want the INSERT and UPDATE to be all-or-nothing.
    finalStmt, finalNames := qb.Batch().AddStmt(secondTableInsertStmt, secondTableInsertNames).
        AddStmt(firstTableUpdateStmt, firstTableUpdateNames).
        ToCql()

    // Had to change the anonymous struct field names so they don't conflict.
    // Use DB tags to match the INSERT and UPDATE statements.
    batchStruct := struct {
        // second_table
        SecondTableUUIDPK          gocql.UUID `db:"uuid"`
        FirstTableUUID             gocql.UUID `db:"first_table_uuid"`
        SecondTableCreateTimestamp time.Time  `db:"create_timestamp"`
        SecondTableUpdateTimestamp time.Time  `db:"update_timestamp"`
        // first_table
        FirstTableUUIDPK    gocql.UUID `db:"uuid"`
        SecondTableUUID     gocql.UUID `db:"second_table_uuid"`
        FirstTableTimestamp time.Time  `db:"create_timestamp"`
        FirstTableTimestamp time.Time  `db:"update_timestamp"`
    }{
        // second_table
        SecondTableUUIDPK:          secondTableRow.UUID,
        FirstTableUUID:             secondTableRow.FirstTableUUID,
        SecondTableCreateTimestamp: secondTableRow.CreateTimestamp,
        SecondTableUpdateTimestamp: secondTableRow.UpdateTimestamp,
        // first_table
        MainUUIDPK:          firstTableRow.UUID,
        AdditionalDataUUID:  firstTableRow.SecondTableUUID,
        MainCreateTimestamp: firstTableRow.CreateTimestamp,
        MainUpdateTimestamp: firstTableRow.UpdateTimestamp,
    }

    err = gocqlx.Query(session.Query(finalStmt), finalNames).
        BindStruct(&batchStruct).
        ExecRelease()
    if err != nil {
        return "", err
    }

    return uuid.String(), nil
}

It's probably something super obvious, but I'm sadly new to Cassandra and Gocqlx.


text:
Q: How to pass html directly to template I want to pass HTML directly as a parameter in template().
I know I could do something like:
%for i in array:
  {{i}}
%end

but I need to pass it directly when I call template,
I tried replacing &lt and &gt with < > with javascript but that did not work.
I want to do this:
{{results_of_i_in_array}}

and the loop will occur in my main rather than in the template,
I never found anyone asking the same question.
Note: this question is NOT a duplicate of this question.
I am using bottle default templating system, thanks in advance.

A: Bottle doc:

You can start the expression with an exclamation mark to disable
  escaping
      for that expression:
>>> template('Hello {{name}}!', name='World')
u'Hello <b>World</b>!'
>>> template('Hello {{!name}}!', name='World')
u'Hello World!'


text:
Q: Mo pub + iAds in iPhone landscape game Now I got one requirement to use MoPub+iAds in iPhone game.
I used mo pub sdk and initialized view like this
MPAdView *moPubAdView =  [[MPAdView alloc] initWithAdUnitId:MOPUB_ADS_ACCOUNT_ID size:MOPUB_BANNER_SIZE];

But this displays 320x50 in size. How to enable iAd for this view? Now it is displaying only mo pub ads.

A: If you want the slim iAd banner you have to pass the correct CGSize in the size parameter. In this case CGSizeMake(480, 32).
To enable iAds for your App go to itunesconnect.apple.com and add your app with your bundle ID. After that find the Button which says iAd Network Settings and enable iAds.
The slim lanscape is rare. Your fillrate will be low. I recommend to use MMA Banner (320, 50) even for landscape orientation. Do this by using this function:
[mpAdView lockNativeAdsToOrientation:MPNativeAdOrientationPortrait];

Also be sure to import the iAd Adapter. Its by default included.


text:
Q: what does error mean and how to fix it <currentversion vob="<vobname>" label="<labal>"/>

<export vob="<vobname>" branch="<branch>" label="<label>"/>

error :

The value of attribute "v" associated
  with an element type "currentversion"
  must not contain the '<' character.

A: Replace < with < (lt=lower than) and > with > (gt = greater than) if it is not part of a tag...
<currentversion vob="<vobname>" label="<labal>"/>

A: The error message means exactly what it says, and you fix it by ensuring that all "&" and "<" characters in your data are escaped as "&" and "<" respectively.


text:
Q: Refresh or Reload modal after button click inside modal On the main page I have a datatable that includes buttons for each row. The button allows users to click and view errors specific to that object on a popup modal. Within the modal I have a button where users can clear the errors. When a user clicks one of the clearing buttons I'm having problems figuring out how to 1) refresh the modal to show the most recent content or 2) re-open the modal.
Main page button (opens modal):
 Errors

The main page button opens the modal, sends the $cluster varible and loads the content from the cluster_errors.php page.
cluster_errors.php (modal content):
<?php
if ( !empty($_GET['cluster'])) {
    $cluster = $_GET['cluster'];
}
?>

    <button type="button" class="close" data-dismiss="modal"
    aria-hidden="true">×</button>

  <?php echo $cluster;?> has errors!

            <?php echo $cluster;?> error table

                Occured
                Object
                Type
                Error
                Resolution Notes
                Resolved

              <?php
             $sql = "<sql query>";
                        $stmt = sqlsrv_query( $conn, $sql );
                        if( $stmt === false) {
                            die( print_r( sqlsrv_errors(), true) );
                        }

                        while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
                        echo'

                            '.$row['DATE_OCCURED'].'
                            '.$row['OBJECT_NAME'].'
                            '.$row['ERROR_TYPE'].'
                            '.$row['ERROR'].'
                            '.$row['RESOLUTION_NOTES'].'	';
                            echo'
                ';
                   if ( $row['RESOLVED'] == 'False') {
                   echo ' Not Resolved';
                   } else {
                   echo ' Resolved';
                   }
                   echo'

';
                    }
                    ?>

The cluster_errors.php modal fetches the $cluster variable from the previous button click and queries the database. The results are shown in another datatable in the modal. Buttons are created to clear each of the errors. The clearing buttons reach out to the cluster_resolve_error.php script.
cluster_resolve_error.php (script that clears errors):
<?php
if ( !empty($_GET['object'])) {
    $object = $_GET['object'];

}

$sql = "<SQL QUERY>";
                    $stmt = sqlsrv_query( $conn, $sql );
                    if( $stmt === false) {
                        die( print_r( sqlsrv_errors(), true) );
                    }
        $object = NULL;

        $url = parse_url($_SERVER['HTTP_REFERER']);
        $trimmedHeader = $url['scheme'] . '://' . $url['host'] . $url['path'];
        header('Location: ' . $trimmedHeader . '#' . $tab);

?>

Currently if the clearing button is clicked it updates the database and then forwards back to the main page via header('Location:. But then that forces the user to click the button on the mainpage to reopen the modal to clear more errors.
How do I refresh or reload the content after the clearing button is clicked and forward the same variables?
Thanks!

A: You can use Ajax to send request to the server when user clicks on  link and then update the "Resolved" column row using the DataTables API method cell().data().
For example:
$('#cluster_error_table').on('click', '.btn-warning', function(e){
   var cell = $(this).closest('td');

   $.get($(this).attr('href'), function(){
      // Update "Resolved" column
      $('#cluster_error_table').DataTable().cell(cell).data(
         ' Resolved'
      );
   });

   e.preventDefault();
});


text:
Q: Chrome shows ERR_CERT_COMMON_NAME_INVALID when firefox is happy Learning how to work with certificates, maybe will have local CA server. I have server with BMC, so I used it for practicing. Generated CA pair then host pair and then signed host CSR with CA pair to get host crt. I uploaded CA crt to chrome trusted keys repository and host pair to BMC.
Now when I go to the server, I can see that BMC returns correct crt, but chrome shows that connection is not secure. Reason is ERR_CERT_COMMON_NAME_INVALID.
However when I click to "Certificate is not valid" I can see both keys and signed certificate is shown as "This certificate is OK.". DNS name used in url = COMMON name. At the same time, for Firefox no problem, it is good with my certs. What may be wrong?
Used this sequence:
#CA PRIVATE
openssl genrsa -out CAKEY.pem 2048

#CA CERTIFICATE (used in browser). Common name: ca.mydomain.com
openssl req -x509 -sha256 -new -nodes -key CAKEY.pem -days 3650 -out CACERT.pem -addext "subjectAltName = DNS:ca.mydomain.com"

#HOST KEY (uploaded to BMC), I need to turn off here password protection, BMC doesn't like password
openssl genrsa -out HOSTKEY.pem 2048

#HOST CSR. Common name: host1.mydomain.com
openssl req -new -key HOSTKEY.pem -out HOSTCSR.pem -addext "subjectAltName = DNS:host1.mydomain.com"

#SIGN (uploaded to BMC)
openssl x509 -req -CA CACERT.pem -CAkey CAKEY.pem -in  HOSTCSR.pem -out HOSTCRT.PEM -days 3650 -CAcreateserial

A: OpenSSL's x509 command doesn't copy the extension from the CSR file to the signed certificate in version 1.1.1 and earlier.
On the latest version there's the -copy_extensions <arg> option, where ` can be none, copy or copyall.
You're getting the message in Chrome, because your certificate hasn't got the Subject Alternative Name (SAN) extension copied, so it complains. I believe Firefox retains the use of the Subject's CommonName if no Subject Alternative Name extension exists, which is why it doesn't complain.
You can work around this by pointing the x509 command to another config file with the -extfile <file> and the -extensions <section> options.  The file <file> just needs to have a named section with the extensions you want to add to the certificate:
[ my_ext ]
subjectKeyIdentifier    = hash
authorityKeyIdentifier  = keyid:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = host1.mydomain.com


text:
Q: Prepared statement with an array field PostgreSQL&PHP Having the following table:
CREATE TABLE submission (
    num SERIAL,
    user_id INTEGER NOT NULL,
    assignment_id INTEGER NOT NULL,
    timestamp TIMESTAMP,
    lti_info TEXT[][],
    PRIMARY KEY(num),
    FOREIGN KEY (user_id) REFERENCES canvas_user,
    FOREIGN KEY (assignment_id) REFERENCES assignment
);

I want to make INSERTs on the table with a php function, something like the following (not working) code:
function create_submission($user_id, $assignment_id, $lti_info) {
        # INSERT everything except lti info
        $query = "INSERT INTO submission (user_id, assignment_id, timestamp) VALUES ($1, $2, LOCALTIMESTAMP) RETURNING num";
        pg_prepare($this->con, "createsub", $query);
        $rs = pg_execute($this->con, "createsub", array($user_id, $assignment_id));
        $row = pg_fetch_row($rs);
        $sub_num = $row[0];

        # update table to insert lti_info
        $serialized = serialize($lti_info);
        $query = "UPDATE submission SET lti_info = $1";
        pg_prepare($this->con, "insertlti", $query);
        pg_execute($this->con, "insertlti", array($serialized));
        return $sub_num;
    }

I have tried to serialize and do something like this answer on a similar question: Supply a prepared statement with an array, but with no success.
I would be very pleased if any of you can provide a solution to the create_submission function.
UPDATE:
When I execute create_submission it gives the following error at the update point:

pg_execute(): Query failed: ERROR: array value must start with "{" or
  dimension information

lti_info is an associative array of strings, similar to:
lti_info = array (
"oauth_consumer_key" => "example",
"oauth_consumer_secret" => "secret"
)

Note: I don't mind if everything is done in a single insert or with first insert "normal" fields and then the lti_info array.

A: There are no associative arrays in Postgresql. To save it as a bi dimensional array it would be necessary to build a suitable string to pass to Postgresql and do the reverse on the way back. It is simpler to save it as JSON:
create table submission (
    num serial,
    user_id integer not null,
    assignment_id integer not null,
    timestamp timestamp,
    lti_info json,
    primary key(num)
);

Use json_encode
<?php
$lti_info  = array (
    "oauth_consumer_key" => "example",
    "oauth_consumer_secret" => "secret"
);

$query = "
    insert into submission (user_id, assignment_id, timestamp, lti_info) values
    ($1, $2, localtimestamp, $3)
    returning num
";

$conn = pg_connect ( "port=5432 user=cpn dbname=cpn");
pg_prepare($conn, "createsub", $query);
pg_execute($conn, "createsub", array(1, 1, json_encode($lti_info)));

$query = "select * from submission";
pg_prepare($conn, "select", $query);
$rs = pg_execute($conn, "select", array());

$lti_info = (array) json_decode(pg_fetch_result($rs, "lti_info"));

print_r ($lti_info);
?>

Outputs
    Array
(
    [oauth_consumer_key] => example
    [oauth_consumer_secret] => secret
)


text:
Q: How to make buttons from one form affect a listview in another one? I want to have buttons in one form, then as I click on them, an item is added to a list in another form.
This is my current code, take in mind that in this code the buttons are in the same form as the listview, and I want to move either to a new one:
    private void button2_Click(object sender, EventArgs e)
    {
        listView1.Items.Add("Panama");
    }

    private void button3_Click(object sender, EventArgs e)
    {
        listView1.Items.Add("Brazil");
    }

    private void button4_Click(object sender, EventArgs e)
    {
        listView1.Items.RemoveAt(0);
    }

How do I do so when the button is clicked, the list in another form gets the item added?

A: You need to have a reference to the other forms from the form that invokes the action.
One way is to expose the ListView as a property on the Form itself and the just reference it via the Form
From Form1
private void button4_Click(object sender, EventArgs e)
    {
        Form2Instance.MyListView.Items.RemoveAt(0);
    }

In Form2 add the following wrapper to expose the original listView
public ListView MyListView{get{return this.ListView1;}}

A: two ways to achieve this:
first you have a reference to the other form and its listview, and call the listview to add/remove item straightaway when the button is clicked in the current form.
second use event: when the button is clicked, raise an event which is subscribed by the other form, and in the handler, do whatever you like (such as add/remove item to your list view according to the event data). for event, ref: http://msdn.microsoft.com/en-us/library/wkzf914z(v=vs.100).aspx

A: Let's say you have Form1 and Form2 where Form1 is the one with the buttons and Form2 contains the ListView. At the moment when you create Form2 you have to save a reference to this instance of Form2 in Form1.
public class Form1
    {
        private Form2 form2;

        public Form1()
        {
            this.form2 = new Form1();
            this.form2.Show();
        }
    }

    public class Form2
    {
        public Form2()
        {

        }

        public void AddItemToListView(string itemName)
        {
            // Check if itemName is valid and add it to your listView
        }
        public void RemoveItemFromListViewAt(int position)
        {
            // Check if the position is valid and remove the item at the position
        }
    }

A: Please don't reference one form from another just to add an item to a list.  :)
Building off of Rex's answer above, you could implement the Domain Event Pattern (http://www.martinfowler.com/eaaDev/DomainEvent.html)
A simple (rudimentary) implementation would have a singleton class managing the event / firing of the event:
using System;

/// <summary>
/// Class representing a single source for domain events within an application.
/// </summary>
public class DomainEventSource
{
    #region Fields

    private static readonly Lazy<DomainEventSource> source = new Lazy<DomainEventSource>( () => new DomainEventSource() );

    #endregion

    #region Properties

    /// <summary>
    /// Gets a reference to the singleton instance of the <see cref="DopmainEventSource"/> class.
    /// </summary>
    /// <value> A<see cref="DomainEventSource"/> object.</value>
    public static DomainEventSource Instance
    {
        get
        {
            return source.Value;
        }
    }

    #endregion

    #region Methods

    /// <summary>
    /// Method called to indicate an event should be triggered with a given item name.
    /// </summary>
    /// <param name="name">A <see cref="string"/> value.</param>
    public void FireEvent( string name )
    {
        if ( this.AddItem != null )
        {
            this.AddItem( source, new AddItemEvent( name ) );
        }
    }

    #endregion

    #region Events

    /// <summary>
    /// Event raised when add item is needed.
    /// </summary>
    public EventHandler<AddItemEvent> AddItem;

    #endregion
}

And then wiring up for and calling events like:
DomainEventSource.Instance.AddItem += ( s, a ) => Console.WriteLine( "Event fired with name: " + a.ItemName );

DomainEventSource.Instance.FireEvent( "Thing" );
With this, you have to keep in mind that events are a easy source of memory leaks.  If you register this, make sure you unregister it.

A: make listView of form as a static one
public static ListView listview1=........
then you can Access that ListView  from another form like follows
Form1.listview1.Add(value);


text:
Q: Plyr - Seeking does not work with custom HTML on audio element in IOS I created a plyr audio instance using custom HTML controls from the document here
Expected result : the audio player seeks to touched part of the input range.
Problem : the audio player pauses briefly and does not seek in IOS safari.
Tested enviroment:
Operating System: iOS
Version: 12
Here is link code pen to show this problem : https://codepen.io/dophuong/pen/mdbqRox
const controls = '

                    <button type="button" class="plyr__controls__item plyr__control" aria-label="Play" data-plyr="play">
                            <svg class="icon--pressed" role="presentation" focusable="false"><use xlink:href="#plyr-pause"></use></svg>
                            <svg class="icon--not-pressed" role="presentation" focusable="false"><use xlink:href="#plyr-play"></use></svg>
                            Pause
                            Play
                    </button>

                                    <input data-plyr="seek" class="plyr__progress--seek" type="range" min="0" max="100" step="0.01" value="0" autocomplete="on" role="slider" aria-label="Seek" id="plyr-seek-{id}" aria-valuemin="0" style="user-select: none; touch-action: manipulation;">
                                    <progress class="plyr__progress__buffer" min="0" max="100" value="0" role="progressbar">% buffered</progress>
                                    00:00

      ';

const player = new Plyr('#player', {controls});

A: I found solution for this problem, I used RangeTouch to fix it
const controls = '

                    <button type="button" class="plyr__controls__item plyr__control" aria-label="Play" data-plyr="play">
                            <svg class="icon--pressed" role="presentation" focusable="false"><use xlink:href="#plyr-pause"></use></svg>
                            <svg class="icon--not-pressed" role="presentation" focusable="false"><use xlink:href="#plyr-play"></use></svg>
                            Pause
                            Play
                    </button>

                                    <input data-plyr="seek" class="plyr__progress--seek" type="range" min="0" max="100" step="0.01" value="0" autocomplete="on" role="slider" aria-label="Seek" id="plyr-seek-{id}" aria-valuemin="0" style="user-select: none; touch-action: manipulation;">
                                    <progress class="plyr__progress__buffer" min="0" max="100" value="0" role="progressbar">% buffered</progress>
                                    00:00

      ';

const player = new Plyr('#player', {controls});
const ranges = RangeTouch.setup('input[type="range"]', {});

I fixed it in : https://codepen.io/dophuong/pen/mdbqRox


text:
Q: Google maps gives me null pointer exception while it shouldn't In my android app, I'm getting some locations when I choose the first element(anyone of the list) from RecyclerView it works and it gives location normally, but when I go back to choose another one it gives me NPE.
First example:

*

*I choose the second element (it works).

*I go back to choose another one.

*I  choose the first element(gives NPE).

Second example:

*

*I choose the first element (it works).

*I go back to choose another one.

*I choose the second element(gives NPE).
My code:
private SupportMapFragment mapFragment;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_sales_item, container, false);

    if(getArguments()!=null)
    {
        saleID = getArguments().getString("saleID");
    }

    initIDs();

   retroFit();

    maps();

    return view;
}

public void retroFit(){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ServiceConstants.URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RoyalAPI royalAPI = retrofit.create(RoyalAPI.class);

    Call<SaleItemResponse> connection = royalAPI.getSaleItem(saleID);
    connection.enqueue(new Callback<SaleItemResponse>() {
        @Override
        public void onResponse(Call<SaleItemResponse> call, Response<SaleItemResponse> response) {
            List<SaleItem> posts = response.body().getData();

            latitude = posts.get(0).getLatitude();
            longitude = posts.get(0).getLongitude();

        }

        @Override
        public void onFailure(Call<SaleItemResponse> call, Throwable t) {

        }
    });

}

private void map(){

    if (mapFragment == null) {
        mapFragment = SupportMapFragment.newInstance();
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                LatLng latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
                googleMap.addMarker(new MarkerOptions().position(latLng)
                        .title(""));
                googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }
        });
    }

    // R.id.map is a FrameLayout, not a Fragment
    getChildFragmentManager().beginTransaction().replace(R.id.map_sales, mapFragment).commit();

}

.
public class SaleItemResponse {

@SerializedName("data")
private List<SaleItem> mData;
@SerializedName("state")
private Long mState;

public List<SaleItem> getData() {
    return mData;
}

public void setData(List<SaleItem> data) {
    mData = data;
}

public Long getState() {
    return mState;
}

public void setState(Long state) {
    mState = state;
}

}

.
public class SaleItem {

@SerializedName("latitude")
private String mLatitude;
@SerializedName("longitude")

public String getLatitude() {
    return mLatitude;
}

public void setLatitude(String latitude) {
    mLatitude = latitude;
}

public String getLongitude() {
    return mLongitude;
}

public void setLongitude(String longitude) {
    mLongitude = longitude;
}
}


text:
Q: Why is Integer[] a sub-type of Number[] in Java, but List is not a sub-type of List? It makes sense that ArrayList<Integer> is not a sub-type of ArrayList<Number> in Java, since otherwise the statement
ArrayList<Number> list = new ArrayList<Integer>();

would be correct, and therefore one could call list.add(Double.valueOf(1.1)) which is obviously wrong.
The question is: Why Integer[] is a sub-type of Number[]? In other words, why the following statements are compiled with no errors? (although the second line will throw a runtime exception, and cannot be executed)
Number[] array = new Integer[10];
array[0] = Double.valueOf(1.1);


text:
Q: iLMerge Enterprise Library 5.0 Has anyone successfully iLMerged Enterprise Library 5.0? iLMerge successfully creates the merged dll and my mvc application compiles, but when launching the application I receive the following error:
SecurityTransparent and SecurityCritical attributes cannot
be applied to the assembly scope at the same time.

A: ILMerge is great if you wrote all of the assemblies that you're trying to merge, and you know that none of them are making assumptions about assembly organization. But under many circumstances (especially ones where heavy reflection or the Dynamic Language Runtime are involved), ILMerge just doesn't work. Sometimes things fail in surprising and mysterious ways.
When ILMerge fails, Jeffrey Richter h a more reliable way to get applications with multiple DLL dependencies to be deployable as a single assembly.
With his approach, every assembly gets to retain its own name, strongname, and attributes, which greatly improves your chances of the resulting application just working.
It isn't without trade-offs, but even the ILMerge author, Mike Barnett, said in the comment thread on that blog post "As the author of ILMerge, I think this is fantastic! If I had known about this, I never would have written ILMerge."
If you can use Richter's method, you won't trip over most of the reflection or dynamism traps.
The implementation steps

*

*Embed all of the third-party assemblies that you depend on in your application's Resources.

*Register a ResolveEventHandler with the AppDomain.CurrentDomain.AssemblyResolve event.

*When your handler gets called with an assembly that you stashed in Resources, load the assembly.

You do part 3 as follows:
var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name);
return Assembly.Load(new BinaryReader(resourceStream).ReadBytes(int.MaxValue));

A: Try to merge only the DLLs that are part of your application, not the framework ones (System.Web.Mvc.dll, System.Web.Routing.dll and System.Web.Abstractions.dll)


text:
Q: Set up combo box row source VBA returning error '1004' I am trying to set up the row source for a combo box in Excel VBA but is returning the error

1004 Method 'Range' of object '_Global' failed.

Private Sub UserForm_Initialize()

    Dim rngVendor As Range

    Set rngVendor = Worksheets("Lists").Range("N2:N" & _
    Range("N2").End(xlDown).Row)

    frmNewVendor.cboVendor.RowSource = Range(rngVendor)

End Sub

A: rngVendor is declared as a range so it doesn't need the Range function
 frmNewVendor.cboVendor.RowSource = rngVendor


text:
Q: C++: Efficient way to check if elements in a vector are greater than elements in another having same indices? I have a vector < vector <int> > like so:
v = {{1,2,3}, {4,2,1}, {3,1,1}....}}

All v's elements like v[0], v[1], v[2]... have the same size. There may be duplicate elements.
What I am trying to do is to find and delete vectors (like v[2]) that are "majorized" by another vector (like v[1]), i.e. all elements of v[1] are greater than/equal to the respective elements(in order of indices) in v[2].
A naive way of doing this would be to loop thorough v and compare each vector with another vector and further compare each element with another vector's element.
But I feel there must a better way to do this without getting O(n^3) in the number of elements of all the vectors in v.
If multiple vectors are equal, I need only one of them (i.e delete all except one). A random choice would be sufficient.
Any thoughts or ideas are appreciated!

A: This is called the maxima of a point set.  For two and three dimensions, this can be solved in O(n log n) time.  For more than three dimensions, this can be solved in O(n(log n)^(d − 3)  log log n) time.  For random points, a linear expected time algorithm is available.


text:
Q: How to answer, log and hang up phone with React Native Incall Manager I am trying to make a react native program that can accept phone call, log phone number and hang up the phone using react-native-incall-manager.
My motivation for doing this is to verify phone number by answering the phone from server without using SMS (cause SMS sending prices too high and I am not making money yet from the application) and sending that verification information to server from the phone. It is very similar to Telegram's phone number verification system.
What I have done so far is:
import React, { Component } from 'react';
import { View } from 'react-native';
import { Text, Button } from 'native-base';
import InCallManager from 'react-native-incall-manager';

export default class PhoneVerification extends Component {
    answerPhone() {
        InCallManager.start();
    }
    hangupPhone() {
        InCallManager.stop();
    }
    render() {
        return (
            <View>
                <Button onPress={this.answerPhone} style={{ marginTop: 600 }}><Text>Answer</Text></Button>
                <Button onPress={this.hangupPhone} style={{ marginTop: 2 }}><Text>Hang up</Text></Button>
            </View>
        );
    }
}

These two buttons do nothing and still default phone answering dialog appears on top of my program when a call made to my phone.
Besides I am open to all of your ideas for cheap phone verification.


text:
Q: Where to see what OMP schedule(auto) picks? Is there a way to find out what scheduling scheme the OMP runtime chooses for schedule(auto)? I found that (and intuitvely it makes sense) for my problemschedule(static) is the fastest, so I am wondering if that's what the runtime chooses when is set schedule(auto) (they're equally fast).

A: Yes. You can set the environment variable OMP_DISPLAY_ENV to TRUE to get this information before running your program. It should print the OMP_SCHEDULE variable when the OpenMP runtime is initialized. For example, on my system, GOMP (GCC) choose DYNAMIC while IOMP (Clang/ICC) choose static by default. You can select this default value by setting the environment variable OMP_SCHEDULE yourself. You can also retrieve the information at runtime in your program using the OpenMP function omp_get_schedule.
Unless you know that a schedule is fundamentally better than another one (for example due to the algorithm itself), it is a good practice to let the default (runtime-based) behaviour. Indeed, the result can be sharply different between two OpenMP runtime or two machines. For example, a dynamic schedule can be theoretically better than a static one, but the overhead with one runtime can be so high that it seems a very bad choice while this could not be a problem with another implementation. The number of core and they layout (eg NUMA systems) are also important parameters impacting the performance of the different scheduling strategies.


text:
Q: Time duration calculation Error runtime using VBScript I am trying to calculate the time durations via the below Sub. But it takes only two iterations.where as it should take 4, as a result all the durations are not being summed up.I introduced 2 msgbox- which are showing the result. Fitst one showing the length which is perfect,but the second one showing some thing undesired.
CODE
msgbox(ArrayListTaskDetails.Count) '~~ output is 16
For IndexSearch = 0 To ArrayListTaskDetails.Count - 1 Step 4

dt1 = ArrayListTaskDetails(IndexSearch + 3)
SumDate = TimeAdd(dt1,SumDate)

If Err Then

msgbox(IndexSearch) '~~ output as 8. here is the question why the error occurs?
Err.Clear
Exit for

End If

Next

Function TimeAdd(dt1,dt2)

If (IsDate(Cdate(dt1)) And IsDate(Cdate(dt2))) = False Then ' `Type mismatch: Cdate` error occurs in this line. Could you guide me here where the wrong is?
TimeAdd = "00:00:00"
Exit Function
End If

TimeAdd = Hour(dt1)+Hour(dt2) & ":" & Minute(dt1)+Minute(dt2) & ":" & Second(dt1)+Second(dt2)

End Function

Note: Time duration are 00:05:23,00:11:58,195:33:12,320:37:13 respectively at 3,7,11,15 th position of the List

A: The IsDate function returns a Boolean value that indicates if the evaluated expression can be converted to a date. It returns True if the expression is a date or can be converted to a date; otherwise, it returns False.Link here
Code  should be as :-
If Not (IsDate((dt1) And IsDate(dt2)) Then            '' If dt1 or dt2, any one from this id not date then it will set timeAdd = "00:00:00"
   TimeAdd = "00:00:00"
   Exit Function
End If


text:
Q: Get the web application context path from META-INF/context.xml to produce an outcome for navigating I have a primefaces web application running on tomcat 8. In META-INF/context.xml I defined the following:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/syslac"/>

While in my view xhtml page I have this fragment code  where p:commandButton has a oncomplete tag that will execute the handleLoginRequest function.
<h:form>
            <h:panelGrid columns="2" cellpadding="5">
               <h:outputLabel for="username" value="Usuario:" />
               <p:inputText value="#{loginBean.usuarioVendedor.usuarioSistema}" id="username" required="true" label="username" />
               <h:outputLabel for="password" value="Contrasena:" />
               <h:inputSecret value="#{loginBean.usuarioVendedor.clave}" id="password" required="true" label="password" />
               <f:facet name="footer">
                  <p:commandButton value="Ingresar" update=":growl" actionListener="#{loginBean.loguearse}" oncomplete="handleLoginRequest(xhr, status, args)" />
               </f:facet>
            </h:panelGrid>
         </h:form>

The script:
      <script type="text/javascript">function handleLoginRequest(xhr, status, args)
{
                if (args.validationFailed || !args.loggedIn) {
                    jQuery('#dialog').effect("shake", {times: 2}, 100);
                } else {
                    dlg.hide();
                    jQuery('#loginLink').fadeOut();
                    window.location = args.view;
                }
}
</script>

But I can not retrieve the context path from META-INF/context.xml through logginBean so that I can send view arg to be used by window.location in navigation: /syslac/page.xhtml where syslac is context path of the application.

A: The context path is in backing bean available by ExternalContext#getRequestContextPath().
String contextPath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();

So you could do for example:
String loginURI = contextPath + "/login.xhtml";
// ...

Note that this is completely unnecessary when using as JSF navigation outcome. For the correct approach, see the second "See also" link in bottom.
The context path is available in EL by HttpServletRequest#getContextPath().
#{request.contextPath}

So you could do for example:
<h:outputScript>
    // ...
    window.location = "#{request.contextPath}" + args.view;
</h:outputScript>

Or when your script is in a .js file (correct practice!):
<html lang="en" data-baseuri="#{request.contextPath}">

window.location = document.documentElement.dataset.baseuri + args.view;

See also:

*

*How get the base URL?

*What URL to use to link / navigate to other JSF pages


text:
Q: Asp.Net Sql Server Session Management I want to know if I have sqlstate session then do I need to create database for aspnetdb in the already (i.e. sampledb) existed database or I should have to create it separately. Suppose if I had create it in sampledb which is already existed then what connection-string path should I have to give in web.config and what changes would I have to make it on the time of deployment of the internet.
Please give me answer because there is lots of questions arising in my mind.

A: You should create a new database for the session state.
Configuring SQL Server session state is really simple and requires two simple steps:

*

*Install ASPState database on your SQL server.
1.1 Open the command prompt and navigate to the folder where .NET Framework is installed on your machine e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319
1.2  Run the following command in the command prompt - aspnet_regsql.exe -S SampleSqlServer -E -ssadd -sstype p

*Configure SQL server session state in the Web.config file to point to the ASPState database on your server.
Web.config:
<configuration>
  <system.web>
    <sessionState mode="SQLServer"
      sqlConnectionString="Integrated Security=SSPI;data
        source=SampleSqlServer;" />
  </system.web>
</configuration>

Complete tutorial can be found here - Session-State Modes


text:
Q: Azure REST apis for get all devices and attaching an iot device to an edge device I have been breaking my head on this for a long time now and haven't found the solution yet. I need

*

*Rest api to add an iot device to an iot edge, in azure iot hub.

*Rest api to get all iot devices under an iot edge, in azure iot hub.

I scampered through the documentation, but to no vain. Someone please do help, if you are aware of these.

A: have a look at the Query POST request with the following payload:
{
  "query":"SELECT * FROM devices WHERE capabilities.iotEdge = true "
}

A: The parameter deviceScope, while adding a device, determines the parent of that particular device. So while adding a device, if you set your device scope to that particular iot edge, then it automatically gets assigned as a child, to the particular iot edge.


text:
Q: Can we know which logical blocks are in used without understanding the filesystem running on top? From this FAQ:

Why Clonezilla can NOT restore an image which is saved from a large drive to a smaller drive? Any workaround?

It's not easy to implement such a feature, since Clonezilla now is a partition "imaging" tool, by "imaging", it means clonezilla actually does not know the files themselves, clonezilla just knows where the used blocks are. Because of this reason, the target partition size must be equal or larger than the original one so that clonezilla can restore the used blocks on that partition. If the target partition size is smaller, then it will go wrong.
Unless Clonezilla has file-based function in the future. Maybe...

From what I know, a file is a list of pointers which point to one or many continuous blocks (or clusters). How can a software know which blocks are in used without understanding the filesystem?

A: Simple answer: No.
The same is true for any data structure.  If you don't understand the data structure you can't find anything in it.

For data recovery purposes there are tools which will scan data (a drive) and search for signatures it understands (eg the start of a jpeg file).  One example tool is photorec
This technique lets the software find some files without understanding the file system.  But it's messy and unreliable.  This technique can't handle fragmentation well and only works for some file types.  It can often result in corrupted files.

There are cloning tools which are file system specific.  For example if you know the partition type is ext2/3/4 you can use a tool like e2image to copy files across without using the Kernel's file system driver.
You could also resize the file system before cloning with clonezilla.  Eg: use resize2fs to shrink the file system first.
Beyond that, your only real option is to mount the file system and copy the files across with cp, tar or rsync.

Regarding CloneZilla's decision not to implement resizing:  Filesystems are generally very complex.  There are some simpler ones but ext2/3/4, reiserfs, etc. are't the simple ones.
It can be simple to parse enough information from a file system to determine which blocks it's using.  Some file systems even have a nice neat table just marking which bocks are used / not used.  Parsing this would not require knowledge of files at all.
As an example, ext3 by default uses blocks of 4096 bytes and block groups of 32,768 blocks.  Each 128MiB block group contains a "Data Block Bitmap" showing which blocks in the group are in-use (see reference).  So without knowing anything about the files themselves, a program can parse just which blocks are in-use.
However resizing a file system requires a much more robust knowledge.  Without knowing specifics of ext2 etc, possible snags include

*

*failing to update cross reference pointers or pointers to / from meta data

*failing to update checksums

*failing to update block usage bitmaps correctly

It would be very easy for a naive developer to implement a resize in a way that corrupts the file system or destroys meta data.


text:
Q: Set Status bar color - delay? When ill try to change the text-color of me StatusBar in iOS, there is always a delay for maybe 1-2 seconds. So it starts with black, and after that delay its getting white, as i want to.
All these changes are in my ViewController, in ViewDidLoad.
Ill use a custom view to get an specific color:
    let statusBarHeight = CGFloat(20)
    let colorBGView = UIView(frame: CGRectMake(0, -statusBarHeight, self.view.bounds.width, statusBarHeight))
    colorBGView.backgroundColor = UIColor.customDarkerGrey()
    self.navigationController?.navigationBar.addSubview(colorBGView)

And set the barStyle to Black (to get the white color font when using an UINavigationController)
    self.navigationController?.navigationBar.barStyle = UIBarStyle.Black

Set the Value for:
 View controller-based status bar appearance

In the plist.info to "YES"
But there is still a "lag" - so everything is white, but it takes up to 2 seconds. Any ideas?
Ill found not an answer question, because this is only about coloring, not for the problem with the delay:
preferredStatusBarStyle isn't called
Edit:
Ok, after creating a new Project with 2 ViewControllers and a NavigationController ill found out, that the "Delay" is normal, when you try to change the Color from ViewController to ViewController. It seems, that the function:
override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent
}

Is called with a little delay - and nothing happens when ill add:
self.setNeedsStatusBarAppearanceUpdate()

So in my case ill changed it globally on the NavigationController, and (because its loaded with my App) you do not recognize the "delay".
Maybe this is helpful for someone else.

A: Try to set color for status bar in AppDelegate in method didFinishLaunchinOptions. As your status bar color is set to other color by default and then you are setting it to new color in your controller, its creating delay.
And also
Set the Value for:
View controller-based status bar appearance

In the plist.info to "NO"


text:
Q: Prompting for download Whats the best method to prompt a user to download something?  In the past I've used window.open('file.pdf'); but I can see popup blockers having a problem with this.  Of course I'll include a manual link aswel.
I basically want something like the Microsoft Download page.  So whats the script that prompts this?

A: Redirect using javascript.
function redirect() {
window.location = 'http://www.url.to/your.file';
}

A: Content-Disposition: attachment; filename="file.pdf"

To do this you may want to pass your file.pdf through a server script that forces that header on it.
What you see on that download page is just a location change. And if that page returns the download header the browser won't change page.

A: Set a content disposition header with an attachment value