text:
Q: CSS Media Query based on element width Having a modal DIV containing responsive tabs that change from horizontal to vertical on min-width (720px) for example.
This div is Resizable by the user!
So the problem is if the user resizes the div to 600px no responsive change occurs, that's because the screen width didn't change.
My question is: is there any hack or way to make a USER RESIZABLE DIV respond to its width change instead of the screen width?
I tried to figure out how to do it with calc, but I think it would be something like :
calc(100% - div-width)= ... etc.

but I don't think it's supported this way by CSS.
Thanks a lot.

A: In order to achieve the result you're looking for as you said in the comments above, i think one great way is to use css grid or flex. You can make your div responsive with one of them without the need of a media query.
Example: display: flex; flex-wrap: wrap;.

A: You can use display:flex; and flex-wrap:wrap as xhoni says. Also i offer you to use font-size with media-queries because if the screen width decrease but your font is not. It may occured some display or design problem.


text:
Q: Avoiding apache to run as root I am working on Apache server on localhost in Linux mint and need to create new file and folder using php script. But it is returning permission denied on 'mkdir' function.
I googled and found that Apache needs to run as root for such permissions. It is running as 'www-data' in my machine. But I also found that running Apache as root will open many vulnerabilities and there is no situation where Apache is needed to run as root.
How to overcome permission restrictions in apache?

A: NEVER EVER let apache run as root - in case of any flaws in your PHP, consequences would be TERRIFYING
Also adding www-data to sudoers is like one of the worst ideas I've seen so far
You need root priviliges to MANAGE apache (start/stop etc)
Make sure that the folder in which you have the PHP script belongs to www-data user & group, and it has sufficient permissions. Also, I don't know how your PHP is configured, but if you are using PHP as CGI, make sure that PHP is also running as www-data
system('whoami');
will help you to determine the user :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use network policy to allow access to pods only from a specific namespace to another in kubernetes? How can I achieve that when obviously you can not use spec.namespaceSelector in the netpol?
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-from-ns-netpol
  namespace: special-ns
spec:
  namespaceSelector:
    matchLabels:
      kubernetes.io/metadata.name: app
  ingress:
    - from:
      - namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: cka-exam

So, this doesn't work.

A: The API resource definition you've provided does not appear to be schema compliant. The NetworkPolicySpec in Kubernetes v1.26 shows that the following fields are allowed: [policyTypes, podSelector, egress, ingress].
I recommend taking a look at the Network Policy documentation.
When you define a Network Policy, you assign it to a Namespace. You can then narrow that Network Policy to only apply to select Pods (in that Namespace) using the .spec.podSelector property. As the documentation states, "An empty podSelector selects all pods in the namespace."
This means if you want block all ingress traffic to the Pods in Namespace special-ns, you would assign the Network Policy to the special-ns Namespace and leave the .spec.podSelector property empty so it selects all of the Pods in special-ns. Without any ingress rules defined, the resource would be the Default deny all ingress traffic definition.
You then use the ingress property to define the restrictions, or rules, on where that incoming traffic can come from. It looks like your existing definition is correct, so ingress traffic will only be allowed from Pods that exist in the Namespace cka-exam.
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-from-ns-netpol
  namespace: special-ns
spec:
  ingress:
    - from:
      - namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: cka-exam


text:
Q: How to read all splitcontainers and i Hi
I have 50 splitcontainers.. i want to read all the splitcontainers & its panels programmatically...Is it possible...?
Because the below code only reads Splitcontainer4 & Panel1, But Iam looking to read all the splitcontainers and its panels programmatically...

foreach (Control Ctrl in this.splitContainer4.Panel1.Controls)
            {
                if (Ctrl is RichTextBox)
                {
                    ((RichTextBox)(Ctrl)).KeyPress += new KeyPressEventHandler(this.Common_KeyPress);
                }
            }
Thanks for ideas...
Regards
PARAMU

A: Find all the splitcontainers see SO question here and check both panels for the desired controls.


text:
Q: Cardinality of a Banach space Let $X$ be a separable infinite-dimensional Banach space.
Assume that every element of $B_{X^{**}}$ is the weak-star limit of a sequence in $B_{X}$.
Clearly, by the canonical embedding, we can see that $\text{card} (X) \leq \text{card}(X^{**})$.
If we choose a norm-dense sequence $\{x_n\}_{n=1}^{\infty}$ in $B_{X}$, then from our assumption, I could check that each element of $B_{X^{**}}$ is the weak-star limit of a subsequence of $\{x_n\}_{n=1}^{\infty}$.
Here is my question: How can I conclude that $\text{card} (X) = \text{card}(X^{**})$ from the above observation?
Any help will be appreciated.


text:
Q: Zoom softly into the center of a D3 map I have a create an interactive map. This map can be zoomed via buttons. These buttons already work but I don't like the current style. It does not feel UX-friendly when by clicking the button the map is shaking a bit. I would like to zoom into the center of the map softly instead.

Here zoom-in code on the button:
d3.select('#zoomplusbutton').on('click', function () {
    ardamap.zoomByFactor(1.3);
});

And here the function code with the strange zooming:
zoomByFactor: function (factor) {
                d3.event.preventDefault();
                var scale = zoom.scale();
                var extent = zoom.scaleExtent();
                var newScale = scale * factor;
                if (extent[0] <= newScale && newScale <= extent[1]) {
                    var t = zoom.translate();
                    var c = [width / 2, height / 2];
                    zoom
                        .scale(newScale)
                        .translate([c[0] + (t[0] - c[0]) / scale * newScale, c[1] + (t[1] - c[1]) / scale * newScale])
                        .event(g.transition());
                }
            }

I really don't know anymore where I got this zooming code from.
So how can I really zoom to the center of the map softly? Feel free to change the JS-code on the website.

A: After several hours now figured out a 'OK' solution. It's not perfectly the center but at the end without shaking and any other bad behaviour:
zoomButton: function (zoom_in) {
            var scale = zoom.scale(),
                extent = zoom.scaleExtent(),
                translate = zoom.translate(),
                x = translate[0], y = translate[1],
                factor = zoom_in ? 1.3 : 1/1.3,
                target_scale = scale * factor;
            if (target_scale === extent[0] || target_scale === extent[1] || target_scale > extent[1] || target_scale < extent[0]) { return false; }
            var clamped_target_scale = Math.max(extent[0], Math.min(extent[1], target_scale));
            if (clamped_target_scale != target_scale){
                target_scale = clamped_target_scale;
                factor = target_scale / scale;
            }
            x = (x - center[0]) * factor + center[0];
            y = (y - center[1]) * factor + center[1];
            if (zoom_in){
                x = x - 500;
            }else{
                x = x + 500;
            }
            d3.transition().duration(450).tween("zoom", function () {
                var interpolate_scale = d3.interpolate(scale, target_scale),
                    interpolate_trans = d3.interpolate(translate, [x,y]);
                return function (t) {
                    zoom.scale(interpolate_scale(t))
                        .translate(interpolate_trans(t));
                    ardamap.zoomedButton();
                };
            });
        }

These calculations work pretty well. And here the two button raising events:
d3.select('#zoomplusbutton').on('click', function(){
    ardamap.zoomButton(true);
});
d3.select('#zoomminusbutton').on('click', function () {
    ardamap.zoomButton(false);
});

You can find the code update on arda-maps.org as well. If you have I fix for really going to the center of the current map, feel free to edit my answer. I'm still interested in improving this!


text:
Q: Is there a Dynamic Programming way to compute the k minimum spanning trees? My teacher asked us to implement a Dynamic Programming solution to that problem, but I'm thinking one doesn't exist since I couldn't find it using Google.
Anyway, given a graph and a k, say 3, you have to find the 3 best MSTs from it. If the graph is such that it doesn't have k subtrees, you can return either the same tree multiple times or suboptimal trees.
I can't really think of a solution to it.

A: You had me confused for a while there and I thought you might have misunderstood the problem. The "k-MST" problem consists of finding k edges that form a subtree such that the sum of its edges is less than or equal to all other sums you can get from subtrees of k edges. But then I saw the plural s.
So ok, for your problem, I personally would try to find a DP-algorithm for finding the MST that combines with a way of generating a "next" MSTs. Since this is dynamic programming I'd look into repeatedly optimizing something (in this case de-optimizing for each step) or at various ways of partitioning edges into subsets that make sense in an MST setting. There might be several ways.
However, searching for partitions and minimum spanning trees I found this, which might be more of help if you just want the answer: http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0101-74382005000200004


text:
Q: Xcode Keeps Crashing. What should I do? Reinstalling, uninstalling, reinstalling 4.0.2 doesn't work
Process:         Xcode [649]
Path:            /Developer/Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:      com.apple.dt.Xcode
Version:         4.0.2 (99)
Build Info:      IDEApplication-990000~53
Code Type:       X86-64 (Native)
Parent Process:  launchd [91]

Date/Time:       2011-05-15 22:13:29.007 +0700
OS Version:      Mac OS X 10.6.7 (10J869)
Report Version:  6

Interval Since Last Report:          128065 sec
Crashes Since Last Report:           7
Per-App Interval Since Last Report:  118616 sec
Per-App Crashes Since Last Report:   7
Anonymous UUID:                      B0FCFF42-38B8-4466-8161-8D3F5CEBC494

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Crashed Thread:  0  Dispatch queue: com.apple.main-thread

