text:
Q: Server access kept blocked until the ghost script completes I'm new to ghostscript and using it to compress PDF files. I'm using the below script for this :

'gs -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite
-dPDFSETTINGS=/screen -dCompatibilityLevel=1.3 -dEmbedAllFonts=true -dSubsetFonts=true -dAutoRotatePages=/None -dColorImageDownsampleType=/Bicubic -dColorImageResolution=66 -dGrayImageDownsampleType=/Bicubic -dGrayImageResolution=66 -dMonoImageDownsampleType=/Subsample -dMonoImageResolution=66 -sOutputFile=output.pdf input.pdf';

First the script takes too long to execute.
Also the main issue is, Other pages of the server kept blocked.

Is it right? I mean, does this happens generally that other location of the server kept blocked.

Can anyone suggest me better way to handle this where I have control of the quality of the compressed pdf.
For example : How can I achieve 80%, 50%, 30% compression from original file.

Thanks.


text:
Q: NHibernate Conversation per Business Transaction and Identity Keys I would like to implement the conversation per business transaction pattern in a WPF application as described here.  Unfortunately this application has a large existing database using SQL Server generated identity keys in all tables.
I know that adding a new object to an NHibernate session will cause it to be inserted if it has an identity key.  Fabio has the pattern commiting the current transaction at the end of each request, even though we haven't necesarily finished the entire unit of work yet.
If I understand correctly, this means that my objects are going to be inserted into the database and not removed even if I abandon the unit of work.  So:

*

*Is this pattern incompatible with identity keys?

*Are there any reasonable work arounds?

*Is there a better pattern I can use in this case?

Edit #1:
Some additional comments from Fabio are here.
Edit #2:
Exploring further has lead me to the persist(...) method which is similar to save(...) but just different enough to be confusing.  This statement taken from the hibernate FAQs is interesting:

The persist() method also guarantees
  that it will not execute an INSERT
  statement if it is called outside of
  transaction boundaries. This is useful
  in long-running conversations with an
  extended Session/persistence context.

Surely if it guaranteed the same inside a transaction boundary it would be more useful?  I was under the impression not using transactions was frowned upon anyway.

A: One workaround - you can hold off on your ISession.Saves until you're ready to commit your unit of work, perhaps as a collection of transient instances in your unit of work class.
Also, if your entities are referenced by an existing entity (and it makes sense to), you can cascade the inserts - done consistently, this means you should only need to explicitly insert your aggregate root objects. This is the approach I normally use in this situation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proper Way to PWM (Voltage Control) Dim LED Strip I have been asked to create a dimming system (Along with other features) that interfaces to the cheap LED strip lights. A lot of people seem to use standard N-FETs with PWM on the low side. My concern is with a long strip (3M) wouldn't this produce a large amount of EMC/EMI due to a hard edged voltage and current wave?

Should the design instead incorporate more of a buck style control with an LC filter to smooth the output waveform? And effectively make it analog dimming if EMC/EMI or radiated emissions is of concern to for instance pass FCC or CE tester? Note values in schematic are for reference only, not calculated.
If so, is there an easy way to do it without a high side switch, or an easy way to efficiently drive it from 0 to 100% PWM?

simulate this circuit – Schematic created using CircuitLab

A: The idea of PWM controlling LEDs is to drive them with their correct drive current for a proportion of the time and let the eye do the averaging as its response is in the 25Hz range.
Using a lower than recommended drive voltage produces a very non linear response and reducing the drive current can produce some unexpected results like spectral shift particularly if the leds are the multiple die types.
If you want to improve EMI then the first thing to do would be to reduce your PWM frequency by a factor of 10. Then you can think about softening the edges. A very simple RC filter would be sufficient.


text:
Q: Manually triggering onChange callback in React 18+ The problem is that I'm unable to manually trigger onChange callback on input component in React. I have a custom 'file picker' which changes the input's value of new selected file path. I want to manually dispatch a 'change'/'input' event for this input.
Example case:
<input onChange={(e) => console.log(e.target.value)} />

const inputRef = /* ref of input above */

/* .. */
const newValue = 'path/test.ext';
inputRef.current.value = newValue;
// dispatch change event for inputRef.current to console log new value

I'd like to point out that I've already researched the subject. The newest solution I've could find is: https://stackoverflow.com/a/71340077/14175627
Sadly, this solution doesn't work anymore and I'm unable to find working one.


text:
Q: How to do kernel function on an array of strings in Numba cuda? I have an array of strings that i read from file ,i want to compare each line of my file to a specific string..the file is too large (about 200 MB of lines)
i have followed this tutorial https://nyu-cds.github.io/python-numba/05-cuda/ but it doesn't show exactly how to deal with array of strings/characters.
import numpy as np
from numba import cuda

@cuda.jit
def my_kernel(io_array):

    tx = cuda.threadIdx.x

    ty = cuda.blockIdx.x

    bw = cuda.blockDim.x

    pos = tx + ty * bw
    if pos < io_array.size:  # Check array boundaries
        io_array[pos]   # i want here to compare each line of the string array to a specific line

def main():
    a = open("test.txt", 'r')  # open file in read mode

    print("the file contains:")
    data = country = np.array(a.read())

    # Set the number of threads in a block
    threadsperblock = 32

    # Calculate the number of thread blocks in the grid
    blockspergrid = (data.size + (threadsperblock - 1)) // threadsperblock

    # Now start the kernel
    my_kernel[blockspergrid, threadsperblock](data)

    # Print the result
    print(data)

if __name__ == '__main__':
        main()

I have two problems.
First: how to send my sentence (string) that i want to compare each line of my file to it to the kernal function. (in the io_array without affecting the threads computation)
Second: it how to deal with string array? i get this error when i run the above code
this error is usually caused by passing an argument of a type that is unsupported by the named function.
[1] During: typing of intrinsic-call at test2.py (18)

File "test2.py", line 18:
def my_kernel(io_array):
    <source elided>
    if pos < io_array.size:  # Check array boundaries
        io_array[pos]   # do the computation

P.S i'm new to Cuda and have just started learning it.

A: First of all this:
data = country = np.array(a.read())

doesn't do what you think it does.  It does not yield a numpy array that you can index like this:
io_array[pos]

If you don't believe me, just try that in ordinary python code with something like:
print(data[0])

and you'll get an error.  If you want help with that, just ask your question on the python or numpy tag.
So we need a different method to load the string data from disk.  For simplicity, I choose to use numpy.fromfile().  This method will require that all lines in your file are of the same width.  I like that concept.   There's more information you would have to describe if you want to handle lines of varying lengths.
If we start out that way, we can load the data as an array of bytes, and use that:
$ cat test.txt
the quick brown fox.............
jumped over the lazy dog........
repeatedly......................
$ cat t43.py
import numpy as np
from numba import cuda

@cuda.jit
def my_kernel(str_array, check_str, length, lines, result):

    col,line = cuda.grid(2)
    pos = (line*(length+1))+col
    if col < length and line < lines:  # Check array boundaries
        if str_array[pos] != check_str[col]:
            result[line] = 0

def main():
    a = np.fromfile("test.txt", dtype=np.byte)
    print("the file contains:")
    print(a)
    print("array length is:")
    print(a.shape[0])
    print("the check string is:")
    b = a[33:65]
    print(b)
    i = 0
    while a[i] != 10:
        i=i+1
    line_length = i
    print("line length is:")
    print(line_length)
    print("number of lines is:")
    line_count = a.shape[0]/(line_length+1)
    print(line_count)
    res = np.ones(line_count)
    # Set the number of threads in a block
    threadsperblock = (32,32)

    # Calculate the number of thread blocks in the grid
    blocks_x = (line_length/32)+1
    blocks_y = (line_count/32)+1
    blockspergrid = (blocks_x,blocks_y)
    # Now start the kernel
    my_kernel[blockspergrid, threadsperblock](a, b, line_length, line_count, res)

    # Print the result
    print("matching lines (match = 1):")
    print(res)

if __name__ == '__main__':
        main()
$ python t43.py
the file contains:
[116 104 101  32 113 117 105  99 107  32  98 114 111 119 110  32 102 111
 120  46  46  46  46  46  46  46  46  46  46  46  46  46  10 106 117 109
 112 101 100  32 111 118 101 114  32 116 104 101  32 108  97 122 121  32
 100 111 103  46  46  46  46  46  46  46  46  10 114 101 112 101  97 116
 101 100 108 121  46  46  46  46  46  46  46  46  46  46  46  46  46  46
  46  46  46  46  46  46  46  46  10]
array length is:
99
the check string is:
[106 117 109 112 101 100  32 111 118 101 114  32 116 104 101  32 108  97
 122 121  32 100 111 103  46  46  46  46  46  46  46  46]
line length is:
32
number of lines is:
3
matching lines (match = 1):
[ 0.  1.  0.]
$


text:
Q: Como atrasar a exibição de um container usando Java Script ou CSS Preciso fazer ajuste em um site, o cliente quer que um conteúdo seja exibido após 30 minutos.
Vou colocar um pequeno exemplo:

            <video src="">Video do Cliente</video>

            <video src="">Conteúdo Para ser carregado após 30 minutos</video>

            <video src="">Conteúdo Para ser carregado após 30 minutos</video>

            <video src="">Conteúdo Para ser carregado após 30 minutos</video>

Qual código faria os demais conteúdos serem carregado após um tempo determinado?

A: function load(){
    setTimeout(function(){
        console.log('run')
},3000)}

O código JS acima printa run no console após 3 segundos contados a partir do momento que a função load() for iniciada.
Você só precisa:

*

*Declarar uma variável que contenha a seleção do elemento container onde seus elementos serão adicionados.

*Modificar a função load() para criar um elemento com o conteúdo desejado.

*Acrescentar (append) o elemento criado dentro do container já selecionado pela variável na etapa 1.

*Ajustar o tempo de setTimeout para o tempo desejado.

O JS também possui uma função setInterval(callback, tempo) que chama a função callback em loop a cada tempo. Recomendo dar uma olhada, é fácil rápido, faça de acordo com sua preferência.


text:
Q: Media Import failure in Wordpress (XML import) I was hosting my website on one hosting platform. Before the hosting got wiped out/deleted, I had exported an XML of the entire content including media(images).
When I try to import the same XML file to my new Wordpress host, all the posts and users get imported but the media fails i.e. I'm not able to retrieve any media.
Any know any solution to get back my media? The old hosting service has been deleted.