Application Specific Information:
ProductBuildVersion: 4A2002a
Encountered multiple assertions. First assertion was: UNCAUGHT EXCEPTION (NSRangeException): *** -[NSCFString _getBlockStart:end:contentsEnd:forRange:stopAtLineSeparators:]: Range or index out of bounds
UserInfo: (null)
Hints: None
Backtrace:
  0  0x00007fff80b40796 __exceptionPreprocess (in CoreFoundation)
  1  0x00007fff821e50f3 objc_exception_throw (in libobjc.A.dylib)
  2  0x00007fff80b405d7 +[NSException raise:format:arguments:] (in CoreFoundation)
  3  0x00007fff80b40564 +[NSException raise:format:] (in CoreFoundation)
  4  0x00007fff80cb64aa -[NSString _getBlockStart:end:contentsEnd:forRange:stopAtLineSeparators:] (in Foundation)
  5  0x00007fff823f202d _NSFastFillAllLayoutHolesForGlyphRange (in AppKit)
  6  0x00007fff82948cbb -[NSTextView(NSPrivate) _ensureLayoutCompleteForVisibleRectWithExtensionFactor:minimumExtensionDistance:repetitions:] (in AppKit)
  7  0x000000010020d1a3 -[DVTSourceTextView(FoldingSupport) _ensureLayoutCompleteForVisibleRectWithExtension:] (in DVTKit)
  8  0x00007fff823ef694 -[NSTextView setNeedsDisplayInRect:avoidAdditionalLayout:] (in AppKit)
  9  0x0000000100204b15 -[DVTSourceTextView setNeedsDisplayInRect:avoidAdditionalLayout:] (in DVTKit)
 10  0x00007fff823acc3b -[NSView setNeedsDisplay:] (in AppKit)
 11  0x0000000100075614 -[NSObject(DVTPropertyLinking) dvt_addObserverWithName:toKeyPath:ofObject:block:] (in DVTFoundation)
 12  0x0000000118f0b833 -[IDESourceCodeEditor contentViewDidCompleteLayout] (in IDESourceEditor)
 13  0x0000000118f0b115 -[IDESourceCodeEditorContainerView didCompleteLayout] (in IDESourceEditor)
 14  0x00000001001d8fc0 +[DVTAutoLayoutView _recursivelyLayoutSubviewsOfView:populatingSetWithLaidOutViews:] (in DVTKit)
 15  0x000000010088c2c9 __66-[IDEEditorContext _openNavigableItem:documentExtension:document:]_block_invoke_0 (in IDEKit)
 16  0x000000010088be38 -[IDEEditorContext _performBlockInsideReentrantGuard:] (in IDEKit)
 17  0x000000010088bd08 -[IDEEditorContext _openNavigableItem:documentExtension:document:] (in IDEKit)
 18  0x00000001008bfd31 -[IDEEditorContext _openNavigableItem:documentExtension:] (in IDEKit)
 19  0x000000010088b50f -[IDEEditorContext _openNavigableItem:] (in IDEKit)
 20  0x00000001008bf033 -[IDEEditorContext _notifyDelegateAndOpenNavigableItem:documentExtensionIdentifier:locationToSelect:annotationRepresentedObject:stateDictionary:annotationWantsIndicatorAnimation:exploreAnnotationRepresentedObject:] (in IDEKit)
 21  0x00000001008bb678 -[IDEEditorContext _notifyDelegateAndOpenEditorOpenSpecifier:updateHistory:] (in IDEKit)
 22  0x00000001008bb453 -[IDEEditorContext _openEditorOpenSpecifier:updateHistory:] (in IDEKit)
 23  0x00000001008bb15e -[IDEEditorContext openEditorOpenSpecifier:] (in IDEKit)
 24  0x00000001008bb13b -[IDEEditorModeViewController openEditorOpenSpecifier:editorContext:] (in IDEKit)
 25  0x00000001008bb0f9 -[IDEEditorArea _openEditorOpenSpecifier:editorContext:takeFocus:] (in IDEKit)
 26  0x0000000100941bcb __108+[IDEEditorCoordinator _doOpenEditorOpenSpecifier:forWorkspaceTabController:editorContext:target:takeFocus:]_block_invoke_0 (in IDEKit)
 27  0x00000001008bae5d +[IDEEditorCoordinator _doOpenWithWorkspaceTabController:editorContext:target:allowFallback:documentURL:usingBlock:] (in IDEKit)
 28  0x0000000100941ae8 +[IDEEditorCoordinator _doOpenEditorOpenSpecifier:forWorkspaceTabController:editorContext:target:takeFocus:] (in IDEKit)
 29  0x00000001008ba899 -[_IDEOpenRequest _runIfNecessary] (in IDEKit)
 30  0x00000001008ba2a1 -[_IDEOpenRequest _enqueueForEventBehavior:] (in IDEKit)
 31  0x00000001008b9dab +[IDEEditorCoordinator _openRequestForEditorOpenSpecifier:workspaceTabController:editorContext:eventBehavior:takeFocus:] (in IDEKit)
 32  0x00000001008b9d00 __99+[IDEEditorCoordinator _openEditorOpenSpecifier:forWorkspaceTabController:eventBehavior:takeFocus:]_block_invoke_0 (in IDEKit)
 33  0x00000001008b9c90 _performBlockInsideReentrantGuard (in IDEKit)
 34  0x00000001008b9bff +[IDEEditorCoordinator _openEditorOpenSpecifier:forWorkspaceTabController:eventBehavior:takeFocus:] (in IDEKit)
 35  0x00000001008b98e9 +[IDEEditorCoordinator openEditorOpenSpecifier:forWorkspaceTabController:eventType:] (in IDEKit)
 36  0x000000011d964ed0 -[IDEStructureNavigator addTemplatesFromCompletedContext:] (in IDEStructureNavigator)
 37  0x00007fff80ca0562 -[NSBlockOperation main] (in Foundation)
 38  0x00007fff80c90cc4 -[__NSOperationInternal start] (in Foundation)
 39  0x00007fff80d6fae7 __doStart2 (in Foundation)
 40  0x00007fff80d6fcdf ____NSOQSchedule_block_invoke_1 (in Foundation)
 41  0x00007fff865f2284 _dispatch_call_block_and_release (in libSystem.B.dylib)
 42  0x00007fff865d0df2 _dispatch_queue_drain (in libSystem.B.dylib)
 43  0x00007fff865d169f _dispatch_queue_serial_drain_till_empty (in libSystem.B.dylib)
 44  0x00007fff8660443c _dispatch_main_queue_callback_4CF (in libSystem.B.dylib)
 45  0x00007fff80adc0c8 __CFRunLoopRun (in CoreFoundation)
 46  0x00007fff80adadbf CFRunLoopRunSpecific (in CoreFoundation)
 47  0x00007fff833ae7ee RunCurrentEventLoopInMode (in HIToolbox)
 48  0x00007fff833ae551 ReceiveNextEventCommon (in HIToolbox)
 49  0x00007fff833ae4ac BlockUntilNextEventMatchingListInMode (in HIToolbox)
 50  0x00007fff823d2e64 _DPSNextEvent (in AppKit)
 51  0x00007fff823d27a9 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] (in AppKit)
 52  0x00007fff8239848b -[NSApplication run] (in AppKit)
 53  0x00007fff823911a8 NSApplicationMain (in AppKit)
 54  0x0000000100000eec

A: after uninstalling xcode, use your Snow Leopard disk to reinstall the system then run all updates from scratch before installing it again. This type of reinstall shouldn't affect your data or setup.


text:
Q: Enable zooming in WKWebView in Swift 4, Xcode 10, for iOS 12 I am trying to enable zooming/magnification (by pinching) in a very simple WebView in a simple app. (I am pretty new to this).
The Swift code that loads the web page is this and it works fine, I got from here, I think.
import UIKit
import WebKit

class SecondViewController: UIViewController {

@IBOutlet weak var WebViewSchedule: WKWebView!
override func viewDidLoad() {
    super.viewDidLoad()
 // load the page
    let url = URL(string: "https://mywebsite.com")
    let request = URLRequest(url: url!)
    WebViewSchedule.load(request)
//how do i make it zoomable ????
 }
}

I've looked at a number of answers about this, and they all refer to a property "allowsMagnification".  I have tried various ways of using this and got nowhere.
So could some  kind person give me a beginners' guide to how to make my iOS Web page zoomable?


text:
Q: How to Clear Dynamically Generated Page Cached on the Server I'm generating a html page that is basically a list of photos saved in a single folder.  I trigger the generation of the pictures.html template each time a new photo is added to the folder.
My problem is the old template page seems to be used from the cached even when I open a new browser on a different device which is what makes me think its a server and not a client cache.
I'm an old coder but new to dynamic web pages.
I'm using Apache2 web server on a raspberry pi Buster (Debian) as my web server.
I'm using Python3 to create the web pages.
I found a way to edit the Apache config file and add a cache exclusion with an example like this one that excludes images.
<FilesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
  Header set Cache-Control "max-age=63072000, public"
</FilesMatch>

The problem is that the "file" I want to exclude never seems to be an actual file.  It's built from a template named pictures.html and some standard  info etc is added.
If I understand correctly the code below creates and loads the page  from my main file named app.py.
@app.route('/pictures/')
def pictures():
    return render_template('pictures.html')

I even checked the following day and the old page is still cached somewhere and loaded into the client browser.
Any ideas how I can force this page to be dropped from the server cache every time it is updated.  Obviously the problem goes away if I restart the Apache service but that's not an option in production.
Even clearing the entire cache would do but that will probably kill a lot of performance gains for all the static files.  My application regularly adds new photos to the folder.
Thanks for any ideas
David
Update
Further research found this page
I added the CacheDisable Directive to my apache2.conf file but the apache service now fails to start.
<Location "/pictures">
    CacheDisable on
</Location>

Here is the error message
Jun 01 18:25:52 ROVER1 apachectl[10723]: AH00526: Syntax error on line 214 of /etc/apache2/apache2.conf:
Jun 01 18:25:52 ROVER1 apachectl[10723]: Invalid command 'CacheDisable', perhaps misspelled or defined by a module not includ
Jun 01 18:25:52 ROVER1 apachectl[10723]: Action 'start' failed.
Jun 01 18:25:52 ROVER1 apachectl[10723]: The Apache error log may have more information.
Jun 01 18:25:52 ROVER1 systemd[1]: apache2.service: Control process exited, code=exited, status=1/FAILURE

A: Turned out I was barking up the wrong tree :)
I changed my approach and removed all the changeable file information from the pictures.html template.
I then added code to app.py that reads the file information and saves it to a list.  I then pass the list to the pictures.html template and in the html, iterated through the list loading the details into a table using jinja text.
It means the list will be generated every time the page is loaded even when nothing has changed since last time but it seems more sensible that dynamically modifying a template and trying to avoid the cache.
I Hope I have all the terminology correct and that this result helps someone else.
David


text:
Q: c# readprocessmemory with Cheat Engine I'm trying to get string value from address which i found using cheat engine. I found for example 0x01742A38 and this is main part of my program (regular windows form application):
            Process[] processes = Process.GetProcessesByName("Tibia");

            foreach (Process p in processes)
            {
                IntPtr windowHandle = p.MainWindowHandle;
                byte[] bufor = new byte[50];
                uint baseAddress = (uint)p.MainModule.BaseAddress.ToInt32();
                IntPtr addr = ((IntPtr)(baseAddress + 0x01742A38));
                uint o = 0;
                UInt32 k = 30;
                if (ReadProcessMemory(windowHandle, addr, bufor, k, ref o))
                {
                    label3.Text = "Success!";
                }
                else
                {
                    label3.Text = "Fail : (";
                }
            }

A: Assuming your static address is correct, you have to open the target process using the OpenProcess function with at least the right PROCESS_VM_READ (0x0010).
I also suggest you to use a more suitable pinvoke signature for the function ReadProcessMemory:
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out IntPtr lpNumberOfBytesRead);


text:
Q: Google chrome wants to use the keychain password frequently Google chrome wants to use the keychain password frequently in my mac system(OSX version 10.9.2).
Before updating the OS to new version, the applications like Textedit, Preview are used to ask the password while accessing them. If I click the cancel button twice, the popup will be disappeared. But, after updating to new OS version, a popup saying Google chrome wants to use the keychain password without any reason.

I need to click the cancel button for eight to twenty times to disappear the popup. While writing this question that dialog box appears three times. Sometimes, I keep that alert box to the bottom like below.

I tried deleting the password for Chrome in keychain, as suggested in this link. But, no use.


text:
Q: Selenium IDE gives different result when running the same code I am new to Selenium and was just playing with the IDE. I have a website that runs locally on my machine which has a IFrame and some popups. The following code runs very well when in medium speed mode or slow mode but fails when run in fast mode it gives an error (see line 15 below). Even though I tried to keep wait statements for things to sync.
Also notice that the same code is executed just fine in line 9 whether running slow or fast.
01    open          /default.aspx
02    type          id=loginContent_txtPassword xxxx
03    clickAndWait      id=loginContent_btnSet
04    windowFocus
05    click         //div[@id='lBar_leftItem_4']/a
06    waitForFrameToLoad            aframe 30000
07    selectFrame               aframe
08    click         css=img[title="Properties"]
09    waitForPopUp      doc              30000
10    selectWindow      name=doc
11    close
12    selectWindow      null
13    selectFrame               aframe
14    click         css=img[title="Properties"]
15    waitForPopUp      doc                        30000   ***[error] can't access dead object**
16    selectWindow      name=doc
17    verifyText        id=popupContent_lblOwner           XYZ*
18    close

A: Tried many things... but finally putting a short pause (for a few seconds) before the statements that causes the issue solved the problem. Maybe the selenium requests are not synced and it sends some requests to the browser before it can handle it (just my guess!)


text:
Q: How to create an array from content parts I want to read a file into an array and use some of the content from the file as array keys.
Example
myfile.txt
 [SPLIT]
 #START:KEY1
 this is the content
 #END:KEY1
 [SPLIT]
 #START:KEY2
 this is the next content
 #END:KEY2
 ...

I load the content from the file
$File = file_get_contents(myfile.txt);

I split the content at the maker [SPLIT] and create a array
    $file_array = explode('[SPLIT]',$File);

    foreach($file_array as $element)
    {
      //search for '#START:' get the part after that till lineend, use this as ($key) a key for a new array
....
      $new[$key]=$element;
    }

So, my question is, is there a easier or faster way, to create a array from the filecontent which looks like?
$myarray[KEY1]=this is the content
$myarray[KEY2]=this is the next content

A: Did you tried to use regular expresions?
$content = file_get_contents('file_name.txt');
preg_match_all('/\[SPLIT\]\n#START:(.*?)\n(.*?)#END/s', $content, $rows);

$data = [];
foreach ($rows[1] as $i => $key) {
    $data[$key] = trim($rows[2][$i]);
}