A: Unfortunately, if the site is gone there is no media to import. The media import only works when the other site exists and the media is accessible. The export file does not contain the media (it's just XML).


text:
Q: what is the use of Csinglelock? It is mentioned in MSDN, that to lock and Unlock CCriticalSection object, we should use CSingleLock. But CCriticalSection::lock() and CCriticalSection::unlock() does the same thing, doesn't it? Then What is the difference between both the methods?

A: Using a wrapper will ensure that (almost) no matter what you do from the point where you are locking the lock, when you leave the function, it will unlock.
Consider:
void func()
{
    lock();
    ... plenty of lines ...
    // x = 8128 happens on a Wednesday, in a month without
    // r in the name, only if the day is divisible by 7 and 3.
    if (x == 8128)
       return;
    ... more lines of code ...
    unlock();
}

So, once every now and again, your application forgets to unlock the lock.
The same applies if you get an exception, use goto, etc.
If you use a wrapper, you are guaranteed that the destructor will be called when the scope of the wrapper ends. This is just as useful for std::string or std::vector as it is for locks.
Of course, it won't help if you use for example longjmp to jump out of the context. But then you shouldn't be using longjmp!


text:
Q: How do I justify this block of text and bring it in front of the icon? Using the following CSS:
.notice--info::before {
    position: relative;
    font-family: "Font Awesome 5 Free";
    font-weight: 900;
    top: .5em;
    left: 0;
    color: #ff980052;
    content: "\f071 ";
    font-size: 4em;
    vertical-align: text-top;
    line-height: .1em;
    text-indent: 0;
}

I've managed to achieve this look:

Using this Kramdown markup in Jekyll on the Minimal Mistakes theme:
{: .notice--info}
Important: Our systems are evolving and becoming more and more interconnected and dependent upon one another.  Therefore, we're providing a single checklist to handle all aspects of the morning prep so we can all work as a team on all aspects of the production.

The goal is to add font awesome icons as watermarks to the Minimal Mistakes Utility Classes defaults.
QUESTION 1: How do I get the first line to overlap without indentation?
QUESTION 2: How do I bring the text to the front so it's the top layer and isn't washed out by the alpha channel of the Font Awesome icon?
Thanks!

A: I've gone about re-creating your intended effect using Unicode rather than Font Awesome because you can achieve so much these days with a combination of Unicode and CSS filters that a third-party dependency like Font Awesome (which was popular in the early 2010s) may not be necessary any more.
Principally,

*

*I've given the paragraph text-align: justify

*I've made the paragraph see-through, by giving it an rgba() background-color

*Finally, I've positioned the warning symbol beneath the paragraph, using a z-index of -6
Working Example:

.notice--info {
  position: relative;
  padding: 12px 12px 30px 12px;
  font-size: 14px;
  line-height: 24px;
  text-align: justify;
  font-family: sans-serif;
  background-color: rgba(187, 197, 224, 0.3);
}

.notice--info::before {
  content: '\26A0 \FE0F';
  display: block;
  position: absolute;
  top: 42px;
  left: 6px;
  z-index: -6;
  font-size: 80px;
  filter: hue-rotate(-10deg) saturate(8);
  opacity: 0.5;
}

Important: Our systems are evolving and becoming more and more interconnected and dependent upon one another.  Therefore, we're providing a single checklist to handle all aspects of the morning prep so we can all work as a team on all aspects of the production.


text:
Q: Using pexpect to listen on a port from a virtualbox I am trying to create a tcplistener in python (using pexpect if necessary) to listen for tcp connection from Ubuntu in virtualbox on a windows xp host. I would really appreciate it, if one of you could point me in the right direction. Thank you.
P.S: I have limited experience in the area, any help would be welcome.

A: Python already has a simple socket server provided in the standard library, which is aptly named SocketServer.  If all you want is a basic listener, check out this example straight from the documentation:
import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "%s wrote:" % self.client_address[0]
        print self.data
        # just send back the same data, but upper-cased
        self.request.send(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()


text:
Q: I am using an IF statement in VBA to compare a calculated date to the dates in a table. I however keep getting the #NAME? error 'A year ago from current date
Dim LastYear As Date
LastYear = Now() - 365
Range("Class[Date_Check]").Formula = "= IF(Class[FAILDATE]< LastYear),""Bad"",""Good"")"


text:
Q: How do I get the URL from context.xml resource I am using a JNDI DataSouce with Tomcat.
my context.xml for java web app has a resource ta that looks like this :
<Resource
        name="jdbc/dbv1RW" type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="10000"
        url="jdbc:mysql://localhost:3306/dbv1"
        driverClassName="com.mysql.jdbc.Driver"
        username="root" password="root"
 />

And I fetch the data source in my java class like this :
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
dataSource = (DataSource) envCtx.lookup("jdbc/dbv1RW");

How can I get the URL of the data source without establishing the connetion with the data source(i.e. without calling the get connection method) ?

A: You have to printout what is the real implementation of the returned data source. If the implementation exposes the parameters then you can cast it to its real type and access them. It will be implementation (server) specific.


text:
Q: dpylr::tbl equivalent for Pandas I am currently trying two switch from R to Python. I am working with large tables  for a Uni project. I load the data as Snowflake objects in R via the commands:
con <-
  nuvolos::get_connection()

db_mcc_desc <-
  dplyr::tbl(con, "Table")

"Table" is about 100GB, so I really like that I can use many dplyr functions on db_mcc_desc without loading it into memory. Whenever needed I can create smaller data frames and load them into memory using collect().
However, when using the following pandas command, it automatically reads in a dataframe which exceeds my memory quite quickly.
import pandas as pd
from nuvolos import get_connection

con = get_connection()
db_mcc_desc = pd.read_sql_table('SELECT * TABLE', con=con)

Normal batching does not really work because the Table is so big. Is there a similar and easy solution in Pandas as available in the dplyr package for R.
Thanks a lot!


text:
Q: node-simplecrawler: ajaxed content pages crawl issue I'm using this script for crawling some shopping sites. I have a huge issue that make this script and any other worthless for me.
We are planing to crawl a page a shopping website called digikala (www.digikala.com). The problem is the main product grids load their data from an AJAX call.
for example this page : http://www.digikala.com/Search/Category-Mobile-Phone/#!/Brand-10/Category-Electronic-Devices/Category-Mobile/Category-Mobile-Phone/
If you see your firebug/developer-console you will see that the products grid of this category is loading after an AJAX post call. So how can I crawl this product pages?
Add some wait (for example 10 sec) before fetch the page will fix the issue?

A: option1: use browser simulation , suck as phantomjs,
option2: checkout the ajax url from developer tool, get data directly from the url. be careful, may need special header, or some kind of validation.


text:
Q: Contact list not accessing all contacts phonegap I created a project in phonegap in appery.io framework. It is not cordova based project but I installed cordova library manually. I am fetching contacts list using Jquery but it is fetching only device contacts list not the sim contacts list. If i want to install cordova contacts plugin using commands then it is showing current directory is not a cordova based project. if anyone could help me out it would be much appreciated.

A: Hi use this to save all contacts in sdcard and display. (default Cordova contacts and file plugin)
 document.addEventListener("deviceReady", deviceReady, false);

   function deviceReady() {

 navigator.contacts.find(["*"], function(contacts) {

  //alert("contacts.length = " + contacts.length);

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
    fileSystem.root.getFile("contacts.json", {create: true, exclusive: false}, function(fileEntry) {
        fileEntry.createWriter(function(writer) {
            writer.onwriteend = function(){
              // Success Contacts saved to sdcard as a contacts.json file
              // Now get and read the json file

var path = fileSystem.root.getFile("contacts.json", {create:false},gotFileEntry, fail);

       // jquery

  $.getJSON(path, function (data) {

user = data;
$.each(user, function (index, user) {
    var all_item = '
'+user.displayName+'
';
    $('#allcontacts').append(all_item);
});
   });
            };
                  writer.write(JSON.stringify(contacts));

        }, onError);

    }, onError);

}, onError);

    }, onError,{"multiple": true});}
    function onError(){
        alert("Error");
             }


text:
Q: UWP FolderPicker.PickSingleFolderAsync fails with COMException / E_FAIL In my UWP app I have the following code:
private async void testButton_Click(object sender, RoutedEventArgs e)
{
  var picker = new Windows.Storage.Pickers.FolderPicker();
  StorageFolder folder = await picker.PickSingleFolderAsync();
}

but when I run this it fails on the second line with the message An exception of type 'System.Runtime.InteropServices.COMException' occurred in .... but was not handled in user code.  The HRESULT from the exception is -2147467259 = 0x80004005 = E_FAIL.
I'm using file pickers already elsewhere in the app without problem.  This is running on a Win10 desktop (launched from VS2015).  Can anyone suggest why the error occurs and/or what to do to resolve it?  Having a meaningless error message in what appears to be the simplest code possible I'm not sure how to proceed.

A: This is a bit of an oddity in WinRT. Although it is not mentioned in the documentation explicitly, it is necessary to add at least one item in the FileTypeFilter collection:
var folderPicker = new FolderPicker();
folderPicker.FileTypeFilter.Add("*");
await folderPicker.PickSingleFolderAsync();

You can use a specific extension like ".jpg", but it doesn't seem to have effect in a FolderPicker anyway. The only thing that matters is that at least one valid item is present.