A: This will split based on new line :
$File = file('tmp/myfile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);


text:
Q: Definition of the stress-energy tensor Why don't we denote presence of matter and energy in space-time (as we do for presence of electric charge) by a 4-vector field?
Is there any information in the stress-energy tensor that is not in 4-vector field of current of energy and matter? As I think there is a current of energy and matter about us very similar to current of charges, and we denote this by 4-vector field $J$.
I hope there is explanation as this example: if someone ask me why we don't denote the presence of charge about us just by scalar field of charge density, then I say charge density of course denote the presence of charge but it neglects current of charges and there are physical phenomenons that arise not from only charges but also from their motion.

A:
Why don't we denote presence of matter and energy in space-time (as we do for presence of electric charge) by a 4-vector field?

Because energy is not Lorentz-invariant, whereas electric charge is. Therefore, when we compute how charge density and its flux transform to assert that charge density together with its flux is a four vector, we only need to account for the fact that different observers see the partitions of spacetime used to calculate the density and its flux differently, they do not see the charges themselves differently. The Lorentz covariance of the 4-current is equivalent to an assertion that electric charge is a Lorentz-invariant scalar.
In contrast, energy is not a Lorentz covariant scalar. It is united with momentum in the 4-momentum. So when we calculate the density of this entity, we need to account for the fact that both the underlying entity and the spacetime partitioning used to calculate a density change for different observers. We are computing the density and flux of a rank-1 tensor, not of a scalar.
This is one reason why Gravitoelectromagnetism doesn't work, although it gives pretty accurate calculations in many relativistic cases. It assumes, like Maxwell's equations, that the gravity field source is a rank 1 tensor - the mass/energy density and its flux - but this is flawed because mass / energy is not Lorentz invariant. Gravitoelectromagnetism gives the wrong values of gravitational radiation - the Larmor formula and its relativistic equivalent foretell radiation quantities that are far too big (falsified by observations of the Hulse-Taylor binary star, for example).

Is there any information in the stress-energy tensor that is not in 4-vector field of current of energy and matter? As I think there is a current of energy and matter about us very similar to current of charges, and we denote this by 4-vector field J
  J.

I think I've answered this one. Essentially the rank 2 stress energy tensor accounts for the Lorentz transformation of both the underlying quantities whose density is being calculated as well as the Lorentz transformation of the spacetime partitions used to calculate the density: a rank 1 four vector can only encode the Lorentz transformation of the latter.

A: "Canonical" reasoning:
In a field theory, associated to every one-parameter family of symmetries is a current 4-vector, which is conserved in terms of being divergenceless.
Now, since Minkowski spacetime is 4 dimensional, there are 4 linearly independent translations: 3 spatial and one temporal.
From nonrelativistic mechanics, we know that momentum is the Noether-charge associated to spatial translations. Since there are 3 spatial translations, momentum has three components. But these are Noether charges, not currents. This means there are three Noether currents associated with spatial translations, $\mathcal{J}_1^\mu,\mathcal{J}_2^\mu,\mathcal{J}_3^\mu$, where $\mathcal{J}^0_i$ denotes the momentum density in the ith direction, and $\mathcal{J}^j_i$ denotes the $j$th component of the momentum flux in the ith direction. The $\sigma_{ij}=\mathcal{J}^j_i$ components form a 3-tensor that is the ordinary stress tensor (or at least related to it by a constant).
If we also consider temporal translations, we also get $\mathcal{J}^\mu_0$, which is the Noether current of time translations. The $\mathcal{J}^0_0$ component is the energy density, and the $\mathcal{J}^i_0$ component is the ith component of the energy flux. The components $\mathcal{J}^\mu_\nu$ together form the $\Theta^\mu_{\ \nu}$ canonical stress-energy tensor. This makes sense only in flat Minkowski spacetime, and these components do transform tensorially.
This tensor can be symmetrized (the Belinfante-Rosenfeld tensor is one such symmetrization), and it can be proven (look around the site for related questions and answers/links therein) that the Belinfante tensor (which is equivalent modulo gauge transformations to the canonical tensor, in particular the conserved charges agree) is equivalent to the general-relativistic Hilbert stress-energy tensor in the flat spacetime limit.
So 1 symmetry $\Longrightarrow$ 4 current components, 4 symmetries $\Longrightarrow$ $4\times 4=16$ current components, hence it is why a second order tensor.
General relativistic reasoning:
The metric tensor naturally couples to basically any sort of matter fields, because the invariance of the action necessitates contractions between derivatives of fields ($\partial_\mu\phi\partial^\mu\phi$ type of stuff), plus the volume element $\sqrt{-g}$ depends on the metric too. The exceptions are topological fields, which have no local degrees of freedom.
Which means that if one forms the total action for a gravitational system, $$ S_t=S_{EH}+S_m,$$ where $S_{EH}=\int R\sqrt{-g}d^4x$ and $S_m$ is the action for matter fields, $S_m$ will be a functional of the metric too, not just the matter fields. To get the (gravitational) field equations, we need to functionally differentiate with respect to $g^{\mu\nu}$, which gives $$ \frac{\delta S_{EH}}{\delta g^{\mu\nu}}=-\frac{\delta S_{m}}{\delta g^{\mu\nu}}. $$ Because $g$ is symmetric, the RHS must be a symmetric second order tensor, which we identify as $\frac{1}{2}T_{\mu\nu}$, so the stress-energy tensor is a second-order tensor because the field variable (the metric) is also second order. Second order configuration variable $\Longrightarrow$ second order source current.

Edit: To elaborate the "canonical reasoning":
You used an example of charges: To charge $Q$, we associate a charge density function $\rho$, and a charge current $\mathbf{j}$. The continuity equation is $$\frac{\partial\rho}{\partial t}+\nabla\cdot\mathbf{j}=0.$$
Relativistically, the charge density and the current form a 4-vector $j^\mu=(\rho,j_x,j_y,j_z)$ (I set natural units). The continuity equation is $\partial_\mu j^\mu=0$.
What about energy and momentum? To energy $E$ we associate a density $u$ and a current vector field $\mathbf{S}$. The continuity equation is $$ \frac{\partial u}{\partial t}+\nabla\cdot\mathbf{S}=0.$$
But momentum is itself a 3-vector, but this 3-vector plays the role of a charge, not a current. Consider component-wise, the $x$-component of momentum is $p_x$. We associate to it a momentum density $\Pi_x$, and a momentum current $\vec{\sigma_x}$. The continuity equation is $$ \frac{\partial\Pi_x}{\partial t}+\nabla\cdot\vec{\sigma_x}=0. $$
If we consider all 3 momentum components we get a "higher order" continuity equation $$ \frac{\partial\vec{\Pi}}{\partial t}+\nabla\cdot\sigma=0, $$ where $\sigma$ is now a second order tensor.
But we know from relativity, that energy and momentum (the charges!) together form a 4-vector $p^\mu=(E,p_x,p_y,p_z)$, which implies that the current is a $4\times 4$ component object $$ \Theta^\mu_{\ \nu}=\left(\begin{matrix} u & S_x & S_y & S_z \\ \Pi_x & \sigma_{xx} & \sigma_{xy} & \sigma_{xz} \\ \Pi_y & \sigma_{yx} & \sigma_{yy} & \sigma_{yz} \\ \Pi_z & \sigma_{zx} & \sigma_{zy} & \sigma_{zz}  \end{matrix}\right). $$

A: There is an explanation, and it's relatively simple. But it does have deep consequences.
We can in fact, and do define the stress energy tensor in general relativity (GR) by $T^{\mu\nu}$, and it represents all contributions to the sources of gravity except for the energy-momentum (and stress) of the gravitation itself. The tensor is a covariant entity, and it includes terms for the energy, momentum, and stress of mass-energy. But it does not include the contribution from the gravitational effect. This has significant consequences - for one, that energy-momentum is NOT generally conserved in GR.
In the Einstein GR equations
$G^{\mu\nu} = kT^{\mu\nu}$,
the G tensor is the gravitation, actually also some terms having to do with the curvature of spacetime, and the equation says that matter-energy (on the right) causes curvature of spacetime. But the G tensor it turns out is not a linear function of the metric, and the contribution of nonlinear (and non trivially characterized) components of G can carry energy and momentum.
And in general then, the energy-momentum from the T tensor is not conserved. The ordinary divergence of the T tensor is not zero, so there is no conserved current. That is
Ordinary Div (T) = $\partial_{\nu}T^{\mu\nu}$ is not equal to zero
What turns out to be true is that the covariant divergence is indeed zero,
Covariant Div (T) = 0
The covariant divergence, formed from the covariant derivative, is zero. But you can't turn it into a partial derivative or ordinary divergence so you can't integrate on the boundary to get zero using Gauss's law. Covariant derivatives include terms formed from derivatives of the metric, that is the connection or Christoffel symbols. That includes the nonlinear effect of gravity in GR.
And energy and momentum is not generally conserved in GR. It is in some special spacetimes, such as where there is a global time symmetry, and where the spacetime is asymptotically flat (and then only total energy, not localized energy).
See for instance the energy stress tensor in GR at https://en.m.wikipedia.org/wiki/Stress–energy_tensor
It does run out that one can manipulate the covariant divergence equation and define another entity, a pseudotensor $\tau$, such that the
Ordinary Div ($T + \tau$) = 0
The pseudotensor represents the stress energy of gravitation, i.e. of spacetime. One could then try to say that the energy momentum vector defined from this is conserved. But It is unfortunately not a covariant entity, it is different in different coordinate systems, and there is no unique definition possible of it. But it can be used in some cases. See towards the end about mass is GR.
See the gravitational stress energy pseudotensor at https://en.m.wikipedia.org/wiki/Stress–energy–momentum_pseudotensor. As you can see form there, there is no unique expression for it, there are various that have been used, and they are not covariant Tensors. Each gives different results in different coordinate systems. Only when you have special spacetimes as indicated above does energy momentum conservation holds or makes sense. In cosmological spacetimes it does not.
So, the bottom line is that in GR there is a stress energy tensor that represents the energy momentum (and stress) of matter energy, except for gravitational mass-energy. And it is of course not conserved. And the gravitational mass energy is not a covariant entity, nor really unique.
The same is true of mass in GR. It is the energy, and it is not unique in GR. You can see various useful definitions of mass for special spacetimes at https://en.m.wikipedia.org/wiki/Mass_in_general_relativity
That is the impact of gravitation being spacetime curvature.


text:
Q: Appending value-pair to a dictionary-key I am reading a textfile with many sections. I would have a dictionary like:
stringArrayCompleteData['Objekt']['Mobile']
stringArrayCompleteData['Objekt']['address']
stringArrayCompleteData['Header']['devicenumber']
stringArrayCompleteData['Header']['departmentemailaddresse']
and much more

But in my loob, always the new value would not be appended, the values would be overwritten. And then i have only the last value.
var stringArray = fullImportContent!.componentsSeparatedByString("\n")
var stringArrayCompleteData = Dictionary<String, Dictionary<String, Any>>()
var arrIndexSection : String = "NoHeader"

        for singleRow in stringArray
        {
            if(singleRow != "")
            {
                switch singleRow {
                    case "#Header":
                        arrIndexSection = singleRow.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    case "#Objekt":
                        arrIndexSection = singleRow.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    case "#Baustelle":
                        arrIndexSection = singleRow.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    case "#Auftraggeber":
                        arrIndexSection = singleRow.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    case "#Architekt":
                        arrIndexSection = singleRow.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    case "#Vermittler":
                        arrIndexSection = singleRow.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    case "#Regulierer":
                        arrIndexSection = singleRow.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    case "#Versicherung":
                        arrIndexSection = singleRow.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    case "#Kontaktstellen":
                        arrIndexSection = singleRow.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    case "#Dateien":
                        arrIndexSection = singleRow.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    default:
                        //Here the multiple array would be filled
                        var arrSingleRow = singleRow.componentsSeparatedByString(";")

                        if( arrSingleRow.count > 0  )
                        {
                            if( arrIndexSection == "Kontaktstellen" )
                            {
                                //TODO: Kontaktstellen einlesen

                                //#Kontaktstellen
                                //Baustelle;0;348873;;;;0
                                //Baustelle;0;381263;;Albrecht;0815;0
                                //Regulierer/SV;0;171979;Josef;Eder;08546/911055;0
                                println( "Kontaktstellendaten" )
                                println( singleRow )
                            }
                            else if( arrIndexSection == "Dateien" )
                            {
                                //TODO: Dateien einlesen

                                //#Dateien
                                //11022015090007_BEmail_INNNUE_21102014141534.pdf; 99; Email an eva.nuhn@mbs-service.de

                                println( "Dateiendaten" )
                                println( singleRow )
                            }
                            else
                            {
                                stringArrayCompleteData[arrIndexSection] = [arrSingleRow[0]: arrSingleRow[1]]

// Here i tried to update the value and append a value
//stringArrayCompleteData[arrIndexSection]?.updateValue(arrSingleRow[1], forKey: arrSingleRow[0])
                                    // Error: cannot mutate a constant dictionary
                            }
                        }
                }
            }
        }
        println( stringArrayCompleteData )
        for key in stringArrayCompleteData.keys {
            println("Key: \(key)")
        }

Here are the results of the println()

[Auftraggeber: [Telefon2: ], Regulierer: [Telefon2: ], Baustelle: [Telefon2: ], Versicherung: [Telefon2: 01805], Header: [iPadNr:3E24-45B8-A2AC-7E3501BED78A], Objekt: [WeitererHinweis: Test]]
Key: Auftraggeber
Key: Regulierer
Key: Baustelle
Key: Versicherung
Key: Header
Key: Objekt

A: I couldn't understand exactly what you are doing but ... why do you use a dictionary where the value is another dictionary? Wouldn't be better to use a dictionary of Array instead?
Something like
 Dictionary<String, Array<Any>>()

Or better
   [String:[Any]]()

In this way the key of the Dictionary is the "section name" and the values of the Array (that you can add using the .append method) are just the values.
Hope this help, if not try to clarify what input and what output do you expect from your code, I know you're not a native speaker but it's difficult to understand what you really need here.
Bye!
D.


text:
Q: Sharing code between Firebase Functions and Cloud Run I have been using Firebase Functions so far. In this time, I would like to use Firebase Functions and Cloud Run in the same project. Is there a good way to share some code between Firebase Functions and Cloud Run? Will it work just by creating a symbolic link? Or, do I need to create private npm packages?
My developing environment is Windows 10, node 8. I'm using Firebase-tools to deploy Firebase Functions and intend to use gcloud command to deploy Cloud Run.
--- edit
I examined how to use the private npm package with Google Cloud Source Repositories. It looks a little cumbersome for this small project. Then I found useful information.

Local npm dependency "does not a contain a package.json file" in docker build, but runs fine with npm start https://stackoverflow.com/a/58368933/7908771

I tried the same way below and it seems to work fine.
--- edit 2
Project folder structure:
project/ ................... <- specify project root when `docker build`
├─ .dockerignore ...........
├─ containers/ .............
│  ├─ package.json ......... <- gather docker commands here
│  └─ hello-world/ .........
│     ├─ Dockerfile ........ <- COPY modules from functions in this Dockerfile
│     ├─ index.js .......... <- require modules from here
│     ├─ package-lock.json .
│     └─ package.json ......
├─ functions/ ..............
│  ├─ index.js .............
│  ├─ package-lock.json ....
│  ├─ package.json .........
│  ├─ modules/ .............
│  │  ├─ cloudStorage/ ..... <- wanted module
│  │  │  ├─ index.js .......
│  │  │  ├─ package.json ...
│  │  │  └─ test.js ........

In Dockerfile:
WORKDIR /usr/src/app
COPY functions/modules ../../functions/modules

.dockerignore on project root:
**/.git
./node_modules # <- ignore only root node_modules to COPY node_modules inside wanted modules

Require copied functions modules in js inside containers:
const cloudStorage = require('../../functions/modules/cloudStorage')

Build script:
{
  "scripts": {
    "build:hello-world": "docker build ../ --tag gcr.io/project/hello-world -f hello-world/Dockerfile",
  }
}

In this way, modules can be loaded when testing js outside the container, and can be loaded even inside the container.
Will this cause any problems? Please let me know if there is anything wrong.
Thank you.

A: A symlink will not work at all, as each deployment to Cloud Functions or Cloud Run is completely independent from each other.  They don't share any filesystems.  You will have to deploy the shared code to each product.  A private npm package might work.  The bottom line is that your package.json will have to describe where to get the code, or the code will have to be part of the deployment.


text:
Q: How to internationalize angular app using i18n Recently i got to internationalize my angular app. I heard about (i18n) and i have no idea about it but i am interested to go through it.
   Can anyone please suggest me some good articles regarding it.Thanks.

A: Angular translate is your friend.


text:
Q: Creating a global modal using react-redux and foundation reveal I'm creating a modal that displays information about a specific user and it's triggered by clicking on a picture. The modal should be able to fire up from different components. My approach is as follows (I use React with Redux):

*

*create store with a "modal" property that's set to a reducer "modalReducer"
modal: modalReducer

*modal is an object with the following properties: showModal=false, user=undefined, image=undefined

*When a div containing picture is clicked, the action is being dispatched that sets showModal to true (with username and url image link as arguments).
export var openModal = (user, image) => {
      return {
        type: 'OPEN_MODAL',
        user,
        image
      }
    }

*For the actual modal I use a foundation reveal modal and in its render method I check if modal.showModal == true and use jQuery to open it up.

Now, toggling the modal works as charm but I cannot use the modal.user and modal.image properties inside of the render method as it prints the following error message:

Uncaught Error: findComponentRoot(..., .0.2.0.0.1): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a  when using tables, nesting tags like , , or , or using non-SVG elements in an  parent. Try inspecting the child nodes of the element with React ID ``.

I'm almost certain the problem lies within the ProfileModal.jsx component. Any idea what I'm doing wrong?
export class ProfileModal extends React.Component {
  componentDidMount () {
    var elem = new Foundation.Reveal($('#profile-modal'));
    $('#profile-modal').on('closed.zf.reveal',()=>{this.props.dispatch(actions.hideModal())});
  }
  render () {
    var {modal} = this.props;
    if (modal.showModal) {
      $('#profile-modal').foundation('open');
    }
      return(

              <div className="modal-picture" style={{backgroundImage: `url(${modal.image})`}}>

{modal.user}

...


text:
Q: How to use exclamation in HTML using replit How to use "!" option in replit like we use it in VS code?
If we type ! in VS code it will autofill the program like in the provided image but i can see that option in replit and i can't fill it


text:
Q: Making a chat bot with Arduino I am trying to build a chat bot with an Arduino that works through the serial port. It sends the stuff to my Mac. I am having lots of problems, bugs, and so on. Can someone please point me in the right direction? Here is my code so far. I know it's not perfect but that's why I am trying to learn.
//error responses from 1 to 10
void error11() {
  Serial.println("What do you mean");
}

void error10() {
  Serial.println("I dont understand");
}
void error9() {
  Serial.println("My Programmer didnt give me a response for that please ask another question");
}
void error8() {
  Serial.println("?????");
}
void error7() {
  Serial.println("Huh??");
}
void error6() {
  Serial.println("Can not compute");
}
void error5() {
  Serial.println("Can you say that again");
}
void error4() {
  Serial.println("Im sorry what");
}
void error3() {
  Serial.println("Hmmm what");
}
void error2() {
  Serial.println("What");
}
void error1() {
  Serial.println("Sorry What Did You Say");
}
// greeting responses from 1 to 10
void greeting10() {
  Serial.println("What can i do for you");
}
void greeting9() {
  Serial.println("Yo");
}
void greeting8() {
  Serial.println("Hello Master");
}
void greeting7() {
  Serial.println("Greetings!!");
}
void greeting6() {
  Serial.println("Sup");
}
void greeting5() {
  Serial.println("Hiya");
}
void greeting4() {
  Serial.println("hi");
}
void greeting3() {
  Serial.println("How is it going");
}
void greeting2() {
  Serial.println("What's up");
}
void greeting1() {
  Serial.println("hello Friend");
}
String stringRead;
long randNumber;
void setup() {
  Serial.begin(9600);
}

void loop() {
  randNumber = random(4);
  if (Serial.available()) {
    stringRead = Serial.readStringUntil('\n');
    if(stringRead =="hello","Hello","HELLO") {
      greeting8();
      if (Serial.available()) {
        stringRead = Serial.readStringUntil('\n');
        if(stringRead =="hi","Hi","HI") {
          greeting4();
        }
      } else {
        error3();
      }
    }
  }
}

I really want to be able to have a random response from 1 to 10 but I couldn't get that to work either. Any help would be greatly appreciated.

A: if(stringRead =="hello","Hello","HELLO") {
is not the way to compare multiple items. You need to use logical OR:
if(stringRead =="hello" || stringRead == "Hello" || stringRead == "HELLO") {
Or you can convert the string to upper case and do just one comparison. See: https://www.arduino.cc/en/Reference/StringToUpperCase


text:
Q: Passing Jquery Autocomplete Selected Item ID to C# Json Here's my partial code for an Autocomplete function in jQuery:
$("#mpvalue").autocomplete({
    source: function (request, response) {
        $.ajax({
            datatype: 'json',
            url: '@Url.Action("GetEmpDetails")',
            type: 'GET',
            data: { term: $("#detail").val() },
            success: function (data)
            select: function (event, ui) {
                $(".list").append ( ui.item.name + ui.item.age)

C#:
public ActionResult Search(string name) {
    name = Request.QueryString["term"];
    return Json(routeList, JsonRequestBehavior.AllowGet);
}

If the user selects an item which outputs the values ui.item.name and ui.item.age, how do I pass these values over to controller in MVC?

A: The question doesn't seem to be complete. You have to elaborate more.
With the current understanding of your question-
source option in autocomplete is the source of data to the control. If you want to pass a value to the controller after selection of an item you have to give a ajax call and pass the selected item($("#mpvalue").val() here would give selected value).


text:
Q: What's the simplest method in Ruby of telling if SQLite returned a row? I am very new to Ruby and I am using it with SQLite.
I have written register and deregister functions but I am stuck writing a function to tell if a given user is registered in the database.
This is the current code:
 def registered?(l)
  db = SQLite3::Database.new "database.db"
  db.execute("SELECT user FROM t1 WHERE user = ?, ", l[1])
  end

What is the simplest method to tell if SQLite returned a row to this query?
Update
Thanks for the suggestions on how to do it. Here is the updated code:
 def registered?(l)
  db = SQLite3::Database.new "database.db"
  results = db.execute("SELECT user FROM t1 WHERE user = ?, ", l[1])
  !results.empty?
 end

and I am using it:
  if registered?(@nick)
   ...
  end

but I guess this isn't right, because my code under registered?(@nick) doesn't get triggered when the @nick is registered. I have both in the same class User. Am I doing something wrong?

A: response should not be an empty Array:
res = db.execute("SELECT user FROM t1 WHERE user = ?, ", l[1])
if !res.empty?
 # some row is returned
end

A: The result of your execution is an array (SQLite3::Execute):
class User
  def registered?
    db = SQLite3::Database.new "database.db"
    results = db.execute("SELECT user FROM t1 WHERE user = ?, ", self)
    !results.empty?
  end
end

Then you'd say @user.registered?


text:
Q: Show child elements if parent is visible I'm trying to have my form show child elements if the parent is visible and I keep getting an "undefined" error with my child element, even though I have it defined. I'm trying to have set this up where:
Q1: Checked responses will show parent elements (divs).
Q2: Depending on this response, it'll show child elements (divs).
Is there a way to do this?

    //Next Tab

    function next() {
            var formTabOne = document.getElementById("stepOne");
            formTabOne.classList.add("formTrans");
            formTabOne.addEventListener("transitionend", function({
                target
                }) {
                if (target === formTabOne) {
                    target.classList.add("hidden");
                    target.classList.remove("formTrans");
                    document.getElementById("stepTwo").classList.remove("hidden");
                }
            })
        }

        //Prev Tab

        function prev() {
            var formTabTwo = document.getElementById("stepTwo");
            formTabTwo.classList.add("formTrans");
            formTabTwo.addEventListener("transitionend", function({
                target
            }) {
                if (target === formTabTwo) {
                    target.classList.add("hidden");
                    target.classList.remove("formTrans");
                    document.getElementById("stepOne").classList.remove("hidden");
                }
            })
        }

function process() {
        var form = document.myForm;
        var biz = document.getElementById("biz");
        var career = document.getElementById("career");
        var change = document.getElementById("change");
        var eq = document.getElementById("eq");
        var empathy = document.getElementById("empathy");
        var pm = document.getElementById("pm");
        var bizMgr = document.getElementsByClassName("bizMgr");
        var bizEE = document.getElementsByClassName("bizEE");

            //Q1 - Topics

                document.querySelectorAll("#chkTopic input").forEach((el) => {
                    const contentID = el.id.replace("chk", "").toLowerCase()
                    document.getElementById(contentID).style.display = el.checked ? "block" : "none";
                });

            //Q2 - Employee Type

                var q2value = "";
                for (var i = 0; i < form.q2.length; i++) {
                var answer = form.q2[i];
                if (answer.checked) {
                    q2value = answer.value;
                    }
                }

                if (q2value == "1") {
                    if (biz.style.display = "block") {
                        bizMgr.style.display = "block";
                        bizEE.style.display = "block";
                    }
                } else {
                    if (biz.style.display = "block") {
                        document.getElementsByClassName("bizEE").style.display = "block";
                    }
                }
        }
    html {
            scroll-behavior: smooth;
        }

        #formWrapper {
            background-color: #eaeaea;
            padding: 20px;
            margin-bottom: 40px;
            min-height: 300px;
        }

        #myForm {
            width: 70%;
            min-height: 280px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            border: 1px solid #dedede;
            box-sizing: border-box;
        }

        .formStep {
            opacity: 1;
            background: #fff;
        }

        .formTrans {
            visibility: hidden;
            opacity: 0;
            transition: visibility 0s 200ms, opacity 200ms linear;
        }

        .hidden {
            display: none;
        }

        #biz, #career, #change, #eq, #empathy, #pm, #pd {
            display: none;
            width: 100%;
            min-height: 200px;
            box-sizing: border-box;
            margin-bottom: 30px;
            border: 1px solid #000;
        }

        .bizMgr, .bizEE, .careerMgr, .careerEE, .changeMgr, .changeEE, .eqMgr, .eqEE, .empathyMgr, .empathyEE, .pmMgr, .pmEE, .pdMgr, .pdEE {
            display: none;
        }
<form name="myForm" id="myForm">

        <input type="button" value="Skip This" onclick="formSkip();">

            Select the topic(s) you're interested in:

                <input id="chkBiz" type="checkbox" value="1">Business Structure/Acumen

                <input id="chkCareer" type="checkbox" value="2">Career Development

                <input id="chkChange" type="checkbox" value="3">Change

                <input id="chkEQ" type="checkbox" value="4">Emotional Intelligence

                <input id="chkEmpathy" type="checkbox" value="5">Empathy

                <input id="chkPM" type="checkbox" value="6">Performance Management

            <button type="button" id="btnStepOne" onclick="next();">Next</button>

            Are you a people leader?

            <input type="radio" name="q2" value="0">No

            <input type="radio" name="q2" value="1">Yes

            <button type="button" id="btnStepTwo" onclick="prev();">Previous</button>
            <input type="button" value="Show Results" onclick="process();">
            <input type="reset" value="Start Over" onclick="formReset();">

    </form>

    Business Structure/Acumen

Manager Content

Employee Content

    Career Development

Manager Content

Employee Content

    Change

Manager Content

Employee Content

    Emotional Intelligence

Manager Content

Employee Content

    Empathy

Manager Content

Employee Content

    Performance Management

Manager Content

Employee Content

A: .getElementsByClassName returns a collection, bizMgr and bizEE are both collections. You have to iterate the collections and set each element to style.display = 'block'. You can't just call xxx.style.display on a javascript collection. You would want to change your code like the following:
            if (q2value == "1") {
                if (biz.style.display = "block") {
                    //bizMgr.style.display = "block"; -NO
                    //bizEE.style.display = "block"; -NO
                    for(let i = 0; i < bizMgr.length; i++){
                       bizMgr[i].style.display = "block";
                    }

                    for(let j = 0; j < bizEE.length; j++){
                       bizEE[j].style.display = "block";
                    }
                }
            } else {
                if (biz.style.display = "block") {
                    //document.getElementsByClassName("bizEE").style.display = "block"; -NO
                    for(let j = 0; j < bizEE.length; j++){
                       bizEE[j].style.display = "block";
                    }
                }
            }


text:
Q: fullcalendar two days event span days are displaying in only one day I wany to display full calendar monthly view events in different dates if event is overnight booking.
I am not getting any idea about this topic as it was customized to display events in single days and its not supporting drag option.
We are passing string as text to display content.
My Javascript integration code is:
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
    theme: true,
     dayClick: function(date, allDay, jsEvent, view) {
        if (allDay) {
            // Clicked on the entire day
            convertedDate= convert(date);
            if ($(jsEvent.target).is('span.fc-day-content') ){
                // Clicked on the day number
                      if(${managePriv ==1}){
                          var selectedDate = document.getElementById("selectedDate").value;
                          window.open("<%=contextPath%>/rooms/roomReservationFrame.action?startingtime="+convertedDate+"&screenFlag=M&selectedDate="+selectedDate,"roomReservation","width=840,height=460,scrollBars=no");
                      }
            }
        }
    },
    header: {
        left: '',
        center: '',
        right: ''
    },
    events: ${jsonstring} ,

    eventRender: function(event, element, view) {
        element.find('span.fc-event-title').html(element.find('span.fc-event-title').text());
         if (event.start.getMonth() != view.start.getMonth())
            return false;
    }

});
var date = new Date();
var d = 1;
var m="${month}";
var y="${year}";
$('#calendar').fullCalendar('gotoDate', y,m,d);

    if(${managePriv !=1}){
      $('span.fc-day-content').css({'visibility': 'hidden'});
    }
});

A: Here issue is for every json object we have to add color:'colorcode' attribute , as it is displaying but default its showing white background show its showing in only in one day and div class = 'fc-event-title' i am appending text directly to that div , so its just printing label like plain text.need any clarification for this question replay back me


text:
Q: Installing the kernel EFI stub loader in kernel 3.2? Kernel EFI stub loader support was added in kernel 3.3, but I'm stuck on 3.2 running an Ubuntu 12.04 64bit distribution. Is there a way for me to somehow bring that stub loader support into my kernel?

A: I ended up simply installing a later kernel. You'd be surprised how easy this is. Simply searching packages.ubuntu.com for kernel packages allowed me to find the packages I needed. I needed to install essentially linux-image-3.X.*, linux-image-extra-3.X.*, and linux-headers-3.X.*. Posting from a nice, shiny EFI-booting Linux.


text:
Q: Confused with Console's command for manage.py import os
import sys

def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

when I run it into console it says:
File "manage.py", line 17
) from exc
^
SyntaxError: invalid syntax .
whats the mistake in this code ? some one plss help!!

A: I copy-pasted your code in my editor and it worked fine.
I guess either you do not have the same thing on your side than what you posted here, or you have an indentation problem. Pay very close attention to indetation, or try pasting the content here back into your file.


text:
Q: Add list view to Fluid template I've built a custom extension which displays comments for a page.
But, of course, I want to have the comments section on every page. Is there a way to add it into the Fluid template so that I won't have to add it to every single page?
Looking for something like this:
<f:blabla.bla extension="tx_comment" action="list"/>

A: You don't need to create your own viewhelper for this. You can use the VHS extension and use render.request
<v:render.request action="[string|NULL]" controller="[string|NULL]" extensionName="[string|NULL]" pluginName="[string|NULL]" vendorName="[string|NULL]" arguments="{foo: 'bar'}" onError="NULL" graceful="1">
    <!-- tag content - may be ignored! -->
</v:render.request>

https://fluidtypo3.org/viewhelpers/vhs/master/Render/RequestViewHelper.html


text: Q: Any way to speed up initialization of statsmodels.nonparametric.kernel_regression.KernelReg I am trying to fit a kernel regression to data (n is approx 230,000). I am using statsmodels.nonparametric.kernel_regression.KernelReg, which works nicely on small amounts of data but is taking multiple hours to initialize on even a small subset of my table. Has anyone experienced this before? Is there any way to speed it up?


text:
Q: How to make a Grouped Bar Plot with a line I have the following dataset:
HIU,0.0833333333,0,0.35,0.0208333333,0.40625,0,0.21875,0.125,0.078125,0.0104166667,1,0.53125,0.4375
TTHY,0,0,0.8,0,0.5,0,0.7083333333,0.2708333333,0,0.6597222222,0,0.1435185185,0
Full,0.0554986339,0.1034836066,0.4620901639,0.0683060109,0.4961577869,0.0696721311,0.222079918,0.1465163934,0.2085040984,0.0476007514,0.893613388,0.396943306,0.4223872951

I made a grouped bar plot according to the rows of HIU and TTHY (figure 1). But I want to add a line according to the "Full" row, such as the second image.
Figure 1:

Figure 2:

How can I do it with R? This is my current code:
df = read.csv('TTR-HIU/resultados.csv',header=FALSE,colClasses=c("NULL",NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA))
df.bar <- barplot(as.matrix(df[-nrow(df),]),beside=TRUE,col=c("darkblue","red"))

A: Using ggplot2, you could try something like this:
# put data in data frame:
df <- data.frame(HIU = c(0.0833333333,0,0.35,0.0208333333,0.40625,0,0.21875,0.125,0.078125,0.0104166667,1,0.53125,0.4375),
                 TTHY = c(0,0,0.8,0,0.5,0,0.7083333333,0.2708333333,0,0.6597222222,0,0.1435185185,0),
                 Full= c(0.0554986339,0.1034836066,0.4620901639,0.0683060109,0.4961577869,0.0696721311,0.222079918,0.1465163934,0.2085040984,0.0476007514,0.893613388,0.396943306,0.4223872951))

library(ggplot2)
library(tidyr) # to make data long (gather)
# create x-values:
df$x <- as.factor(seq_len(nrow(df)))
# make data long for ggplot2:
df_long <- df %>% gather(key, value, -x)
ggplot() +
  # plot bars:
  geom_col(data = subset(df_long, key %in% c("HIU", "TTHY")),
           mapping = aes(x = x, y = value, fill = key),
           position = position_dodge()) +
  # plot lines:
  geom_line(data = subset(df_long, key == "Full"),
            mapping = aes(x = x, y = value, group = key, color = key),
            size = 2) +
  # make plot look a little like your desired output:
  scale_color_manual(values = c("Full" = "yellow")) +
  scale_fill_manual(values = c("HIU" = "blue", "TTHY" = "red")) +
  theme_minimal() +
  theme(axis.title = element_blank(),
        legend.title = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank())

However, you might have to put your data in data-frame-shape as in this example. Use dput to show how your data exactly looks like, if you need further help...


text:
Q: How to Add a Menu Without a Bar I've seen a lot of applications
There is no actionbar
But there is menu how?
like this picture
enter image description here
How can I create this

A: http://developer.android.com/guide/topics/ui/menus.html
learn more ^
public void Noactionbar(View v) {
    PopupMenu popup = new PopupMenu(this, v);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.actions, popup.getMenu());
    popup.show();
}


text:
Q: when a gas turns into plasma does its particles get smaller? In expansion the space in between the particles increase, not the particles, however does that still apply to plasma? and when a gas turns into plasma do the particles get smaller?

A: When a gas turns into a plasma, each atom or molecule loses one or more electrons. These electrons are a lot smaller than atoms or molecules, so in this sense many (about half) the particles in the plasma are a lot smaller than the atoms or molecules of the original gas.
An atom which has lost an electron is also somewhat smaller on average than the neutral atom, but this is not such a big effect. For atoms in group 1 of the periodic table is a moderately substantial effect.
Although the particles are thus smaller, as measured by their distribution of mass and charge, nevertheless their effects reach out to larger distances because now they are charged, so they each have a substantial electric field around them, and a magnetic field too if they are moving. When considering things like collisions and scattering of light, this is usually more important than the size of the particle itself.


text:
Q: Adding common factors in C I'm just trying to add all common factors of 3 and 5, stopping at a sum of 1000. I keep getting an expected expression on line 15:18. Is there anyone that can find any new errors or help? It would be much appreciated. Thanks.
#include<stdio.h>
#include<stdlib.h>

/*Multiples of 3 and 5
If we list all natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6
and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.*/

int cd_function(int n, int sum)
{

    if(sum >= 1000)
        return 0;

    if(n%3 == 0 || n%5 == 0)
            sum + return cd_function(n, sum);
}

int main(void)
{
    int i, iter, sum = 0;

    for(i = 0; i < cd_function(iter, sum); i++)
        sum++;

    return 0;
}

A: #include<stdio.h>
#include<stdlib.h>

Most people will add a space here:
#include <stdio.h>
#include <stdlib.h>

.
int cd_function(int n, int sum)
{

    if(sum >= 1000)
        return 0;

    if(n%3 == 0 || n%5 == 0)
            sum + return cd_function(n, sum);
}

There is two ways, to have this functions add n to sum: Either by passing sum as pointer (reference), this would be done this way:
void cd_function(int n, int * sum) {
    // if (*sum >= 1000) - no need to test this here
    if (!n%3 || !n%5) {
        *sum += stuff;
    }
}

or by having the function return the new sum:
int cd_function(int n, int sum) {
    // if (sum >= 1000) - no need to test this here
    if (!n%3 || !n%5) {
        return sum + stuff;
    } else {
        return sum;
    }
}

Now, sum + return cd_function(n, sum); is wrong, YSC already told so in his comment. So you should either use *sum += n; or return sum + n; (i.e. replace stuff by n above).
int main(void)
{
    int i, iter, sum = 0;

Since you don't need iter, get rid of it:
    int i, sum = 0;

    for(i = 0; i < cd_function(iter, sum); i++)
        sum++;

a. If you want to sum some[tm] is, then you shouldn't increment sum in each iteration.
    for (i = 0; i < cd_function(iter, sum); i++)
        ;

b. Then you should get a proper exit condition. You wanted to sum everything until you reach a sum >= 1000, so write that in the condition:
    for (i = 0; sum < 1000; i++)
        /* ??? i < cd_function(iter, sum) */;

c. Depending on the implementation of cd_function you choose from above, you would now either call
        cd_function(i, &sum);

or
        sum = cd_function(i, sum);

d. And finally, you should add curly brackets, even there is only one statement:
    for (i = 0; sum < 1000; i++) {
        // option 1
        cd_function(i, &sum);
        // option 2
        sum = cd_function(i, sum);
    }

rest is fine:
    return 0;
}


text:
Q: How can I click on a pop-up Calendar wizard in Selenium 2? I'm using selenium 2 for a project which allows for date selection using jsf calendar wizard from myfaces (jsf 1.1). Can some one help me the steps for date selection. Thank you in advance.
Date of Birht field screenshot

Calendar popup screenshot

Corresponding html being generated

      <input id="firstApplicant2:ApplicantContent-DateOfBirth" name="firstApplicant2:ApplicantContent-DateOfBirth" type="text" maxlength="10" class="dateStyle" onfocus="selectText('null', 'firstApplicant2:ApplicantContent-DateOfBirth')" onclick="selectText('null', 'firstApplicant2:ApplicantContent-DateOfBirth')">

                Today is 06/15/2011

A: Would it be acceptable to just update the input text field with the properly formatted date? Unless you are specifically testing that MyFaces widget, I think this should suffice.


text:
Q: css radio buttons toggle background i have radio buttons styled appear as regular buttons.  i made it so once you click on the first button, the second button drops its opacity. the problem i am having is that once you click the second button, the first button does not change opacity.  i had accomplished this with jquery but wanted to do it in css instead.
heres an example: http://jsfiddle.net/mahsj3qx/
html:
<input type="radio" id="radio01" name="konnect" value="yes">yes
<input type="radio" id="radio02" name="konnect" value="no">no

css:
input[type=radio] {
    display: none;
}
input[type=radio] + label {
    cursor: pointer;
    float: left;
    padding: 5px 0;
    font-size: 18px;
    color: #ffffff;
    text-align: center;
    width: 50%;
    height: auto;
    margin-bottom: 10px;
    vertical-align: middle;
}
/* yes */
#radio01 + label {
    background: rgb(46, 204, 113);
}
#radio01 + label:hover {
    background: rgba(46, 204, 113, 0.75);
}
#radio01:checked + label {
    background: rgb(39, 174, 96);
}
#radio01:checked ~ label[for="radio02"] {
    background: rgba(26, 188, 156, 0.25);
}
/* no */
#radio02 + label {
    background: rgb(26, 188, 156);
}
#radio02 + label:hover {
    background: rgba(26, 188, 156, 0.75);
}
#radio02:checked ~ label[for="radio01"] {
    background: rgba(46, 204, 113, 0.25);
}
#radio02:checked + label {
    background: rgb(22, 160, 133);
}

A: Try this demo
#radio01 + label {
    background: rgba(26, 188, 156, 0.25);
}


text:
Q: AX2012: Capture SysInfoAction on form initialization Situation:
I am opening a form via a SysInfoAction (SysInfoAction_FormrunQuery to be exact) from an error message (info log) as follow (Compressed a bit):
query.addDataSource(tableNum(WDPErrorLogView)).addRange(fieldNum(WDPErrorLogView, ErrorOutboundMessage)).value(SysQuery::value(resultRecId));
error("@WDP1299", '', SysInfoAction_FormrunQuery::newFormnameQuery(formStr(WDPErrorLog), query));

Problem:
The form I am calling here, has multiple tabs, since it can be opened with queries from various tables. I would like to capture this calling record to not only filter on the record passed (This already happens thanks to the SysInfoAction), but also make the appropriate tab page active.
I thought that element.args().record() would contain this calling record, but to my surprise it does not. Any ideas how to could get hold of this record... or, at least its table id?

A: This is easy.  Just add a parmMethod for an object/caller to \Classes\SysInfoAction_FormrunQuery.  Copy the static method newFormnameQuery and call it newFormnameQueryWithCaller for example and then add an extra argument, then set that argument in your parm method with the same style as newFormnameQuery.
Then in your \Classes\SysInfoAction_FormrunQuery\run, where it sets up the args record, just add args.caller(...) and set your caller object if it exists.