text:
Q: which is better to pass a PHP var in AJAX call to another page: POST or through the session? in a PHP site I am building, I use a Prototype AJAX call to address some other php page. This called php page needs a variable that lives as a SESSION var on the first page (in the sense that it's used multiple times throughout that page anyway).
It's more curiosity than anything else but: which of both ways to pass our variable is preferable, if any:

*

*on the called page, start the session and get the var needed from there, or

*in the AJAX call, pass the session var on as a POST parameter

So, I am curious if there is a higher 'cost' to passing a POST var between pages, versus getting the var from the session (adding session_start() etc).

A: If the value has no security concerns, pass it via the GET or POST method.  Only ff the value has some security issues or it could be a serious problem if the user were to change the value (via a proxy or injection) then use SESSION.

A: Using the POST method it's easy to cluster the servers since there is less state remembered on the server side, but at the cost of sending, potentially sensitive, data to the client.
Using the Session method, there is less bandwidth passing between the server and the client, but it's harder to scale across multiple front-end web servers.

A: I'd say use the session. You're already suffering the overhead of sending the session id in the request header so you may as well make use of it. Having said that it's not a vast overhead anyway but neither is posting a small amount of data.
In order to post the data, you need to have it available at the client side too and if that's the only reason you have it at the client side, you've left yourself needlessly open for spoofing.
The scalability across load balanced servers, if it turns out to be a problem, is going to have to be dealt with anyway if you're using sessions.
So if your sessions are working, use them.

A: I am actually looking for an answer for your question.
Bu this is what I found:
If the Variable is on the Session in the first page, this means that you cant call session_start() on the "ajax called" page.
Unless there is some workaround Im not aware of?


text:
Q: CDI - handling errors I am migrating my Seam 2 powered application to CDI and one of the things that is critical for me to retain is the error handling.  In Seam 2, I simply replaced the default exception handler with my own, but in CDI, I am guessing I'll have to use an Interceptor.
How would I set this up as using an Interceptor requires me to specify where it will intercept calls?  I mostly want to accomplish auditing, so when an exception occurs, it is logged, then a notification (email, xmpp, sms, phone call) is sent out to administrators.
When an exception occurs, is there simply an event that I can listen for and act on?
Walter

A: Are you using JSF2? If yes, instead of writing an Interceptor, you could register an ExceptionHandlerFactory in your web.xml as described here. In a CustomExceptionHandler, you can catch all Exceptions and handle them programmatically.
I'm using this approach in my JEE6-CDI-app, find it quite okay.


text:
Q: Migrate Windows Server 2008 to a new hard disk 2 A few weeks ago, I already asked how to move a Windows Server 2008 to a new hard disk. Despite the previous answers and two weeks lost trying to do it, I am always unable to move the OS to the new drive.
What I tried:

*

*A backup/restore using Windows Backup. This never helped.

*

*First, I tried to backup, then copy the backup to a new drive, then restore. This results in "The parameter is incorrect. (0x80070057)" error caused by a bug in Windows Backup.

*

*Recently, I attempted to backup to a network share, but I can't restore from it, because of a "*The network path was not found. (0x80070035)" error. Trying the netsh interface ipv4 set address [...] does not work neither (saw at least three different errors, mostly "The interface is unknown.") Solved, but then I have "The parameter is incorrect." error which I have even after removing all old backups, clearing all logs and doing a new full backup.

*A previously suggested solution using imagex from Windows AIK results in a non-bootable disk after writing an image to it. When booting from Windows 2008 installation disk (from USB), it finds that the HDD is not bootable and proposes to fix this, but then crashes, resulting in an unbootable USB flash disk (and HDD stays unbootable).

*As I said in my previous question, doing a clone of a hard disk drive gives an (of course) bootable disk, but Windows complain about hardware changes and cannot start.
Now can somebody suggest me another way to move Windows Server 2008 to a new hard disk? Is it at least possible to do, or any hard disk failure/change implements necessarily to reinstall the whole OS?

A: Unless the original disk is defective, I leave the old system disk in the server and just move the data to the new drive. Your server has room for spare disks, right?
In case you really must remove the old disk, your best bet is imaging software like Acronis Trueimage, Norton Ghost or similar.
In case the new disk uses a different controller than the old one (say IDE -> SATA), you have to install the new drivers etc first. With a little bit of tweaking, it should boot off the new disk. Read about boot.ini in this case.
After you did your backup, and tested it, you add the new disk to the server, and make a copy to the new disk. Then you remove the old disk and put it somewhere safe, make the new disk boot, and you are fine.
P.S. a dvd drive costs 15 bucks. Working around not having one is not cost effective. Just plug any old dvd into the server for as long as you need it.
The imaging path should be tested in a lab first, just to make sure you dont image the empty disk onto the full one.

A: The bootmgr and BCD may have been on a different partition when you used imagex to make a backup. This is the default for Windows Server 2008 R2 and Windows 7; 2008 and Vista it depended on if you enabled BitLocker, and which direction the wind was blowing that day. When you booted WinPE did it show both a C: and a D: drive? If so, keep reading.
Unfortunately this is a possibility in Server 2008 that I didn't cover in my previous post, my apologies if this is the case. It's a somewhat easy fix at least:

*

*Pop the old drive back in the server, and use imagex to grab both the Boot Partition (C:) and the System Partition (D:) (you'll have to run it twice to get both partitions, don't write both to the same WIM file, the second time will just overwrite the first).
imagex /capture C:\ Z:\MyServer-BootPartition.wim "MyServer"
imagex /capture D:\ Z:\MyServer-SystemPartition.wim "MyServer"

*Pop the new drive into the server. Create partitions like so in diskpart
sel drive 0
clean
create part pri size=100
format quick
act
assign letter=c
create part pri
format quick
assign letter=d
exit
Note: If you pick different letters than C and D above, substitute those letters in the following steps as well. The letters you assign in this step will not effect the letter assignment when windows boots, that's in the registry.

*Write the images to the drive partition (covered in the last post, but repeated here for clarity):
imagex /apply Z:\MyServer-BootPartition.wim 1 C:\
imagex /apply Z:\MyServer-SystemPartition.wim 1 D:\

*Modify the BCD for the new partitions.
Run: bcdedit -store C:\boot\BCD -enum and take note of the "identifier" line in the "Windows Boot Loader" section. It's usually "{current}" or "{default}" but could be a GUID. Whatever it is, substitute that identifier where I put {current} in the 2nd and 3rd line below.
bcdedit -store C:\boot\BCD -set {bootmgr} device partition=c:
bcdedit -store C:\boot\BCD -set {current} device partition=d:
bcdedit -store C:\boot\BCD -set {current} osdevice partition=d:

A: Install both drives. Convert both drives to dynamic. Add the second disk as a mirror. Let it replicate, then remove the old drive as mirror.
I'd recommend testing this in a lab before attempting it on a production system.


text:
Q: How to handle iterator::difference_type when you have no way of measuring the difference? I'm writing a C++ wrapper for a 3rd party C library.
The library provides some functions for iterating through a series of objects.
I want to write an iterator to wrap this behaviour so iteration is easier, but I cannot think how I will be able to provide the mandatory 'difference' type since the iterated objects don't have a meaningful relative order and the API I am working with does not provide a means of finding the number of objects available in advance.
I can't count the objects as they're iterated because although that would solve individual iterators it would render the difference between the end() iterator and other iterators undefined.

A: All iterators in C++ need to provide some sort of difference_type. Whether or not that type is meaningful or useful is a completely separate issue.
From what you're describing, it seems like you're working with an input iterator, which gives you the ability to make a single pass over a stream of data but not to back up or save positions in the stream. For input iterators, there's still a requirement to have a difference_type defined, but there's no meaningful way to take the difference of two iterators. The only way to measure distance is to manually count up how many elements you've seen as you go.
Using the default of std::ptrdiff_t is probably very reasonable here unless you have a data stream that can produce so many elements that you can't fit the number of them into a std::ptrdiff_t. Clients can then use this to count up how many things they've seen, even though your iterator doesn't actually let people compute distances between entries.


text:
Q: Data loss when uploading image data to PHP-Server I have an iOS App which should upload image data to my php server on Nginx with a POST request. I can upload the data but when I download it after, the uploaded file is corrupted and smaller and I can't open it.
I have changed the values for post_max_size, max_input_vars and upload_max_filesize high enough and have all permissions set correctly.
Here is my code:
App:
DispatchQueue.global().async {
    let url = "url to upload.php"

    var urlComponents = URLComponents(string: url!)
    urlComponents.queryItems = [
        URLQueryItem(name: "filetype", value: "img")
    ]

    var request = URLRequest(url: urlComponents.url!)
    request.httpMethod = "POST"

    let boundary = UUID().uuidString
    let contentType = "multipart/form-data; boundary=\(boundary)"

    var body = Data()

    body.append("--\(boundary)\r\n".data(using: .utf8)!)
    body.append("Content-Disposition: form-data; name=\"username\"\r\n\r\n".data(using: .utf8)!)
    body.append("\(username)\r\n".data(using: .utf8)!)

    body.append("--\(boundary)\r\n".data(using: .utf8)!)
    body.append("Content-Disposition: form-data; name=\"image-upload\"; filename=\"img.jpg\"".data(using: .utf8)!)
    body.append("Content-Type: image/jpeg".data(using: .utf8)!)
    body.append(imageData) // 2735963 bytes

    body.append("\r\n--\(boundary)--".data(using: .utf8)!)

    request.setValue(contentType, forHTTPHeaderField: "Content-Type")

    request.httpBody = body

    let task = URLSession.shared.dataTask(with: request) { data, response, error in

            if error != nil {
                print(error!.localizedDescription)
                return
            }

            let responseString = String(data: data!, encoding: .utf8)
            print(responseString!) // final data stored on server: 2734537 bytes

    }
    task.resume()
}

PHP:
<?php

$user = $_POST['username'];///I need this for the path
$username = str_replace(array("\r", "\n", "'"), '', $user);
$type = $_GET['filetype'];

if ($type == "img")
{
    $path = "path to save img.jpg";
    $image = $_FILES['image-upload']['tmp_name'];

    if (move_uploaded_file($image, $path)) {
        echo "Success";
    }
    else
    {
        echo "Failed";
    }
}

?>

Is anything wrong with it?

A: You're missing the \r\n\r\n after Content-Type: image/jpeg.
E.g.:
body.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)

And you probably need it after the final boundary, too:
body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

Also, we generally do not set Content-Length. Let URLSession do that for you.
See https://stackoverflow.com/a/26163136/1271826 or consider using a library like Alamofire which gets you out of the weeds of preparing a multipart request.


text:
Q: Bash grep from text file and edit I am doing a update on the file test.txt which stores some info about storybooks
I've the code below for the function but i realise that using this method of grep, i am unable to get the rest of the values for price quantity and sold which are not mentioned in the grep command.
Is there a better command i can use for this case?
Thanks in advance for replies. :)
echo "Title: "
read title
echo ""
echo "Author: "
read author
echo ""
echo "Number of copies sold: "
read numSold

if grep -iq "$title:$author:" test.txt
then
echo "Current Book Info :"
echo "$title, $author, $price, $quantity, $sold"
echo ""

newQuantity=`expr $quantity - $numSold`
newSold=`expr $sold + $numSold`
sed -i "s/^\($title:$author:[^:]*\):[^:]*:/\1:$newQuantity:/" BookDB.txt
sed -i "s/^\($title:$author:.*\):.*$/\1:$newSold/" BookDB.txt

echo "New Book Info :"
echo "$title, $author, $price, $quantity, $sold"
fi