text:
Q: C++-CLI Pipeline only returns the first row of the error message I'm executing exchange powershell commands through a pipeline from my code.
The problem is that when the command is executed on the powershell directly the error returned is four rows long, but when I run the command through the pipeline it only returns the first row of the error message.
This is the code I have so far:
bool ps_calls::check_invoke(Pipeline^ pipeline)
{
    if (pipeline->Error->Count <= 0)
        return true;

    Collection<System::Object^> errorCollection =  pipeline->Error->ReadToEnd();
    for (int i=0; i< errorCollection.Count; i++)
    {
        String^ msg = String::Format("Error {0}",errorCollection[i]->ToString());
        m_errors->Add(msg);
        m_logger->info_msg(String::Format("ERROR: {0}", msg));
    }

    return false;
}

This is an example of what my pipeline returns now:
ERROR: Error The operation couldn't be performed because object 'Testing' couldn't be found on 'server'.

This is an example of what the error message is if the same command is executed on the powershell console manually:
The operation couldn't be performed because object 'test' couldn't be found on 'server'.

    + CategoryInfo          : NotSpecified: (:) [Get-MailboxDatabase], ManagementObjectNotFoundException

    + FullyQualifiedErrorId : 2F753561,Microsoft.Exchange.Management.SystemConfigurationTasks.GetMailboxDatabase

    + PSComputerName        : server