A: Well unfortunately the build of the test.txt is unknow.
If you could show an example that can help.
But if the Price quantity and other staff are in the 1-2 line away from the line you grepping you can use the grep -A 2 (which will grep 2 next lines) or -B 2 (2 lines from above)
after that u can just remove the '\n'from the results and print it :
grep -A 2 "$title:$author:*" | tr '\n' ' '

this will give you a line (build out of 3 lines) with all the data.
Of course its based on the how test.txt is build.
some thing like this :
> grep -A 2 "Konan Doil:Story" test.txt
Konan Doil:Story
Price - $$$$$
Quantity - XXXX, Sold - 99999

In response to the comment below :
I think its better then use array to save the input. after that u can do
with array what ever you want as the values are same
(Index 0 = Author, 1 = Book Name ... etc.)
 >IFS=$':'; i=0 ; for line in $(grep "Konan Doil:Good" test.txt) ; do arr[$i]=$line; i=$(($i + 1)) ; done
 >echo "${arr[0]}"
Konan Doil
>echo "${arr[1]}"
Good story
 >echo "${arr[3]}"
XXXXX
 >echo "${arr[4]}"
YYYYYY
 >echo "${arr[2]}"
$$$$$
 >


text:
Q: The result of []==false is true, why? In ES5, The Abstract Equality Comparison Algorithm:
If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
To Number Conversions Algorithm:If x is an Object, the firstStep is to get primValue, and then it will return ToNumber(primValue).
To Primitive Conversions Algorithm:  Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType.
[[DefaultValue]] uses "valueOf" method, and returns a primitive value.
The question is: Object.ValueOf method  gets a Object value not a primitive Value. it confuses me .
let a=[]
let b=a.valueOf()// object a
console.log(b)
let c=a.toString()//undefined
console.log(c)
typeof b //object
typeof c //string


text:
Q: spark-kafka-integration This tag is related to the spark-streaming-kafka and spark-sql-kafka libraries.
External sources:

*

*Spark Streaming + Kafka Integration Guide

*Structured Streaming + Kafka Integration Guide
To precise your question, you can consider adding

*

*spark-streaming or

*spark-structured-streaming
This tag serves as a synonym for the existing (low traffic) tag spark-streaming-kafka which only focuses on Spark Streaming (not batch and not Structured Streaming).


text:
Q: Carregar "php.ini" especifico para um sub-domínio Para carregar um php.ini personalizado para um sub-domínio, apliquei no .htaccess na raiz do sub-domínio em questão o seguinte código:
AddHandler php5-fastcgi .php
Action php5-fastcgi /cgi-bin/php.fcgi

O ficheiro só tem estas duas linhas.
O mesmo carrega as definições em condições e de forma independente do domínio principal, que consigo ver através do phpinfo().
Problema
Com a linha em cima presente no .htaccess, deixo de conseguir aceder ao sub-domínio, só conseguindo aceder ao mesmo através do domínio principal seguido da pasta onde se encontra o sub-domínio:
Acesso pretendido:
http://sub.dominio.com/

Acesso que funciona com as directivas em cima:
http://www.dominio.com/sub/

Nota:
No htaccess na raiz do domínio principal existem diversas directivas para uso do mod_rewrite.c, mod_deflate.c, Options, IndexIgnore, Header, as quais se relevantes para o problema poderei adicionar aqui.

Pergunta
O que falta ou estou a fazer de errado para perder o acesso directo via sub-domínio quando tenho as duas linhas no .htaccess do mesmo?

A: Use a diretiva PHPINIDir na configuração de virtual host do site para o qual você quer especificar um php.ini personalizado.
<VirtualHost 1.2.3.4:80>
    PHPINIDir /var/www/web1
</VirtualHost>


text:
Q: repaint JPanel with every click at JList everytime i click on a JList item, i need to clear + refresh my current panel & load another panel, returned via method 'populateWithButtons()'. temp is an int variable that stores what was clicked at the JList. How do i rectify the following?
        list_1.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent evt) {

                //refresh + populate JPanel
                Food food = new Food();
                JPanel panel2 = new JPanel();
                JPanel pane11 = new JPanel();

                panel2.add(panel1);
                panel1.validate();
                panel1.repaint();
                panel1.setBounds(153, 74, 281, 269);

                panel1.add(food.populateWithButtons(temp));
                contentPane.add(panel2);
        }

A: *

*don't to use NullLayout

*add ListSelectionListener to JList instead of MouseListener, otherwise you would need to convert point from mouse to Item in JList

*use CardLayout instead of add, remove JPanels on runtime, then selection from ListSelectionListener (ListSelectionModel to SINGLE...) to switch prepared card (JPanel with some contents)
EDIT

.

.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class CardlayoutTest {

    private Color[] colors = new Color[]{Color.BLACK, Color.RED, Color.GREEN, Color.BLUE};
    private JFrame frame = new JFrame();
    private JList list = new JList();
    private JPanel panel = new JPanel();
    private CardLayout card = new CardLayout();

    public CardlayoutTest() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel.setLayout(card);
        Vector<String> items = new Vector<String>();
        for (int x = 0; x < colors.length; x++) {
            JPanel pnl = new JPanel(new BorderLayout());
            pnl.setBackground(colors[x]);
            panel.add(pnl, colors[x].toString());
            items.add(colors[x].toString());
        }
        list = new JList(items);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    String card = list.getSelectedValue().toString();
                    CardLayout cL = (CardLayout) (panel.getLayout());
                    cL.show(panel, card);
                }
            }
        });
        frame.add(new JScrollPane(list), BorderLayout.WEST);
        frame.add(panel);
        frame.setPreferredSize(new Dimension(400, 150));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CardlayoutTest();
            }
        });
    }
}

A: move validate() and repaint() after adding to contentPane as in that point it will be redrawed.


text:
Q: transition treemap diagram in d3.js I am loading data  from a google spreadsheet that contains the GDP of selected countries from the 1955 to 2012. From this I want to draw a treemap. So far so good.
I've loaded the data through out internal link and formatted into an object that d3 can handle, then got the layout to draw on the screen-all well and good. I've based it on the Mike Bostock tutorial at http://bl.ocks.org/mbostock/4063582.
The problem comes when I try to transition from a set of data from say 1955 to 2010. I'm confident that the function I'm using to generate the treemap layout is working because the initial display is correct. I pass it a date and it creates the treemap structure.
However when I trigger a change the transition seems to occur and the individual squares change size. But when I examine them I realise that they are all wrong and that I seem to have mapped the new set of value onto the wrong countries.
The newstructure looks visually correct but all the names are wrong. So I get things like cyprus having the largest GDP in 2012. Its as if I've got a list in alphabetical order thats having another set of values in order of magnitude applied to the rather that the new value for say the US being mapped the old value.
Going around in circles here as I'm still faily new to d3 so all help gratefully received.
Code looks like this:
/*global app:true JST:true d3:true*/

(function (window, $) {

'use strict';

var menuItems = [];
var menuType='measure';
var checboxItems= ['advanced','emerging'];
var ddID = '0';
var model=[];
var yearValue="2012"
var group="gdp";
var treeStruc={
name:[],
children:[]
}

var margin = {top: 25, right: 5, bottom: 5, left: 5},
width = 965 - margin.left - margin.right,
height = 650 - margin.top - margin.bottom;

var color = d3.scale.category10();

app.spreadsheet.get(function (data) {
// TODO: process the data
menuItems = data.measures
//console.log(data);
//console.log('menuItems', menuItems);
//crete dropdown and use toggle to swich display on and off
$('#dropDown').click(function () {
  $('ul.ddMenuList').toggle();
});
//populate the dropdown menu
for (var k = 0; k <menuItems.length; k++) {
  $('#ddList').append('
'+menuItems[k].menulist     +'
');
};
//add functionality to dropDown menu
$('#ddList li').bind('click', function () {
  ddID = this.id.split('_')[1];
      var text = $(this).text();
  //console.log ("ID=",ddID);
  //console.log (text, "Measure=",menuItems[ddID].type);
  $('#ddTitle').empty();
  $('#ddTitle').append(text);
  createCheckboxes()
});

function createCheckboxes() {
//decide which check boxes to populate
if (menuItems[ddID].type==="measure") {
  group=menuItems[ddID].type
  checboxItems=[];
  $.each(menuItems, function (i) {
    if (menuItems[i].type==="group"){
      checboxItems.push (menuItems[i].checkbox);
    }
    //console.log (checboxItems);
  });
}
    else {
  group=menuItems[ddID].type
  checboxItems=[];
  $.each(menuItems, function (i) {
    if (menuItems[i].type==="measure"){
      checboxItems.push (menuItems[i].checkbox);
    }
    //console.log (checboxItems);
  });
}
//Populate the check boxes
console.log ("Populating check boxes");
$('#cbHolder').empty();
$('#cbHolder').append('<form>');
    $.each(checboxItems, function (i) {
  $('#cbHolder').append('<input type="checkbox" id="cb_'+i+'">'+checboxItems[i]);
  $('#cbHolder').append('</form>');
  //console.log ("checkboxItems",checboxItems[i]);
});
changed3 ()

}

//creates an object containing just the advanced countries
treeStruc={name:[],children:[]};
console.log ("group=",group);
$.each(checboxItems, function (k) {
  console.log("Parent",checboxItems[k])
  model=jQuery.grep(data.stats,function(e,i){return e[checboxItems[k]];});
  console.log('model', model);
  treeStruc.children.push({"name":checboxItems[k],"children":[]});
  //Construct the children of 1 big group to be completed to be updated for each sheet
  $.each(model, function (i) {
  treeStruc.children[k].children.push({'name':model[i].countryname,'size':model[i]    [group]});
  });
});

console.log('treeStruc', treeStruc)
Handlebars.createOptionsHelper(data.options);
drawd3 ();
});

function generateTreemapLayout(filter){
  return d3.layout.treemap()
    .size([width, height])
    .sticky(true)
    .value(function(d) {
      if(d.size[filter] < 0){
        return 0;
      }
  return d.size[filter];
    });
  }

function drawd3() {
  console.log ("function drawd3");
  var treemap = generateTreemapLayout('y'+yearValue)

  var div = d3.select("#d3Object").append("div")
    .style("position", "relative")
    .style("width", (width + margin.left + margin.right) + "px")
    .style("height", (height + margin.top + margin.bottom) + "px")
    .style("left", margin.left + "px")
    .style("top", margin.top + "px");

    var node = div.datum(treeStruc).selectAll(".node")
      .data(treemap.nodes)
    .enter().append("div")
      .attr("class", "node")
      .call(position)
      .attr("id",function(d){
        return d.name;
      })
      .style("background", function(d) { return d.children ? color(d.name) : null; })
      .text(function(d) { return d.children ? null : d.name; });

    };
    function position() {
      this.style("left", function(d) { return d.x + "px"; })
          .style("top", function(d) { return d.y + "px"; })
          .style("width", function(d) { return Math.max(0, d.dx - 1) + "px"; })
          .style("height", function(d) { return Math.max(0, d.dy - 1) + "px"; });
}

function changed3() {
    console.log ("function changed3");
    //make a new treemap layout
    var treemap = generateTreemapLayout('y'+1955);
    console.log('treeStruc',treeStruc);
    //redraw the treemap using transition instead of enter

    var node = d3.select("#d3Object")
    .datum(treeStruc).selectAll(".node")
    .data(treemap.nodes)
    .transition()
    .duration(1500)
    .call(position)

  }

}(this, jQuery));

A: Many thanks to Tom Pearson my work colleague for this. The problem lies in where the data is bound to the item on the page. When you come to re draw the treemap because the data isn't bound to the div with a nique identifier like the object name it re maps the data to the first item o the list as it where. This means that something like China's gets given Belgium's information. simple solution is as follows Instead of
.data(treemap.nodes)

use
 .data(treemap.nodes,function(d){
  return d.name;
})

The are two instances of this in the original drawd3 function them in the changed3 function. Hope that helps anyone stuck with something similar


text:
Q: Importing nested name-value pairs from json into SQL Server I am importing a json file into SQL 2016 which has some nested name-value pairs in a nested values structure. It's the values from these pairs I am having problems with, such as .
{ "name": "Colour", "value": "Orange" }, { "name": "Calories", "value": "25" }

sql:
Declare @JSON varchar(max)
SELECT @JSON = BulkColumn
FROM OPENROWSET (BULK 'C:\temp\fruit.json', SINGLE_CLOB) as j

If (ISJSON(@JSON)=1) BEGIN
    Select * from openjson ( @JSON )
    WITH(
        id int,
        fruit varchar(20),
        Colour varchar(20) '$.values.Colour',
        Weight int '$.values.Weight'
    ) as Orders
END
ELSE
  Select 'JSON is invalid!'

and the results of which are:
id  fruit   Colour  Weight
1   orange  NULL    NULL
23  Banana  NULL    NULL

full (test) data..
[
    {
      "id": 1,
      "fruit": "orange",
      "values": [
        { "name": "Colour", "value": "Orange" },
        { "name": "Weight", "value": "16" },
        { "name": "Calories", "value": "25" }
      ]
    },
    {
      "id": 23,
      "fruit": "Banana",
      "values": [
        { "name": "Colour", "value": "Yellow" },
        { "name": "Weight", "value": "30" },
        { "name": "Calories", "value": "250" }
      ]
    }
  ]

A: You may try with next approach, which will return full data:
DECLARE @json nvarchar(max)
SET @json = N'[ { "id": 1, "fruit": "orange", "values": [ { "name": "Colour", "value": "Orange" }, { "name": "Weight", "value": "16" }, { "name": "Calories", "value": "25" } ] }, { "id": 23, "fruit": "Banana", "values": [ { "name": "Colour", "value": "Yellow" }, { "name": "Weight", "value": "30" }, { "name": "Calories", "value": "250" } ] } ]'

SELECT i.id, i.fruit, v.[name], v.[value]
FROM OPENJSON(@json)
WITH (
   id int '$.id',
   fruit nvarchar(50) '$.fruit',
   [values] nvarchar(max) '$.values' AS JSON
) AS i
CROSS APPLY (
   SELECT *
   FROM OPENJSON(i.[values])
   WITH (
      [name] nvarchar(max) '$.name',
      [value] nvarchar(max) '$.value'
   )
) v

Output:
id  fruit   name     value
1   orange  Colour   Orange
1   orange  Weight   16
1   orange  Calories 25
23  Banana  Colour   Yellow
23  Banana  Weight   30
23  Banana  Calories 250

If you want output with information about color and weight, try this:
DECLARE @json nvarchar(max)
SET @json = N'[ { "id": 1, "fruit": "orange", "values": [ { "name": "Colour", "value": "Orange" }, { "name": "Weight", "value": "16" }, { "name": "Calories", "value": "25" } ] }, { "id": 23, "fruit": "Banana", "values": [ { "name": "Colour", "value": "Yellow" }, { "name": "Weight", "value": "30" }, { "name": "Calories", "value": "250" } ] } ]'

SELECT i.id, i.fruit, v1.[value] AS Colour, v2.[value] AS Weight
FROM OPENJSON(@json)
WITH (
   id int '$.id',
   fruit nvarchar(50) '$.fruit',
   [values] nvarchar(max) '$.values' AS JSON
) AS i
OUTER APPLY (
   SELECT *
   FROM OPENJSON(i.[values])
   WITH (
      [name] nvarchar(max) '$.name',
      [value] nvarchar(max) '$.value'
   )
   WHERE [name] = 'Colour'
) v1
OUTER APPLY (
   SELECT *
   FROM OPENJSON(i.[values])
   WITH (
      [name] nvarchar(max) '$.name',
      [value] nvarchar(max) '$.value'
   )
   WHERE [name] = 'Weight'
) v2

Output:
id  fruit   Colour  Weight
1   orange  Orange  16
23  Banana  Yellow  30


text:
Q: How can I change ng-click behavior for a single element in an ng-repeat? I am refactoring a table written in angular. Currently ng-repeat is used to create multiple tables rows, any of which will redirect to a given ui-sref when clicked upon:

                {{user.name}}
                {{user.attending ? 'Yes' : 'No'}}
                {{user.interestDeclared}}
                {{user.interestThreeOrGreater}}
                {{user.github}}
                {{user.email}}
                {{user.city}}
                {{user.searchStage === 'Out' ? 'Opted Out' : user.searchStage}}

I need to replace the 2nd td, currently displaying 'Yes' or 'No' with a checkbox, the problem being that the check box needs to be toggled when clicked on, and not redirect to the ui-sref like the rest of the td's.
I have a working solution which is to hardcode the ui-sref into every  except for the checkbox:

                {{user.name}}
                <input type="checkbox" ng-model="user.attending">
                {{user.interestDeclared}}
                {{user.interestThreeOrGreater}}
                {{user.github}}
                {{user.email}}
                {{user.city}}
                {{user.searchStage === 'Out' ? 'Opted Out' : user.searchStage}}

Is there another, more elegant and/or Angular way to implement this solution?

A: You can simply do this:

            {{user.name}}
            <input type="checkbox" ng-model="user.attending">
            {{user.interestDeclared}}
            {{user.interestThreeOrGreater}}
            {{user.github}}
            {{user.email}}
            {{user.city}}
            {{user.searchStage === 'Out' ? 'Opted Out' : user.searchStage}}

A: You could do something like:
{{user.attending ? 'Yes' : 'No'}}

$scope.dontSref = function(e) {
    e.preventDefault();
    e.stopPropagation();
}

Basically, since your element will get the click event first, you should be able to stop it from propagating to it's parent, which will prevent it from following the link.
http://jsfiddle.net/H2jUH/


text:
Q: cannot log into openstack instances After I reboot my openstack nodes I cannot seem to ssh into any of the instances that I have created. I cannot ping their IP's or even use the web console to load on the browser to be able to login. i can ping management and provider gateway from the controller.
I have used the default openstack setup with selfservice network options 2 using the default ip addressing and networks in the installation guides
my controller is 10.0.0.11
my instance has 172.16.1.190, 203.0.113.78
I can ping 203.0.113.1
here is my routing table
$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.0.0.1        0.0.0.0         UG    0      0        0 enp1s0
0.0.0.0         203.0.113.1     0.0.0.0         UG    100    0        0 brq5425fcec-c8
10.0.0.0        0.0.0.0         255.255.255.0   U     0      0        0 enp1s0
192.168.122.0   0.0.0.0         255.255.255.0   U     0      0        0 virbr0
203.0.113.0     0.0.0.0         255.255.255.0   U     0      0        0 brq5425fcec-c8

my netplan config
$ cat /etc/netplan/*
# This is the network config written by 'subiquity'
network:
  ethernets:
    enp1s0:
      addresses:
      - 10.0.0.11/24
      gateway4: 10.0.0.1
      nameservers:
        addresses:
        - 8.8.8.8
        - 8.8.4.4
        - 10.0.0.1
        search: []
  version: 2
network:
  ethernets:
    enp7s0:
      addresses:
      - 203.0.113.11/24
      gateway4: 203.0.113.1
      nameservers:
        addresses:
        - 8.8.8.8
        - 8.8.4.4
        - 203.0.113.1
        search: []
  version: 2

I am using ubuntu 22.04 LTS, openstack yoga installation


text:
Q: SQL Where clause in ORACLE How can i use the END_DATE/START_DATE from the first sub select in the second subselect?, the provided values are only examples. (06/01/2010).
SELECT "PROJECT"."ID",
        "PROJECT"."CLIENT",
        "PROJECT"."NAME",
        "PROJECT"."STATE",
        "PROJECT"."EARLIEST_START",
        "PROJECT"."LATEST_END",
        "PROJECT"."EFFORT",
        "PROJECT"."LINK",
        "PROJECT"."STATUS",
        "PROJECT"."DESCRIPTION",
        (SELECT SUM((END_DATE - START_DATE + 1) * (WORKLOAD / 100))
           FROM WORKITEM WHERE PROJECT = PROJECT.ID
        ) AS "P_A",
        (SELECT COUNT(*)
          FROM PUBLIC_HOLIDAY
          WHERE HOLIDAY_DATE BETWEEN TO_DATE('06/1/2010','MM/DD/YYYY') AND
                                   TO_DATE('06/2/2010','MM/DD/YYYY')) AS P_B,
        "PROJECT_STATE"."STATE",
        "PERSON"."DISPLAY_NAME" AS "RESPONSIBLE"
        FROM "PROJECT"
        INNER JOIN "PROJECT_STATE" ON PROJECT.STATE = PROJECT_STATE.ID
        INNER JOIN "PERSON" ON RESPONSIBLE = PERSON.ID
        WHERE (PROJECT.CLIENT = '1') AND (PROJECT.STATE = 1)
        ORDER BY "PROJECT"."NAME" ASC

A: Here is one way to use start_date and end_date in more than one place
with (select to_date('06/01/2010','MM/DD/YYYY') as start_date,
             to_date('06/02/2010','MM/DD/YYYY') as end_date
        from dual) as q1
select project.id,
       project_state.state,
       q1.start_date,
       q1.end_date,
       (SELECT SUM((q1.END_DATE - q1.START_DATE + 1) * (WORKLOAD / 100))
       FROM WORKITEM WHERE PROJECT = PROJECT.ID) AS P_A
 from project
 join project_state on project_state.id = project.state
 join q1 on 1=1

A: You cannot.
You could make a single subselect from the two using a join, and move the new composite subselect from the SELECT part to the FROM part of the main query.

A: Is this what you are looking for
    SELECT "PROJECT"."ID",
        "PROJECT"."CLIENT",
        "PROJECT"."NAME",
        "PROJECT"."STATE",
        "PROJECT"."EARLIEST_START",
        "PROJECT"."LATEST_END",
        "PROJECT"."EFFORT",
        "PROJECT"."LINK",
        "PROJECT"."STATUS",
        "PROJECT"."DESCRIPTION",
        (SELECT SUM((END_DATE - START_DATE + 1) * (WORKLOAD / 100))
           FROM WORKITEM WHERE PROJECT = PROJECT.ID
        ) AS "P_A",
        (SELECT COUNT(*)
          FROM PUBLIC_HOLIDAY
          WHERE HOLIDAY_DATE BETWEEN NVL(END_DATE,SYSDATE) AND
                                   NVL(START_DATE,SYSDATE)) AS P_B,
        "PROJECT_STATE"."STATE",
        "PERSON"."DISPLAY_NAME" AS "RESPONSIBLE"
        FROM "PROJECT"
        INNER JOIN "PROJECT_STATE" ON PROJECT.STATE = PROJECT_STATE.ID
        INNER JOIN "PERSON" ON RESPONSIBLE = PERSON.ID
        LEFT JOIN "WORKITEM" ON WORKITEM.PROJECT = WORKITEM.ID
        WHERE (PROJECT.CLIENT = '1') AND (PROJECT.STATE = 1)
        ORDER BY "PROJECT"."NAME" ASC


text:
Q: file include with if condition in php? My html is like this
<form name="time" method="POST" action="add.php">
    <input type="text" name="empcode" id="empcode" class="textbox" placeholder="822"/>

    <input type="text" name="totaltime" id="totaltime" class="textbox" value = "50" />

    Start Date<input type="date" name="sday">

    End Date<input type="date" name="eday">

    <input type="submit" class="submit-button" value="Submit"/>
</form>

When user fill data in $_POST['sday'] and $_POST['sday'] the add.php file will include file.php otherwise file2.php
I tried this in add.php
if(isset($_POST['sday']) && isset($_POST['eday'])){
    include('file1.php');
}
else{
    include('file2.php');
}

But its not working should I check with zero value ?

A: Use !empty() instead of isset().  those fields will always be set, at least to an empty string.
if ( !empty($_POST['sday']) && !empty($_POST['eday']) ) {

A: isset() only checks whether a variable is defined and not equal to null. If a posted value is not filled in, it will most likely be an empty string.
Therefore, you should check for empty strings, too:
if (isset($_POST['sday'], $_POST['eday']) &&
        strlen($_POST['sday']) &&
        strlen($_POST['eday'])) {

Why not empty()?
You could use empty() as well, but due to empty('0') yielding true you would need an extra condition leading to more cumbersome code.


text:
Q: Is it possible to make a coil-less simple Shortwave Receiver I am really a newbie here in Electronics and I'm into it as a hobby/passtime.
I was going through this simple coil-less Shortwave Transmitter circuit on a blog.

Q1 – BC548, X1 – 10.7 MHz ceramic resonator, 3 terminal, C1 – 10 nF, C2 – 100 nF, C3 – 100 pF, R1 – 10 kOhm, R2 – 150 kOhm, R3 – 1 kOhm
My questions are:

*

*Does circuits like this work? I want to know how this circuit oscillates at a shortwave frequency without LC Tanks. Is it entirely done by the ceramic resonator?

*Can I create a similar circuit to receive Shortwave audio signal, which won't use a old-days coil and ferrite rod? If someone could help me with a simple circuit diagram for a shortwave radio receiver which uses such ceramic resonator I will be grateful. I couldn't find it on the web.

A: *

*Yes, a circuit such as you've shown can emit rf. It functions similar to a pierce crystal oscillator...something for you to Google.  However, without "old days coils " to form a tank circuit, there's a good chance it emits not only at 10.7 MHz but on 21.4 and 32.1 MHz as well.  I won't go into licensing aspects here.

*A receiver can be as simple as a diode, capacitor, and a good ground and antenna.  No coil.  Of course, it will receive only the strongest signal and no way to tune it.  On the other end of the no old days coil design, a fast A/D, a processor such as a DSP, sprinkled with software, you can have what's called a software defined radio or SDR.
Coils have their place.  They're not something that goes out of style.

A: Ceramic and Crystal resonators are very high Q resonators with equivalent circuits the same as an LC parallel tank cct here.  ( Q= 5k to 10k )  They work by passing a bandpass where the phase shift is 180 deg together with C3 such that with the inverting transistor the result is some gain with positive feedback to become an oscillator.
Which won't use a old-days coil and ferrite rod?
You would need multiple stages of ceramic and crystal bandpass filters.  Coils are good for the intial stage LC resonant band filter with high passive gain.
Coils are very useful and should not be ignored.

But here are some ways of finding more info by adding keywords


text:
Q: How can I make it so only 1 "if-statement" is used if 2 are in the action In a game...
When the "done" button is pressed, there are 2 'if-statements': one brings you to the next level and the other returns you home. How can I make it so only one happens at a time? The way it works now, is both the winning and losing 'alertviews' pop up no matter if the user got it right or wrong. This is how it looks:
-(IBAction)done {

    if ([entry.text isEqualToString:sentance.text]) {

        UIAlertView *alert = [[UIAlertView alloc]
                             initWithTitle:@"Cleared!"
                             message:@""
                             delegate:nil
                             cancelButtonTitle:@"Ok"
                             otherButtonTitles: nil];
        [alert show];
        [alert release];

        seconds.text = @"5 Seconds";
    }

    if ([entry.text isEqualToString:entry.text]) {

        NSString *nssScore= [NSString stringWithFormat:@"Final Score: \n %i Points", Score];

        UIAlertView *alert = [[UIAlertView alloc]
                             initWithTitle:@"Nope! Wrong"
                             message:nssScore
                             delegate:nil
                             cancelButtonTitle:@"Ok"
                             otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}

A: There is something wrong with your second if.
if ([entry.text isEqualToString:entry.text]) {

This if is always true, since why should entry.text not be equal to itself?
Also if you have two if statements and only one shall be true, you always use a else if for the second one:
if (<condition>) {

} else if (<other condition>) {

}

If condition is true, the other if is not executed, even if other condition is also true. However, in your case your second if seems nonsense to me. An if that is always true is useless and be left out completely. The code is equivalent to
if (<condition>) {

} else {

}

A: You can use else if condition.
Like this :
-(IBAction)done {

    if ([entry.text isEqualToString:sentance.text]) {

        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Cleared!"
                              message:@""
                              delegate:nil
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles: nil];
        [alert show];
        [alert release];

        seconds.text = @"5 Seconds";
    }
    else if ([entry.text isEqualToString:entry.text]) {

        NSString *nssScore= [NSString stringWithFormat:@"Final Score: \n %i Points", Score];

        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Nope! Wrong"
                              message:nssScore
                              delegate:nil
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}

or you can add a line of code in each block "return;"
like this:

A: I got the answer guys...
    if ([a.text isEqualToString:b.text] == FALSE) {

condition

}

Thanks!


text:
Q: a href click not triggering in jquery         $(function() {

            $.getJSON("companies.json", function(response) {

                var html = '
';
                response.businesses.forEach(function(row) {
                    html += '
' + row.id + '	' + row.name;
                });
                html += '
';

                $("#tabledata").html(html);
            });

            $(".move").click(function() {

                var $id = $(this).attr("idname");

                $.getJSON("companies.json", function(response) {

                    $.map(response.businesses, function(obj) {
                        if (obj.id == $id)
                            console.log(obj);
                        return obj; // or return obj.name, whatever.
                    });
                });
            });
        });

HTML:

Please help?

A: If you use event delegation, your problem goes away (and your app becomes more performant and less prone to memory leaks).
// Only do this once, when your page loads...
$(document.body).on('click', '.move', function (ev) {
    // This is the link that was clicked.
    var $targ = $(ev.target);
});

A: As your .move element is added to your page dynamically, you have to make use of jQuery's on() method to delegate the event to an ancestor of the .move element which does exist when your JavaScript first loads.
$(document).on('click', '.move', function() { ... });

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

You can read more about jQuery's event delegation here.

A: Try This
$('#tabledata').on('click', '.move', function(e) { ... });

A: The reason the event isn't being triggered is because the event is only added to elements that exist on the page when you call the .click() method.
Instead, you can use event delegation:
$(document.body).on('click', '.move', function (ev) {
    var $targ = $(ev.target);
});

which really says: call the function when any element that matches .move that's inside document.body is clicked.
I know others have said this already but I wanted to make event delegation clearer.


text:
Q: CSS
* does not extend I have
 list and inside
 i have link
I want the
 not to be influenced by the content and have fixed size.
My CSS
 ul.files {
    display: inline-block;
    padding: 0;
    margin: 0 auto;
}

ul.files li {
    display: inline;

}

ul.files li a {

    color: black;
    float: left;
    padding: 8px 15px;
    text-decoration: none;
    border: 1px solid #ddd;
    margin: 0 3px;
    background-color: #ffffff;
}

My HTML

    123

A: To be able to set fixed width and height to
 you need to change display: inline; to inline-block
ul.files li {
    display: inline-block;
    width: 150px;
    height: 150px;
}

To center text
To center content of li you can use display: inline-flex
ul.files li {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 150px;
  height: 150px;
}


text:
Q: why a lemma shows well-definedness of linear transformations The following lemma can be used to show that some linear transformations are well-defined. I don't quite see that. I mean, if a linear transformation $T$ is well-defined, then if $x=y$ then $T(x)=T(y)$. Can someone explain why this lemma shows well-definedness? I even provided an example where the authors of the book claim that a linear transformation is well-defined because of that lemma. I can't figure out why. If someone could clarify this, I'd be so grateful!

A: "Well-defined" is not just used in the sense you gave, but can be used for any kind of situation where it is not immediately obvious that the formula that you write down for a function makes sense.  In this particular case, you have an infinite sum, and for that to make sense, you must check that the sum converges.  Lemma 4.3 shows that the sum converges, so the function is well-defined.


text:
Q: Spring nested transactions In my Spring Boot project I have implemented following service method:
@Transactional
public boolean validateBoard(Board board) {
    boolean result = false;
    if (inProgress(board)) {
        if (!canPlayWithCurrentBoard(board)) {
            update(board, new Date(), Board.AFK);
            throw new InvalidStateException(ErrorMessage.BOARD_TIMEOUT_REACHED);
        }
        if (!canSelectCards(board)) {
            update(board, new Date(), Board.COMPLETED);
            throw new InvalidStateException(ErrorMessage.ALL_BOARD_CARDS_ALREADY_SELECTED);
        }
        result = true;
    }
    return result;
}

Inside this method I use another service method which is called update:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Board update(Board board, Date finishedDate, Integer status) {
    board.setStatus(status);
    board.setFinishedDate(finishedDate);

    return boardRepository.save(board);
}

I need to commit changes to database in update method independently of the owner transaction which is started in validateBoard method. Right now any changes is rolling back in case of any exception.
Even with @Transactional(propagation = Propagation.REQUIRES_NEW) it doesn't work.
How to correctly do this with Spring and allow nested transactions ?

A: Using "self" inject pattern you can resolve this issue.
sample code like below:
@Service @Transactional
public class YourService {
   //... your member

   @Autowired
   private YourService self;   //inject proxy as an instance member variable ;

   @Transactional(propagation= Propagation.REQUIRES_NEW)
   public void methodFoo() {
      //...
   }

   public void methodBar() {
      //call self.methodFoo() rather than this.methodFoo()
      self.methodFoo();
   }
}

The point is using "self" rather than "this".

A: The basic thumb rule in terms of nested Transactions is that they are completely dependent on the underlying database, i.e. support for Nested Transactions and their handling is database dependent and varies with it.
In some databases, changes made by the nested transaction are not seen by the 'host' transaction until the nested transaction is committed. This can be achieved using Transaction isolation in @Transactional (isolation = "")
You need to identify the place in your code from where an exception is thrown, i.e. from the parent method: "validateBoard" or from the child method: "update".
Your code snippet shows that you are explicitly throwing the exceptions.
YOU MUST KNOW::

In its default configuration, Spring Framework's transaction
  infrastructure code only marks a transaction for rollback in the case
  of runtime, unchecked exceptions; that is when the thrown exception is
  an instance or subclass of RuntimeException.

But @Transactional never rolls back a transaction for any checked exception.
Thus, Spring allows you to define

*

*Exception for which transaction should be rollbacked

*Exception for which transaction shouldn't be rollbacked

Try annotating your child method: update with @Transactional(no-rollback-for="ExceptionName") or your parent method.

A: This documentation covers your problem - https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html#transaction-declarative-annotations

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. @PostConstruct.

However, there is an option to switch to AspectJ mode

A: Your transaction annotation in update method will not be regarded by Spring transaction infrastructure if called from some method of same class. For more understanding on how Spring transaction infrastructure works please refer to this.

A: Your problem is a method's call from another method inside the same proxy.It's self-invocation.
In your case, you can easily fix it without moving a method inside another service (why do you need to create another service just for moving some method from one service to another just for avoid self-invocation?), just to call the second method not directly from current class, but from spring container. In this case you call proxy second method with transaction not with self-invocatio.
This principle is useful for any proxy-object when you need self-invocation, not only a transactional proxy.
@Service
class SomeService ..... {
    -->> @Autorired
    -->> private ApplicationContext context;
    -->> //or with implementing ApplicationContextAware

    @Transactional(any propagation , it's not important in this case)
    public boolean methodOne(SomeObject object) {
      .......
       -->> here you get a proxy from context and call a method from this proxy
       -->>context.getBean(SomeService.class).
            methodTwo(object);
      ......
   }

    @Transactional(any propagation , it's not important in this case)public boolean
    methodTwo(SomeObject object) {
    .......
   }
}

when you do call context.getBean(SomeService.class).methodTwo(object); container returns proxy object and on this proxy you can call methodTwo(...) with transaction.

A: *

*You could create a new service (CustomTransactionalService) that will run your code in a new transaction :
@Service
public class CustomTransactionalService {

    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public <U> U runInNewTransaction(final Supplier<U> supplier) {
        return supplier.get();
    }

    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void runInNewTransaction(final Runnable runnable) {
        runnable.run();
    }
}

*And then :
@Service
public class YourService {

   @Autowired
   private CustomTransactionalService customTransactionalService;

   @Transactional
   public boolean validateBoard(Board board) {
      // ...
   }

   public Board update(Board board, Date finishedDate, Integer status) {
      this.customTransactionalService.runInNewTransaction(() -> {
          // ...
      });
   }
}


text:
Q: How does .NET Core on Linux determine what port a SQL Server instance listens on? I have an ASP.NET Core 1.1 Web API which runs in a Docker container on Ubuntu and connects out to a SQL Server database (SQL Server 2012 SP3) on a Windows server.  This works in 3 out of 4 of out environments, but in one environment it cannot connect to the SQL Server and I am trying to troubleshoot it.
The error is:

Unhandled Exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 25 - Connection string is not valid)

The SQL Server has an instance name: SQLSERVER1\APPS.  From the Linux server I can ping the server SQLSERVER1 and telnet to SQLSERVER1 1372 (1372 is the port for the APPS instance: so network connectivity is there.
The only space I can see for the problem to occur is how .NET Core translates the instance name to a port number.  Does anyone know how this is done and whether it is configurable on the client machine?

A: Remote named instance listening port discovery relies SQL Server Browser Service and protocol. As you cannot leverage this for your Linux docker image, I suggest you connect by explicitly specifying the port and omitting the instance name: "server=tcp:SQLSERVER1,1372;database=...;...":

The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name: server=tcp:servername, portnumber

BTW if you live the instance name it should make no difference whatsoever after you explicitly specify the port.
PS. After reading again the question, the issue is related but different cause. Normally the Linux container can discover the Windows SQL Server, as the Browser service is probably up and running (proof that 3 envs. it works). In the 4th environment it means something blocks the discovery. Either the Browser service is stopped, or the browser discovery protocol listening port is blocked in the FW (UDP 1433), or perhaps the UDP packet (or the response!) is lost somewhere between the container and the server. You can investigate and find the root cause, but, you can also just ignore the problem and work around the issue by... specifying the port explicitly, just as I showed.


text:
Q: How to use getInitialProps in React component this is my first time working with React and Next.js so I'm not very experienced, but I'm trying to help out with a project that uses both of these things. I need to get an array of artists from an endpoint and use it in ProjectForm. The getInitialProps function is used to do this elsewhere in the project, so I'm attempting to follow suit, but am not sure how to pass this data to ProjectForm. I've tried things like const ProjectForm = (props: ProjectFormProps, artists) and adding artists: artists to the ProjectFormProps, but no dice. How can I use the artists data I'm getting from the getInitialProps function within ProjectForm? Any help would be much appreciated!
import React, { useState, useEffect, useReducer } from 'react';
import axios from 'axios';

interface ProjectFormProps {
  entity: any;
  user: any;
  projectTypes?: any;
  handleButtonClick?: any;
  isNew?: boolean,
  onSubmitForm?: Function,
  onChange?: Function,
};

const ProjectForm = (props: ProjectFormProps) => {

  console.log(artists);

  return (

Artists

  );
}

ProjectForm.getInitialProps = async ({ req }) => {
  const baseUrl = req ? `${req.protocol}://${req.get('Host')}` : '';
  const artists = await axios.get(`${baseUrl}/api/artists`)
    .then(res => res.data)
    .catch(err => console.error(err, 'Unable to retrieve artists from API.'));
  return {
    artists
  };
};

export default ProjectForm;

A: Can you try this:
interface ProjectFormProps {
  entity: any;
  user: any;
  projectTypes?: any;
  handleButtonClick?: any;
  isNew?: boolean,
  onSubmitForm?: Function,
  onChange?: Function,
  artists?: any
};

const ProjectForm = (props: ProjectFormProps) => {
  console.log(props.artists);

  return (

Artists

  );
}


text:
Q: Adding another tsconfig.json file to project confuses tsc when finding definitions I have a file structure for an application using typescript that looks akin to this;
./
./tsconfig.json
      /typings   /* typescript d.ts from typings */
      /src
      /sites
            /wiki
                  /scripts
                        /typescript-file.ts
                        /typescript-file.ts

and that works fine. but I have a situation where I would like to add a new tsconfig.json to the /wiki/ directory, to change the way it behaves in just that part of the project.
At first glance this seems fine, but whenever I try to run tsc on that directory, I get a notification that it cannot find the typescript definitions in the /typings/ directory - which is a higher level.
is there anything I can do about this that doesn't require me to clone the typings directory into the lower-level folder?
root level tsconfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "experimentalDecorators": true,
    "stripInternal": true,
    "noImplicitAny": false,
    "removeComments": false,
    "sourceMap": false,
    "target": "es5",
    "module": "commonjs",
    "allowSyntheticDefaultImports": true,
    "noEmitOnError": false,
    "moduleResolution": "node",
    "pretty": true,
    "declaration": false
  },
  "exclude": [
    "node_modules",
    "bower_components",
  ]
}