I would like to be able to get the rest of this error message as well so that I can see the ErrorID when an error occurs.

A: PowerShell doesn't call ToString when it does formatting, that's why you don't see the same output.
Some host applications typically pipe output to Out-Default - if you did that, you'd see the expected format for errors.
Other host applications will pipe output to Out-String - this will format objects in the same way that the would be formatted if piped to Out-Default, but you'll get a string object that you can log however you need to.


text:
Q: explain the main reason to use getColor() method from ContextCompat class? LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);
int color = ContextCompat.getColor(getContext(), mColorResourceId);
linearLayout.setBackgroundColor(color);

i have these line of code :
mColorResourceId it's hold R.color.category_numbers -> mColorResourceId = R.color.category_numbers
when i pass mColorResourceId directly to setBackgroundColor(mColorResourceId); it's doesn't change the color despite the method accept int value .
my question why i need this extra step int color = ContextCompat.getColor(getContext(), mColorResourceId); to change the color ??

A: The setBackgroundColor() method accepts an int that is supposed to be a color value in aarrggbb format. The resource ID R.color.category_numbers is also an int, but it is not a color value; instead it is the identifier of a color resource. Calling ContextCompat.getColor(getContext(), mColorResourceId) retrieves the actual color value corresponding to mColorResourceId.
Part of the reason Android does this kind of indirection is to provide flexibility. The actual color returned may depend on the current theme or the device configuration and may actually change at run time (depending on how you declare your color resource).


text:
Q: ASP.NET MVC3 Upload a file from a Partial view (and fill the corresponding field in the Model) I know the subject has already been discussed on SO and elsewhere, but I can't find any answer to my question.

I'm working on an ASP.NET MVC3 project, and I'd like to create a Partial view containing a FileUpload. This partial view is called on a basic Create page, and I'd like the file to upload belongs to the model to create. It is only when the user will submit the form the selected file will be uploaded.
Here is an explanation by the code :

Model ModelToCreate

public class ModelToCreate
{
    //Some properties

    public FileUploadModel Files { get; set; }
}

Model FileUploadModel

public class FileUploadModel
{
    public IEnumerable<HttpPostedFileBase> Files { get; set; }
}

My PartialView (_UploadFiles.cshtml)

@model Models.ModelToCreate

//I tried with Html.BeginForm(Create, MyController instead of null, null, but with no result.
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })
}

How the partial view is called (by Create.cshtml)

@Html.Partial("_UploadFiles")

I also tried with @Html.Partial("_UploadFiles", Model), but with no result...

When I click the Submit button in Create.cshtml, the form is submitted to my controller BUT Files field is always null whereas the other datas are OK.

Am I missing something ? Could you indicate my where (and why ?)
Thank you !

UPDATE (and Solution)
Here is some additionnal information I forgot about Create.cshtml
The form look like this :
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "target-form" }))
{
    // Some fields, Textboxes and others CheckBoxes

    //Call to partial View
}

When I take a look to generated source code, I see the partial view in a <form> tag... So I have a <tag> in a <tag>, which is illegal and "ignored". This causes the problem
SOLUTION Just add this tag to the BeginForm of Create.cshtml :
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "target-form", enctype = "multipart/form-data" }))

and call my Partial View as
@Html.Partial("_UploadFiles", Model)

A: Ok, this will get it working for you.
Create.cshtml View (With the form & submit moved outside of the partial)
@using(Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
   @Html.Partial("_UploadFiles", Model)
   <input type="submit" value="submit" />
}

_UploadFiles.cshtml view
@model ModelToCreate

@Html.TextBoxFor(m => m.Files.Files, new { type = "file", name = "Files" })

Models (Changed to a List and also note the initializer in the FileUploadModel constructor).
public class ModelToCreate
{
    //Some properties
    public FileUploadModel Files { get; set; }
}

public class FileUploadModel
{
   public FileUploadModel()
   {
        Files = new List<HttpPostedFileBase>();
   }

   public List<HttpPostedFileBase> Files { get; set; }
}

Controller actions:
public ActionResult Create()
{
    var model = new ModelToCreate();

    return View(model);

}

[HttpPost]
public ActionResult Create(ModelToCreate model)
{
   var file = model.Files.Files[0];
   return View(model);
}


text:
Q: My File Upload Form Does Not Upload Non-Image Files. Why? I have an HTML file upload form that uploads files on my server using PHP. It uploads image files but other type of files such as mp3 or mp4 are not uploading. I can't figure out what's the problem.
Here is the code:

HTML :

<form id="uploadForm" method="post" action="upload.php?ref=home" enctype="multipart/form-data">
<input id="shout_media" class="hidden" name="media" type="file" />
</form>

PHP :