higher level tsconfig.json
{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "amd",
  }
}

A: A couple thoughts.
One, would you object to introducing a files property? I've got a tsconfig that has a files property like this:
"files": [
    "typings/tsd.d.ts",
    "src/main.ts",
    ...
]

Everything that src/main.ts imports is still compiled. You only really have to specify the entry points of the import graph, and this is working out well enough for me.
Another slightly more controversial option may be to introduce the typings directory into your wiki directory via a symlink rather than manually copying it.


text:
Q: How to prevent IFRAME from redirecting top-level window Some websites have code to "break out" of IFRAME enclosures, meaning that if a page A is loaded as an IFRAME inside an parent page P some Javascript in A redirects the outer window to A.
Typically this Javascript looks something like this:

My question is: As the author of the parent page P and not being the author of the inner page A, how can I prevent A from doing this break-out?
P.S. It seems to me like it ought to be a cross-site security violation, but it isn't.

A: I use the sandbox attribute on the iframe element:

*

*allow-forms allow form submission

*allow-popups allows popups

*allow-pointer-lock allows pointer lock

*allow-same-origin allows the document to maintain its origin

*allow-scripts allows JavaScript execution, and also allows features to trigger automatically

*allow-top-navigation allows the document to break out of the frame by navigating the top-level window