<?php

  if(isset($_GET['ref'])) {

   if((isset($_FILES['media']))&&(is_uploaded_file($_FILES['media']['tmp_name']))) {

      $name = $_FILES['media']['name'];

      $tmpname = $_FILES['media']['tmp_name'];

      $size = $_FILES['media']['size'];

      $i = strrpos($name,".");

      if (!$i) { return ""; }

      $l = strlen($name) - $i;

      $xt = substr($name,$i+1,$l);

      $ext = strtolower($xt);

      if(preg_match("/(jpg|jpeg|png|gif|mp3|mp4)/",$ext)) {

          if(move_uploaded_file($tmpname,'photos/'.$name.'')) {

               echo 'Uploaded successfully!';

           }

      }

  }

I'm using jQuery and http://www.malsup.com/jquery/form/ Ajax Form Plugin to upload files without reloading the page.

AJAX Form Plugin Code:

$("#uploadForm").ajaxForm({
   success: function(responseText) {
      if(responseText.length>0) {
           $(".uploadStatus").text('Uploaded!');
  }
   }
}).submit();

What is the problem and how can I solve it? I need to allow my users to upload other type of files, most importantly MP3s and MP4s.
Thank you!

A: Line
if(preg_match("/(jpg|jpeg|png|gif)/",$ext)) {
is filtering files by extension. Add additional extensions you want to allow to the list, like
if(preg_match("/(jpg|jpeg|png|gif|mp3|mp4)/",$ext)) {
Just be aware that all files will be uploaded to the same folder, so even your mp3 files will be in photos folder. If you don't want that, you have to change path for move_uploaded_file based on the filetype.
Since you have updated your question, check post_max_size and upload_max_filesize settings in php to see if your files are larger than the maximum allowed size


text:
Q: I implemented ADS in recycler view every 3 items but repeats the first 3 items everytime I tried implementing ADS in recycler view every 3 items but instead of following the next items in the list of items, it repeats the first 3 times over and over until the list.size() is over.
AdMob , ad item in Recycler View hides some items and creates spaces after the ad
For achieving this, i tried to implement this code abovein my own code and it works fine except for the repetition of the first 3 items. The code is modified to satisfy my needs, so it may seem strange.
open class AdsAdapter2(override val activity: FragmentActivity, var dataSet: MutableList<adslist>, protected var itemLayoutRes: Int,
    showSectionName: Boolean = true) : AbsMultiSelectAdapter<AdsAdapter2.ViewHolder, adslist>(activity, R.menu.menu_media_selection),
    PopupTextProvider {
    var onItemClick: ((adslist) -> Unit)? = null
    private var showSectionName = true

    init {
        this.showSectionName = showSectionName
        this.setHasStableIds(true)
    }

    open fun swapDataSet(dataSet: List<adslist>) {
        this.dataSet = ArrayList(dataSet)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        if (viewType == AD_VIEWTYPE){

            val v = LayoutInflater.from(activity).inflate(R.layout.item_favourite_card, parent, false)

            return ViewHolder(v)
        }
        else{
             val v = LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false)

             return ViewHolder(v)

        }
    }

 override fun onBindViewHolder(holder: ViewHolder, position: Int) {

       val card = getCardForPosition(position)
        if (card == null){
            Picasso.get().load(R.drawable.default_artist_art).into(holder.image)
        } else {

            // holder.courseNameTV.text = song.artistandname
            if (card.img == 0) {
                Picasso.get().load(card.img2).into(holder.img)
            } else {
                Picasso.get().load(card.img).into(holder.img)
            }
        }
    }

    override fun getItemCount() = dataSet.size + (dataSet.size / ITEMS_PER_AD)

    override fun getIdentifier(position: Int): adslist? {
        return getCardForPosition(position)
    }

open inner  class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) {

        protected open val adslist: adslist
            get() = dataSet[layoutPosition]

        //  val layoutposition: LinearLayout = itemView.findViewById(R.id.layoutposition)

        init {
            itemView.setOnClickListener {
                onItemClick?.invoke(getCardForPosition(position)!!) //WHEN AD CLICKED ==NULL
            }
        }

        val img: AppCompatImageView = itemView.findViewById(R.id.image)
        val layput: MaterialCardView = itemView.findViewById(R.id.imageContainer)
        //  val layoutposition: LinearLayout = itemView.findViewById(R.id.layoutposition)
        val layout: MaterialCardView = itemView.findViewById(R.id.imageContainer)
        val image: AppCompatImageView = itemView.findViewById(R.id.image)
        val title: MaterialTextView = itemView.findViewById(R.id.title)

    }

    companion object {
        val TAG: String = AdsAdapter2::class.java.simpleName
        const val ITEMS_PER_AD = 3
        const val AD_FREQUENCY = ITEMS_PER_AD + 1
        const val AD_VIEWTYPE = 0
        const val CARD_VIEWTYPE = 1
    }

    override fun onMultipleItemAction(menuItem: MenuItem, selection: List<adslist>) {
        TODO("Not yet implemented")
    }

    override fun getPopupText(position: Int): String {
        TODO("Not yet implemented")
    }

    override fun getName(model: adslist): String? {
        TODO("Not yet implemented")
    }

    private fun isCard(position: Int) = (position + 1) % AD_FREQUENCY != 0

    private fun getCardForPosition(position: Int): adslist? {
        val offset = position / AD_FREQUENCY
        return if (isCard(position)) dataSet[position - offset] else null
    }

    override fun getItemViewType(position: Int) =
        if (isCard(position)) CARD_VIEWTYPE else AD_VIEWTYPE

}

The logic of knowing which part of the list is gonna be an AD or a CARD is explained in the answer of the url above and it is applied on the last 3 functions and i do think the problem resides there but i cant see it clearly.
I'm not  a super developer so it could be something so simple


text:
Q: maven-metadata.xml not generated in artifactory with jenkins I´m not sure how does POM in maven works correctly. Here is the thing.
I was able to create a job with Jenkins Which  build & publish a WAR from java code, to Artifactory using maven (with artifactory plug in) with job number at the end to keep versioning .Then a maven-metadata.xml is created on artifactory as showed below.

After that on a second job,  with build with parameters option in jenkins  I choose artifact and deploy the number of war I want like this

Now I wanted to do the same but using maven to ZIP just a folder and publish to artifactory. I was able  to do that with maven assembly plug in successfully using a POM and a zip.xml file. Thing is that the metadata.xml in artifactory is not generated. It only generates the zip file (also a jar) but not metadata.xml which is needed so I can use jenkins to choose Zip file. here is image from artifactory of Zip generated and error I receive from jenkins:

So question is, how does POM generates this metadata.xml file in artifactory? I used same pom of Java project tha was used to build and publish WAR, except that  on   part I included maven assembly plugin to zip file, and zip  was successfully uploaded and created as I showed on image . Here is POM and zip.xml
    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    <groupId>com.grey</groupId>
    <artifactId>go</artifactId>
    <version>${releaseVersion}</version>

    <name>go</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <releaseVersion>0.0.0-SNAPSHOT</releaseVersion>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-documentdb</artifactId>
            <version>1.5.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>

    </dependencies>

    <build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.2-beta-5</version>
            <configuration>
                <descriptors>
                    <descriptor>assembly/zip.xml</descriptor>
                </descriptors>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id> <!-- this is used for inheritance merges -->
                    <phase>package</phase> <!-- append to the packaging phase. -->
                    <goals>
                        <goal>single</goal> <!-- goals == mojos -->
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
   </build>
</project>

And here is the zip.xml
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<baseDirectory>/</baseDirectory>
    <formats>
        <format>zip</format>
    </formats>
    <fileSets>
        <fileSet>
            <directory>static</directory>
            <outputDirectory>/</outputDirectory>
        </fileSet>
    </fileSets>
</assembly>

Please need help since I´m dealing with this and is not quite clear. I´m not a developer so my knowledge in java and  pom file and maven is not one of the bests.  thanks for your help!
This is jenkinfile to upload code to artifactory. same as used for Java app.
Only thin changed was repo name in artifactory and the command "package" instead of "clean install"
node {
    def server  = Artifactory.server 'azure-artifactory'
    def rtMaven = Artifactory.newMavenBuild()
    def buildInfo //= rtMaven.run pom: 'pom.xml', goals: 'clean install -D releaseVersion="${BUILD_NUMBER}"'

    stage ('Code Checkout') {
                git branch: 'devopstest',
                    credentialsId: '3e3c8889-0dcc-4b4d-bae1-ac140894d292',
                    url: 'ssh://git@bitbucket.org/xxxxx/xxxxxxx'
            }

    stage('Artifactory Configuration') {
        // Tool name from Jenkins configuration
        //rtMaven.tool = 'Apache Maven 3.0.5'
        env.MAVEN_HOME = '/usr/share/maven/'
        // Set Artifactory repositories for dependencies resolution and artifacts deployment.
        rtMaven.deployer server: server, releaseRepo: 'go-fe-maven-2'

    }

     stage('Maven build') {
        //buildInfo = rtMaven.run pom: 'pom.xml', goals: 'clean install -D releaseVersion="${BUILD_NUMBER}"'
        buildInfo = rtMaven.run pom: 'pom.xml', goals: 'package -D releaseVersion="${BUILD_NUMBER}"'
      //  rtMaven.deployer.deployArtifacts buildInfo
    }

stage('Publish build info') {
       // server.publishBuildInfo buildInfo
       server.publishBuildInfo buildInfo
    }

// Wipe the workspace so we are building completely clean
        deleteDir()
}


text:
Q: Getting JavaScript to create a full li function loadFamily() {

  var family = ["Kelly", "Paul", "Jason", "Jessica", "Mat"];
  var ulElement = document.getElementById("nameList");

  for (var name in family);
  {
    var listItem = ulElement.appendChild(document.createElement("li"));
    listItem.appendChild(document.createTextNode(family[name]));
  }

}

I am trying to get this code to create a ul in my html. I have been able to make it work; however it will only place the last name of the array when the page is loaded. This is my first time working with JavaScript and I'm sure that this is a really simple problem, but any help is much appreciated!

A: You are stopping your for loop here:
for (var name in family);
//----------------------^ Remove this.

It runs fully and the index is in the last, so it executes only the last one now. So change your code to:
function loadFamily() {

  var family = ["Kelly", "Paul", "Jason", "Jessica", "Mat"];
  var ulElement = document.getElementById("nameList");

  for (var name in family) {
    var listItem = ulElement.appendChild(document.createElement("li"));
    listItem.appendChild(document.createTextNode(family[name]));
  }

}

Note: A for...in loop only iterates over enumerable properties. Do not use this for Arrays. It is better to change your loop like:
function loadFamily() {

  var family = ["Kelly", "Paul", "Jason", "Jessica", "Mat"];
  var ulElement = document.getElementById("nameList");

  for (var name = 0; name < family.length; name++) {
    var listItem = ulElement.appendChild(document.createElement("li"));
    listItem.appendChild(document.createTextNode(family[name]));
  }

}

The above is better and good.

A: The is more of a note than the answer as the other person answered you.  But arrays have a forEach() can use for iteration.
var family = ["Kelly", "Paul", "Jason", "Jessica", "Mat"];

function loadFamily() {
    var ulElement = document.getElementById("nameList");

    family.forEach(function(name){
        var listItem = ulElement.appendChild(document.createElement("li"));
        listItem.appendChild(document.createTextNode(name));
    });
}

You also have jquery in your tags but none of this is jquery.  But, just in case you were curious how you could do the same with jquery.
var family = ["Kelly", "Paul", "Jason", "Jessica", "Mat"];

function loadFamily() {
    $('#nameList').append($.map(family, function(name){
        return $('<li>').text(name);
    }));
}


text:
Q: How to find out what fields are referring to a NetSuite custom field I have a problem deleting a custom field from a vendor in NetSuite. When I try to delete it I get the following error message.

This custom field cannot be deleted because it is referred to by other custom fields

I've looked at many of my other custom fields and columns but I can't find any that are referencing this one. Is there a way to find all fields that refer to a particular custom field?

A: This is because you might be using this custom field value some where else. I'm not sure if there is any inbuilt functionality to identify the other fields which are being referred by your custom field. I had a similar issue but I solved it using mass update. I set that field value for all the vendor as blank then I was able to delete the custom field.
In case it is a custom list field then follow the steps bellow :
First delete the list from Setup > Customization > Transaction Item Options, then from the Custom Item Fields and then finally from the Custom Lists

A: To narrow down the list of fields to check, go to Customization->Lists, Records & Fields->Entity Fields. Sort that list by the Vendor column. That is the list that needs to be checked. Open each of these fields, and check that the 'Field' under the 'Validation and Defaulting' tab is not your custom field that you want to delete. Then check the values on the 'Sourcing and Filtering' tab as well.
Good luck, and hopefully there is not too many vendor fields to check this way!