Top navigation is what you want to prevent, so leave that out and it will not be allowed.  Anything left out will be blocked
ex.
<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" src="http://www.example.com"

A: Try using the onbeforeunload property, which will let the user choose whether he wants to navigate away from the page.
Example: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload
In HTML5 you can use sandbox property. Please see Pankrat's answer below.
http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

A: I know it has been a long time since question was done but here is my improved version it will wait 500ms for any subsequent call only when the iframe is loaded.

and onload="frameLoad()" and  onreadystatechange="frameLoad();" must be added to the frame or iframe.

A: Since the page you load inside the iframe can execute the "break out" code with a setInterval, onbeforeunload might not be that practical, since it could flud the user with 'Are you sure you want to leave?' dialogs.
There is also the iframe security attribute which only works on IE & Opera
:(

A: In my case I want the user to visit the inner page so that server will see their ip as a visitor. If I use the php proxy technique I think that the inner page will see my server ip as a visitor so it is not good. The only solution I got so far is wilth onbeforeunload.
Put this on your page:

This works both in firefox and ie, thats what I tested for.
you will find versions using something like evt.return(whatever) crap... that doesn't work in firefox.

A: With HTML5 the iframe sandbox attribute was added. At the time of writing this works on Chrome, Safari, Firefox and recent versions of IE and Opera but does pretty much what you want:

If you want to allow top-level redirects specify sandbox="allow-top-navigation".

A: After reading the w3.org spec. I found the sandbox property.
You can set sandbox="", which prevents the iframe from redirecting. That being said it won't redirect the iframe either. You will lose the click essentially.
Example here: http://jsfiddle.net/ppkzS/1/
Example without sandbox: http://jsfiddle.net/ppkzS/

A: try:

A: By doing so you'd be able to control any action of the framed page, which you cannot. Same-domain origin policy applies.


text:
Q: How to exclude node_modules from watchers files When I do ng serve the log shows errors like this:
Error from chokidar (/PATH_OF_MY_PROJECT/node_modules/ionicons/dist/ionicons/svg): Error: ENOSPC: System limit for number of file watchers reached, watch '/PATH_OF_MY_PROJECT/node_modules/ionicons/dist/ionicons/svg/ios-subway.svg'

I read that the solution is to change watchers file on Linux but that is a bad solution!
Why does Angular need to see changes to node_modules? It is a folder that doesn't change. If I need to install a new library I can restart the server.
Do not answer me if your solution is:
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf. I do not want to use this bad solution.

A: I had the same problem and every answer pointed the solution you said.

Doesnt answer me if your solution is: echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf

This didn't help me either.
I couldn't find a solution, but in webpack you can ignore/exclude the directories you don't want to check just doing the next thing inside your module.exports:
module.exports = {
      target: 'node',
      ...
      watchOptions: {
        ignored: [
          /node_modules/,
          ...
        ],
      },


text:
Q: Why in common brouhgt praxis of IT a Quantum Computer is too expensive and not yet usable for business-users? Why in common brouhgt praxis of IT a Quantum Computer is not yet existent?
Quantum Computing is a very much discussed term in Theoretical Physics, Information Science and Mathematics, it's a main topic in whole IT Society.
It's a summary for all actual activities with circuits using sub-atomic particles.
Till now - nearly 60 years after first classical computer - we have "Quantum Circuits" which need immense research power only and cost a lot of Money because of necessary error corrections and simulations.
A computer needs clear definable states - in Quantum Physics system knowledge based on probabilities is valid (see f.i. QM Standard Model). We have no usable element like a Relay or Transistor. If we don't have this we never can create any computer system (= set of such searched quantum elements).
So all Quantum Computing till now is science-journalistic writing only - not more. Since the 70th of last century topics arise about a "running Quantum Computer" but in reality all are finaly not usable elctronic cirtcuits of latest micro- and nanoelectronics.

A: Well, first of all, the ideas of quantum computing were started in the 1980s, not fifty years ago. Since then, several groups have constructed few-qubit systems and managed to perform multi-qubit operations in a variety of systems: NV centers, trapped ions, NMR, microwave/superconducting circuits...
We just aren't yet at the point where such systems are scalable to many qubits, enough to do something very practical. However, note that it doesn't take very many qubits before you can do something that classical computers simply can't simulate--dealing with 20 qubits starts to get very difficult classically. I know a professor who says he'll have 20 qubits up and running within the year, so we might start to see some really interesting quantum simulation soon.


text:
Q: JavaScript added rows not accessible in c# I am making a web page in asp.net. I have created an HTML table with runat="server". I added some rows to it using JavaScript by getting values from input boxes. I need these rows accessible in code behind c#. When I use this table in code behind, it gives me just one row, which I added as a table heading in the HTML section. It does not consider the rows added in JavaScript. Is there any way to access these rows?
My HTML Code:

        S. No.
        Staff Name
        Room
        Phone No.
        Remove

Javascript Code:
function addStaff()
{
    var tbl = document.getElementById('tblStaff');
    var lastRow = tbl.rows.length;
    // if there's no header row in the table, then iteration = lastRow + 1
    var iteration = lastRow;
    var row = tbl.insertRow(lastRow);

    var cell0 = row.insertCell(0);
    var textNode = document.createTextNode(iteration);
    cell0.appendChild(textNode);

    var cell1 = row.insertCell(1);
    var textNode = document.createTextNode(document.getElementById('txtStaffName').value);
    cell1.appendChild(textNode);

    var cell2 = row.insertCell(2);
    textNode = document.createTextNode(document.getElementById('txtRoomNo').value);
    cell2.appendChild(textNode);

    var cell3 = row.insertCell(3);
    textNode = document.createTextNode(document.getElementById('txtPhoneNo').value);
    cell3.appendChild(textNode);

    var lastCell = row.insertCell(4);
    var el = document.createElement('input');
    el.type = 'button';
    el.name = 'btnDelete' + iteration;
    el.id = 'btnDelete' + iteration;
    el.value = 'Remove';
    el.size = 40;
    el.setAttribute('onclick', 'deleteRow(' + iteration + ');');
    lastCell.appendChild(el);
}

A: It looks like your addStaff() function only adds to the table in the frontend. If I may point out, the C# is executed server side, and so, the rows added by your javascript do not exist at the time when your C# is looking for them.
Like Florian Gl suggested, you could include an ajax submit in your addStaff() function, that also sends whatever row the javascript displays in the table in the browser, to the C# in the backend. Once you have the data in your C#, you can proceed with sending the email or can even opt to save a database...

A: I'd recommend to let the user add some data via a form, then send it to the server and store it where you want. If this was successful, add the rerendered table to the response and render it on the client or add just the new row client side. On server side you cannot access the new rows, but you can access its data models, what should be sufficient.
If you want further advice you should elaborate on why you want to access those rows server side.
EDIT:
Have a look at this fiddle. There you see the structure your table has to be. Now if you want to add an user, just add a new row in this format with index of users in name incremented. Now if you hit submit, all users will be send as an array to the server where you can iterate through them and send an email.
You web api method could look like:
//route url/to/api
public void AddNewUser(User[] users)
{
   //iterate through users and send email
}

A: Try this
using System.Web.UI.HtmlControls;

 foreach (HtmlTableRow row in tblStaff.Rows)
          {
            string txtCell0 = row.Cells[0].InnerText;
            string txtCell1 = row.Cells[1].InnerText;
          }


text:
Q: C# saving object from NodeList xml I have such xml:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Pepole>
  <PersonList>
    <Person>
      <Name>aa</Name>
      <Surname>asdf</Surname>
      <City>asdf</City>
    </Person>
  </PersonList>
  <PersonList>
    <Person>
      <Name>aa</Name>
      <Surname>dafsd</Surname>
      <City>dafdsa</City>
    </Person>
  </PersonList>
  <PersonList>
    <Person>
      <Name>asdf</Name>
      <Surname>asdfasdf</Surname>
      <City>asdfadsf</City>
    </Person>
    <Person>
      <Name>asdfsadf</Name>
      <Surname>Dasfdasdf</Surname>
      <City>asdfdsaf</City>
    </Person>
    <Person>
      <Name>asdfdsaf</Name>
      <Surname>asdfdsaf</Surname>
      <City>asdfdsaf</City>
    </Person>
  </PersonList>
</Pepole>

Method:
public static void SendTheLoadedPerson(ObservableCollection<ObservableCollection<Person>> list)
{
    XmlDocument xmlDoc = new XmlDocument();
    XDocument doc = XDocument.Load(path);
    XmlElement root = xmlDoc.DocumentElement;
    XmlNodeList nodes = xmlDoc.DocumentElement.ChildNodes;
    XmlNodeList nodes2 = root.SelectNodes("//Pepole/PersonList/Person");

    foreach (XmlNode node in nodes)
    {
        var items = (from r in doc.Root.Elements("Person")

        select new Person()
        {
            Name = (string)r.Element("Name"),
            Surname = (string)r.Element("Surname"),
            City = (string)r.Element("City")
        }).ToList();

        list.Add(new ObservableCollection<Person>(items));
    }
}

And now I have a problem, because the XmlNode returns fine - 3 Personlist and inside the Person, but I would like to asigne count of nodes separately to the ObservableCollection> list.
I meant : When PersonList contains 2 person, I would like to send to the list 2 person, as one count, it's hard to explain to me so it's should looks like that:
template
I will be very grateful for any tips / help!

A: This is the fourth time you posted the same question.  The newest posting has slightly different xml.  Below is the solution provided in one of these postings using latest xml and adding a count.  Your solution is more complicated using Elements instead of Descendants.  :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("PersonList").Select(x => new {
                count = x.Elements("Person").Count(),
                people = x.Elements("Person").Select(y => new {
                    name = (string)y.Element("Name"),
                    surname = (string)y.Element("Surname"),
                    city = (string)y.Element("City")
                }).ToList()
            }).ToList();

        }
    }
}