text:
Q: Working through bugs of Python program, not sure why they are occuring I am building a program to add a list with a specific length to a bigger list from a string. For example, In the string, "The quick brown fox jumped over the lazy dog" if I were to split it up in a list of 4, my return value would be
"[[The, quick, brown, fox], [jumped, over, the, lazy], [dog]]"

My code is:
text = "The quick brown fox jumped over the lazy dog"
micro = []
count = 1
split = text.split(" ")
total_list = []
for i in range(0, len(split)):
    print(split[i], count)
    if count < 5:
        micro.append(split[i])
        print(micro)
        if count == 4:
            total_list.append(micro)
            print(total_list)
            micro.clear()
            count = 0
     count+=1
print(total_list)

The idea of this is to split the text into a big list, keep a counter to add in groups of 4, and then add that smaller split to the overall list. Because this string is odd, I know that I won't add dog to the end, which I don't know how to fix given my current setup. My output is:The 1
['The']
quick 2
['The', 'quick']
brown 3
['The', 'quick', 'brown']
fox 4
['The', 'quick', 'brown', 'fox']
[['The', 'quick', 'brown', 'fox']]
jumped 1
['jumped']
over 2
['jumped', 'over']
the 3
['jumped', 'over', 'the']
lazy 4
['jumped', 'over', 'the', 'lazy']
[['jumped', 'over', 'the', 'lazy'], ['jumped', 'over', 'the', 'lazy']]
[[], []]

Mostly, I am confused and am wondering if there is an easier ways to do this. I am hoping to use this to break down in order to use apriori. Because of the scale of the data I am working with (1100+ set with text ~100 words)I want to break down and that is why I want a list of lists.I want to be less intensive overall.
Any help would be appreciated. Thanks.

A: You can use the range and array slice for this:
text = "The quick brown fox jumped over the lazy dog"
text = text.split()
result = []
step = 4
for i in range(0, len(text), step):
    result.append(text[i: i + step])
result
#[['The', 'quick', 'brown', 'fox'], ['jumped', 'over', 'the', 'lazy'], ['dog']]


text:
Q: Mousemove event is causing infinite loop even after mousemovement has stopped Here's the page in question: http://yac-web.com/clients/dessert/ I am trying to set up an effect that happens while the mouse is being moved and stops when it's not. For some reason the event starts fine but then just keeps looping. I am not super familiar with JS and couldn't find much info on the mousemove event. Thanks
$('html').mousemove(function () {
    $('html').toggleClass("change", 1000, "easeOutSine");
})

then
html {
    background: rgba(191, 54, 245, 1);
}
.change {
    background: rgba(61, 98, 245, 1);
}

Demo: Fiddle

A: The basic problem is when the mouse is moved you are queuing a lot of toggle classes which uses a queuing system so even after the mouse is stopped the animation will continue to run.
The solution is not to add more toggles if there is a animation in progress, try
var flag = false;
$('html').mousemove(function () {
    if (flag) {
        return;
    }
    flag = true;
    $('html').toggleClass("change1", 1000, "easeOutSine", function () {
        flag = false;
    });
})

Demo: Fiddle
Another is to use :animated selector
var $html = $('html').mousemove(function () {
    if ($html.is(':animated')) {
        return;
    }
    $('html').toggleClass("change1", 1000, "easeOutSine");
})

Demo: Fiddle

A: Arun P Johny's answer is probably the best in terms of actually solving the problem, however it doesn't go into depth as to exactly why it is happening.
This is why the problem is happening:
Each time the mouse position updates (several times a second, unless you are having serious lag; I will assume 1/16th of a second between updates), it adds a new animation to the end of the list of animations it needs to do. Then, when you stop moving your mouse, it still has a number of the animations left in the queue, which take an entire second each. It is adding a second on to the animation time every 1/16 of a second that you are moving the mouse. Thus, if you move it for one second, it will be 16 seconds after you started that the animation will stop.
This is solved by ensuring that a new animation is not added until the old one finishes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why doesn't the google maps tutorial work on my pc? So I've downloaded a sample bit of code from the google developer website to play around with. The bit of code found below is exactly the same as the code found here. When I download the html and try to open it locally in chrome it doesn't show anything, it returns me a blank screen without any errors (firebug lite). I'm using a mac and I'm new at all this web dev stuff. Should I set up a localhost thing or am I completely missing something? Any help is greatly appreciated.
  <!DOCTYPE html>

        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <title>Google Maps JavaScript API v3 Example: Circle Simple</title>
        <link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">

A: The problem is that the link element's href attribute in the head of the document uses a relative URL pointing to a stylesheet on your local machine.  Unless you've downloaded that stylesheet and put it at the location referenced in the link element's href attribute, it won't find it.
In this case though, I'd recommend that you just change it to the following so it uses the stylesheet from Google's server:
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">

A: Since you saved the file directly from the demo site, you did not save the CSS file associated with it (/maps/documentation/javascript/examples/default.css). So your map has no width/height to it. If you save this file and reference it properly it should work. Alternatively, you can just add the bit of css to your html file:
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Google Maps JavaScript API v3 Example: Circle Simple</title>


text:
Q: my form doesen't work right I made a form but it doesn't send to my email; instead, it opens Windows Live Mail.
Here is my code:
<form name="name" action="mailto:someone@example.com" method="post">
What can I do to make the form send to my email instead of opening Windows Live Mail?

A: Your code IS good. Your code does exactly what it is supposed to do. When you submit a form with  action attribute involving a mailto:, it opens up your email program to send an email to the someone@example.com address.
If you want the form to not send the email using the system's default mail program, you need to use something server-side. I don't know of any client side solutions, but who knows. There might be something out there...


text:
Q: How to add columns to a view in SQL Server 2005 I have no experience with SQL Server 2005. I've been assigned a task to modify views for adding 4 columns to the view. Is it possible to do this without the column change reflected in the table the view is referring. If I have the columns in the Table, then should I just drop the view and create a new one or is there a way to alter it.

A: If these 4 columns are calculated based on existing data then you just need to run ALTER VIEW... and add them into the query definition used by the view
ALTER VIEW dbo.foo
AS
SELECT originalcolumnlist, A+B AS col1, C+D as col2, E+F as col3, G+H as col4
FROM yourtable

You can right click the View definition in Management Studio and "Script View as -> Alter" to see the existing definition.

A: alter view TheViewName
as
select oldCol_A, oldCol_B, NEWCol_C
from someTable
go

A: You can use ALTER VIEW to achieve the result you are looking for.
This will just act as dropping the existing view and adding new columns from your new select statement. However, this is better than dropping your existing view and creating a new view because the Alter view will retain the permissions granted to users.


text:
Q: DTM data type from Int16 to Float I downloaded a data set 'SRTM Arc-Second Global' from the USGS EarthExplorer (GeoTIFF 1 Arc-second). Apparently, the DTM data type is Int16 whereas I need Float. I am trying to convert the format using the Raster -> Conversion -> Translate (Convert Format) ... dialogue in QGIS. However, if I run e.g.
gdal_translate -of GTiff
-ot Float32
-co COMPRESS=LZW (lossless compression)
 /Downloads/Tra_Vinh_.tif
 /Downloads/Tra_Vinh_float.tif

I receive the following error:

ERROR 6: Too many command options '/Downloads/Tra_Vinh_.tif'

If I use less command options, e.g.
-ot Float32
-co COMPRESS=LZW (lossless compression)
/Downloads/Tra_Vinh_.tif
/Downloads/Tra_Vinh_float.tif

or
-ot Float32
/Downloads/Tra_Vinh_.tif
/Downloads/Tra_Vinh_float.tif

It says:

The process failed to start. Either the invoked program is missing, or
  you may have insufficient permissions to invoke the program.

A: qgis uses gdal for raster conversion. if you use the raster > conversion > convert tool in QGIS, you will have a command line that fills automatically at the bottom of the form. Simply use the edit button to add

-ot Float32

on the command line and run the tool. Note that you can add other usefull option, such as:
-co COMPRESS=LZW (lossless compression)

-co TILED=yes (tiling)


text:
Q: Proper Way to Stop App While Threads Are Waiting on WaitOne() I'm playing around with AutoResetEvent and my app isn't ending, and I think I know why: the threads are still running and therefore the app won't terminate. Normally, in Main(), after I press a key, the app terminates. But the console window no longer closes. I have a simple console app:
    private static EventWaitHandle waitHandle = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        AutoResetEventFun();

        Console.WriteLine("Press any key to end.");
        Console.ReadKey();

        waitHandle.Close();  // This didn't cause the app to terminate.
        waitHandle.Dispose();  // Nor did this.
    }

    private static void AutoResetEventFun()
    {
        // Start all of our threads.
        new Thread(ThreadMethod1).Start();
        new Thread(ThreadMethod2).Start();
        new Thread(ThreadMethod3).Start();
        new Thread(ThreadMethod4).Start();

        while (Console.ReadKey().Key != ConsoleKey.X)
        {
            waitHandle.Set();  // Let one of our threads process.
        }
    }

    // There are four of these methods. Only showing this one for brevity.
    private static void ThreadMethod1()
    {
        Console.WriteLine("ThreadMethod1() waiting...");

        while (true)
        {
            waitHandle.WaitOne();
            Console.WriteLine("ThreadMethod1() continuing...");
        }
    }

What's the right way to terminate this app? Do I need to retain a reference to each thread and call Abort() on each one? Is there a way to signal waitHandle so that the threads waiting on it will terminate? (I don't think so, but I thought it would be worth asking.)

A: While I'm not entirely sure what you're trying to accomplish, one way to have this app terminate is to make all thread background threads:
private static void ThreadMethod1()
{
    Thread.CurrentThread.IsBackground = true;
    Console.WriteLine("ThreadMethod1() waiting...");

    while (true)
    {
        waitHandle.WaitOne();
        Console.WriteLine("ThreadMethod1() continuing...");
    }
}

A: Another way is to set a volatile 'Abort' boolean flag that the threads always check after returning from the WaitOne() call to see if they need to exit.  You could then set this flag and signal the WaitHandle [no. of threads] times.


text:
Q: Usage message when using argparse.REMAINDER I have a Python program that takes as its (only) positional command-line argument one or more file path expressions. I'm using argparse for the CL parsing, and argparse.REMAINDER for the variable that contains the file path(s). See code below:
import argparse
import sys

# Create parser
parser = argparse.ArgumentParser(
    description="My test program")

def parseCommandLine():
    # Add arguments
    parser.add_argument('filesIn',
                        action="store",
                        type=str,
                        nargs=argparse.REMAINDER,
                        help="input file(s)")

    # Parse arguments
    args = parser.parse_args()

    return(args)

def main():
    # Get input from command line
    args = parseCommandLine()

    # Input files
    filesIn = args.filesIn

    # Print help message and exit if filesIn is empty
    if len(filesIn) == 0:
        parser.print_help()
        sys.exit()

    # Do something
    print(filesIn)

if __name__ == "__main__":
    main()

Now, when a user runs the script without any arguments, this results in the following help message:
usage: test.py [-h] ...

Where ... represents the positional input. From a user's perspective it would be more informative if the name of the variable (filesIn) was displayed here instead. Especially because typing test.py -h results in this:
usage: test.py [-h] ...

My test program

positional arguments:
  filesIn     input file(s)

I.e. the usage line displays ... but then in the list of positional arguments filesIn is used.
So my question is whether there's some easy way to change this (i.e. always display filesIn)?

A: Don't use argparse.REMAINDER here. You are not gathering all remaining arguments, you are trying to take filenames.
Use '+' instead to capture all remaining arguments as filenames and you need at least one:
parser.add_argument('filesIn',
                    action="store",
                    type=str,
                    nargs='+',
                    help="input file(s)")

This produces better help output:
$ bin/python test.py
usage: test.py [-h] filesIn [filesIn ...]
test.py: error: too few arguments
$ bin/python test.py -h
usage: test.py [-h] filesIn [filesIn ...]

My test program

positional arguments:
  filesIn     input file(s)

optional arguments:
  -h, --help  show this help message and exit


text:
Q: Weird behavior of Apache2 ModSecurity2 I am hosting a nextcloud application on my apache2 production server on which I use modsecurity for hardening.
As modsecurity will detect many requests generated by Nextcloud as false positives, I want to enable the special modsecurity nextcloud exclusions via "tx.crs_exclusions_nextcloud=1".
Since I am hosting multiple vHosts/Subdomains on this server and nextcloud has its own one (as well as that its not an option to do such exclusions globally for every subdomain) I want to enable this exclusions via the Apache VirtualHost Config Directory:
<VirtualHost _default_:443>
    ServerName nextcloud.mydomain.tld
    ...
    SecAction "id:x,pass,log,setvar:tx.crs_exclusions_nextcloud=1" #also tried ALL possible combinations of variables (id, log, nolog, pass, ...) etc, please don't assume the issue being here as long as you don't are 100% sure.
    ...
</VirtualHost>

This does not work. And I have completely no clue why. The documentation says this command is usable in the VirtualHost section and I checked the order of the config files being included.

Order:

*

*Mod itself being loaded

*/etc/apache2/mods-enabled/security2.conf

*/etc/modsecurity/000_modsecurity.conf

*/etc/modsecurity/001_crs-setup.conf

*/etc/modsecurity/rules/*.conf | OWASP ModSecurity CRS v3.3.0         <--- Rule definition

*/etc/modsecurity/002_crs-exclusions.conf <--- Current Hotfix, see below

*Site-Configs                                                     <--- <VirtualHost>
Since the SecAction in VirtualHost does not work and modsecurity is still detecting many nextcloud requests as false positives, I currently use the last file, 002_crs-exclusions.conf, to active the nextcloud exclusions:
SecRule REQUEST_HEADERS:Host ^nextcloud.mydomain.tld$ "id:900130,phase:1,nolog,pass,t:none,setvar:tx.crs_exclusions_nextcloud=1"

which works.
Bit I am not satisfied with this solution - I want to use this via the VirtualHost directive, since this should work.

Second issue
Modsecurity blocks the request URI /remote.php/dav/calendars/<user>/personal/<uuid>.ics if a user is trying to update a calendar entry. This is due to the fact that this request has the Header Content-Type: application/xml but no real xml content, which leads modsecurity to a libxml2 parse error. So I want to exclude rule# 200000 (this rule defines that Header Content-Type: application/xml-requests should go through modsecurity's xml-parser) for the URI /remote.php/dav/calendars/.* with SecRuleRemoveById via an <Location> directive:
<Location ~ "/remote.php/dav/calendars/.*">
    Header set LocDebug "works"  #to check if <Location> is applied correctly
    SecRuleRemoveById 200000
</Location>

Result:
Every request going to one of these URIs (loading of the calendar, etc.) have the header LocDebug in them, showing that the rules in <Location ...> are applied successfully - but if the user tries to update the calendar entry (request with malformed xml), the request still fails with HTTP 500 and modsecurity reporting an parsing error - This request has NO LocDebug header, leading me to assume that there is some issue with the order of those actions and commands applied in relation to when the request is actually parsed.

I also tried setting SecRuleRemoveById globally, but this one does completely not work AT ALL.
I tried everything, literally everything and as documented above the order should be no problem.

Does anybody have any idea what I may be doing wrong or where the issue could be? I am clueless.

Technical information:

*

*OS: Debian 10 Buster - all packages newest ver.

*Apache: apache2.4.38-3+deb10u4

*ModSecurity: libapache2-mod-security2 v2.9.3-1

A: For the first issue
Your SecAction does not have phase action. In this case the mod_security2 puts the rule/action into the 2nd phase, which is too late imho.
For the second issue
I don't see the reason, why SecRuleRemoveId does not work, it shoudl work. But you can put a SecAction here too, with a ctl:ruleRemoveById=200000.


text:
Q: awk / sed script to remove text I am currently in need of a way to programmatically remove some text from Makefiles that I am dealing with. Now the problem is that (for whatever reason) the makefiles are being generated with link commands of -l<full_path_to_library>/<library_name> when they should be generated with -l<library_name>. So what I need is a script to find all occurrences of -l/ and then remove up to and including the next /.
Example of what I'm dealing with

-l/home/user/path/to/boost/lib/boost_filesystem

I need it to be

-lboost_filesystem

As could be imagined this is a stop gap measure until I fix the real problem (on the generation side) but in the meantime it would be a great help to me if this could work and I am not too good with my awk and sed.
Thanks for any help.

A: sed -i 's|-l[^ ]*/\([^/ ]*\)|-l\1|g' Makefile

A: Here you go
echo "-l/home/user/path/to/boost/lib/boost_filesystem" | awk -F"/" '{ print $1  $NF  } '


text:
Q: Python on Mac: Fink? MacPorts? Builtin? Homebrew? Binary installer? For the last few days, I have been trying to use Python for some audio development.
The thing is, Mac OSX does not handle uninstalling stuff well. Actually, there is no way to uninstall anything. Once it is on your system, you better pray that it didn't do any funny stuff. Hence, I don't really want to rely on installer packages for Python.
So I turn to Homebrew and install Python using Homebrew. Works fabulously. Using pip, Numpy, SciPy, Matplotlib were no (big) problem, either. Now I want to play audio. There is a host of different packages out there, but pip does not seem willing to install any. But, there is a binary distribution for PyGame, which I guess should work with the built-in Python.
Hence my question: What would you do? Would you just install the binary distributions and hope that they interoperate well and never need uninstalling? Would you hack your way through whichever package control management system you prefer and deal with its problems? Something else?

A: Short answer: use virtualenv
Longer answer:
1) Leave system Python as is (don't touch at all)
2) Install different versions of Python via this buildout: https://github.com/collective/buildout.python
3) Use virtualenv for every project


text:
Q: Can't interact with children of an itemRenderer in Flex 4 Gumbo I thought this would be pretty easy but I'm running into all sorts of problems with this. I have an ItemRenderer with a an image and two labels. I want to assign separate mouse events to the image and two labels. It seems like the item renderer is treated like a single interactive piece and I haven't found a way to override that. I couldn't even disable the default rollover effect so I had to style the rollOverColor to match my background.
Can anyone provide a solution?
<s:DataGroup id="browserDataGroup" dataProvider="{model.userBoardList}"
                 verticalCenter="0" left="10" rollOverColor="0x424242"
                 itemRenderer="edu.xxxxx.components.board.BrowserItemRenderer">
<!--itemrenderer code below -->
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo"
        xmlns:ns="library://ns.adobe.com/flex/mx"
        buttonMode="true" useHandCursor="true"
        mouseChildren="true">
    <s:states>
        <s:State name="up"/>
        <s:State name="over"/>
    </s:states>
    <s:layout>
    <s:VerticalLayout gap="2"/>
    </s:layout>
    <s:Group>
    <ns:Image id="image" source="{data.thumbnail}"
              addedEffect="Fade" completeEffect="Fade" removedEffect="Fade"
              width="130" height="89"
              horizontalCenter="0" verticalCenter="0"/>
    <s:Rect id="imageRect" width="130" height="89">
        <s:stroke>
            <s:SolidColorStroke color="0xFFFFFF" joints="miter" pixelHinting="true"/>
        </s:stroke>
    </s:Rect>
    </s:Group>
    <s:Label text="{data.title}" color="0xFFFFFF" fontWeight="bold"/>
    <s:Group>
        <s:layout>
        <s:HorizontalLayout gap="3"/>
        </s:layout>
        <s:Label text="Edit" color="0xFFFFFF" click="trace('edit');"
                 textDecoration.up="underline" textDecoration.over="none"/>
        <s:Label text="|" color="0xFFFFFF"/>
        <s:Label text="Delete" color="0xFFFFFF" click="trace('delete');"
                 textDecoration.up="underline" textDecoration.over="none"/>
    </s:Group>

</s:ItemRenderer>

A: Just in case this helps anyone else, turns out the solution was to use set autoDrawBackground="false" for the itemRenderer instance. That disables the drawing of the overlays. Then, I should have been using rollOver and rollOut for the individual children that I wanted to interact with. Rookie mistakes…you hate to see them.


text:
Q: Problems with my for loops printing out my arrays can anybody help me figure out why my for loops cant print the right answer out.
Its like its skipping the first array number [0]. but if i try to make it print out my Array nr [1] out it works fine.
It must be somthing with my counter ans answer at the top.
package assignment9.pkg1;

import java.util.Scanner;

/**
 *
 * @author Anders
 */
public class Assignment91 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String studName = "Anders";
        int counter = 1;// i think the problem is here
        int answer = 1; // same
        System.out.println(" welcome to student database, show informations about student" + studName);

        Scanner courseScan = new Scanner(System.in);
        Scanner gradeScan = new Scanner(System.in);
        Scanner answerScan = new Scanner(System.in);

        System.out.println(" Enter the name of courses");

        String[] courseArray = new String[counter];
        int[] gradeArray = new int[counter];

        for (int k = 0; k <= counter; k++) {

            if (counter < 20) {

                while (answer != 0) {  // what have i done here with that 0 answer??

                    System.out.println(" enter name");
                    courseArray[k] = courseScan.nextLine();
                    System.out.println(" Enter grade");
                    gradeArray[k] = gradeScan.nextInt();
                    System.out.println(" Do you want to add one more course enter 1, if not enter 0");
                    answer = answerScan.nextInt();

                }
            } else {

                System.out.println("Sorry, there is no more memory");

            }
        }

        int n = gradeArray.length;
        int temp = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 1; j < (n - i); j++) {

                if (gradeArray[j - 1] > gradeArray[j]) {
                    //swap the elements!
                    temp = gradeArray[j - 1];
                    gradeArray[j - 1] = gradeArray[j];
                    gradeArray[j] = temp;

                    // Swap the course array
                    String gradeArrayTemp;

                    gradeArrayTemp = courseArray[j - 1];
                    courseArray[j - 1] = courseArray[j];
                    courseArray[j] = gradeArrayTemp;

                }

            }

        }

        for (int l = 0; l < courseArray.length; l++) {

            System.out.println("grade " + gradeArray[l] + "name " + courseArray[l]); // why does it not print all the array out
        }

        Scanner request = new Scanner(System.in);

        System.out.println(" what do you want to do. Enter 1 to rename a course");
        System.out.println(" enter 2 to change a grade ");
        int regNumber = request.nextInt();
        switch (regNumber) {

            case 1: // rename a course

                Scanner search = new Scanner(System.in);
                System.out.println("Enter the name of the course you want to rename");
                String searchCourse = search.nextLine();

                for (int i = 0; i < courseArray.length; i++) {
                    if (searchCourse.equals(courseArray[i])) {

                        System.out.println("Yes there is a course named " + courseArray[i]);
                        System.out.println(" to change coursename insert new name");
                        // here i change the coursename
                        Scanner newName = new Scanner(System.in);
                        courseArray[i] = newName.nextLine();

                    } else {

                        System.out.println(" no record of this course");

                    }

                    System.out.println(" you have chosen to rename course into " + courseArray[i]);

                }

        }
    }
}

A: In this section of the code:
 for (int k = 0; k <= counter; k++) {

            if (counter < 20) {

                while (answer != 0) {  // what have i done here with that 0 answer??

                    System.out.println(" enter name");
                    courseArray[k] = courseScan.nextLine();
                    System.out.println(" Enter grade");
                    gradeArray[k] = gradeScan.nextInt();
                    System.out.println(" Do you want to add one more course enter 1, if not enter 0");
                    answer = answerScan.nextInt();

                }
            } else {

                System.out.println("Sorry, there is no more memory");

            }
        }

note that you have used k to insert into array. the k do not update because is stuck in the inner while loop There for use another counter.
Also here
String[] courseArray = new String[counter];
you use counter to create the array. Which is 1. You are creating one eliment array.
You code will work like this:
 int k = 0;

            if (counter < 20) {

                while (answer != 0) {  // what have i done here with that 0 answer??

                    System.out.println(" enter name");
                    courseArray[k] = courseScan.nextLine();
                    System.out.println(" Enter grade");
                    gradeArray[k] = gradeScan.nextInt();
                    System.out.println(" Do you want to add one more course enter 1, if not enter 0");
                    answer = answerScan.nextInt();
                    k++;
                }
            } else {

                System.out.println("Sorry, there is no more memory");

            }

And
for (int i = 0; i < courseArray.length; i++) {
            if(courseArray[i] != null)
            System.out.println("grade " + gradeArray[i] + "name " + courseArray[i]); // why does it not print all the array out
        }

I have assumed that you take only 20 records depending on the loop. So i initiated arrays
 String[] courseArray = new String[20];
        int[] gradeArray = new int[20];


text:
Q: Почему не работает android:theme для TextInputLayout в android 4.4? Почему-то не работает android:theme для TextInputLayout в версии android 4.4.
 <android.support.design.widget.TextInputLayout
                    android:id="@+id/text_input_project_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/Name_project"
                    android:theme="@style/EditTextInputAddContactProject">

                    <EditText
                        android:id="@+id/name_project_create"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:inputType="textMultiLine"
                        android:text="sdsd"
                        android:textColorHint="@color/color_gray_text"
                        app:backgroundTint="@color/color_gray_text"
                        android:backgroundTint="@color/color_gray_text"
                        android:textIsSelectable="false" />
                </android.support.design.widget.TextInputLayout>

Вот стиль, который использую
<style name="EditTextInputAddContactProject">
    <item name="colorPrimary">#ff0400</item>
    <item name="colorPrimaryDark">#00ff04</item>
    <item name="colorAccent">#0055ff</item>
    <item name="colorControlHighlight">#ff0400</item>
    <item name="android:textColorHint">#ffea00</item>
    <item name="android:cacheColorHint">#00ff04</item>
    <item name="android:textSize">20sp</item>
    <item name="colorControlNormal">#00ff04</item>
    <item name="colorControlActivated">#00ff04</item>
    <item name="android:textColorHighlight">#ff0400</item>
    <item name="android:textColorLink">#ff0400</item>
    <item name="android:textColorSecondary">#ff0400</item>
</style>

Уточнение:
Есть глобальный стиль, который подключается в манифесте и если разметку layout(в котором проблема, описанная выше) использовать в activity, то проблема остаётся, а если этот же layout использовать в фрагменте, то проблемы нет.
Стиль:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/white</item>
    <item name="android:textColorSecondary">@color/white</item>
    <item name="colorControlHighlight">#277dd3</item>
</style>

Манифест:
 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:name=".utils.App"
    android:theme="@style/AppTheme"> <!-- Глобальный стиль-->

В чём проблема и как устранить?
Для проверки использую эмулятор.


text:
Q: Amplification without transistors or tubes? Are there any means or technologies that can be used to linearly (or close to linear) amplify an audio or LF RF electrical signal that do not require transistors or vacuum tube technologies?  (Or equivalent tech such as ICs, photo-transistors, klystrons, etc.)
Specifically linear (or "close enough" as are the usual slightly non-linear simple tube or transistor amp circuits), so disqualifying a two state relay as a possible solution.
Were any electromechanical gadgets tried before Fleming and De Forest?

A: Negative-resistance devices such as tunnel diodes can be used as amplifiers/oscillators.
There are also magnetic amplifiers, most often used for electromechanical control.
A relay has gain, but it's highly nonlinear.
Are these the sorts of things you're looking for?

A: A generator without permanent magnets can be used as a amplifier.  The extra power comes from the power provided by mechanically rotating the shaft.  The magnitude of the output signal is then proportional to the shaft rotation speed and the field winding current.  Since extra power is being added to the system via the shaft, you can get more power out than you put into the field windings.  If you keep the shaft rotating at a fixed speed, the generator can be thought of as a amplifier from the field current to the output.
One problem with this is that these generators usually put out AC.  That can be rectified, but will still have some ripple.  If you wind the generator with enough poles and spin it fast enough, the AC output frequency can be higher than your highest frequency of interest.  In that case, it can be AM demodulated to yield the final amplified signal.
Rigging up something like this to work at audio frequencies will be tricky.  However, you can demonstrate the concept without too much trouble at lower frequencies.  Connect a LEB (light emitting bulb) to the output of the generator and spin it to get typical line frequency out, like 60 Hz.  Now you can control the lightbulb, or a bank of lightbulbs, with much less power than it takes to drive them directly.
The alternator in your car actually works on this principle to keep the rectified output of the alternator at the right voltage.  The alternator spins at whatever speed it spins at.  The control system modulates the field current so that the alternator output produces the right voltage to keep the battery charged but to not overcharge it.  In this case the "amplifier" is being used as a voltage regulator, but the overall concept is the same.  Less power is required to run the alternator field windings, which comes from the 12 V DC, than the alternator puts back onto the 12 V DC line.  The extra power comes from adding a mechanical load on the engine.

A: A pure mechanical audio amplifier called an auxetophone uses an air compressor and a gate that is mechanically modulated.  This video shows a recreation of an auxetophone where a solenoid is used to move the gate, but it can be mechanically moved.
In a similar manner, the gate could be replaced with an adjustable power resistor, so you can build a mechanical amplifier that converts the small signal to mechanical movement, which then modulates a much larger power source.

A: A transformer can provide gain i.e. a "step-up" transformer can magnify the input voltage by the turns ratio but it isn't a power amplifier. They can be fairly linear.
A tuned circuit (L & C) can also amplify a voltage signal by many times but it is limited to a small band of frequencies close to the resonant point. Beyond that frequency signal output levels fall off.

A: Parametric amplifiers can be made with nonlinear capacitors.
In the early days of radio, a device called the coherer was used.. It could be described as a detector with gain. Not linear at all.

There were various devices in the early history of instrumentation that provided something like gain without actual power gain. For example, the optical lever, the galvanometer, the thermopile.

A: An audio transducer (e.g., speaker) can be coupled to a microphone to provide gain in the audio frequency spectrum. This technique was used in early long distance telephony.

A: Here's a schematic of an amp purely only using capacitors:

From https://www.eevblog.com/forum/beginners/tested-capacitor-amplifier/


text:
Q: Fix a div after scrolling in mobile browsers I want to fix a div during scrolling of the page. My code works in desktop browsers but it is not working in mobile devices where the div is fixed only when the scroll bar stops.
You can test the page here www.spiaggiati.it/antani/.
The code is:
function fixDiv() {
var $div = $("#order");
if ($(window).scrollTop() > $div.data("top")) {
    $div.css({'position': 'fixed', 'top': '-10px', 'width': $('div#content').width()});
    $('#categories').css('margin-top', '50px');
}
else {
    $div.css({'position': 'static', 'top': 'auto'});
    $('#categories').css('margin-top', '0px');
}
}

A: I assume fixDiv() is fired constantly using the scroll-event.
If so then there's no solution at the moment as this is how scrolling on mobile devices works. The scroll event is triggered only when the scrolling has come to an end. As long as the momentum is moving the content no events are fired at all. You can see this in Figure 6-1 The panning gesture in Apple's "Safari Web Content Guide".


text:
Q: excel 2010 vba pivot table report filter update I have 16 pivot tables on the same sheet, "Analytics Admin", I recorded and cleaned up the macro below (the code right before updates the info the pivot tables source). It's basically the same code 16 times, the only thing that changes is the pivot table name ( MSP, MSP30, FSP, FSP30, etc). Is it possible to change the report filter for all the pivot tables at once?
Worksheets("Analytics Admin").Activate

'refreshes all data, clears all filters then filters 0 and blanks out of all custom range pareto pivot tables

ActiveSheet.PivotTables("MSP").PivotCache.Refresh
    ActiveSheet.PivotTables("MSP").PivotFields("count").ClearAllFilters
    ActiveSheet.PivotTables("MSP").PivotFields("count").ShowAllItems = True

    With ActiveSheet.PivotTables("MSP").PivotFields("count")
        .PivotItems("0").Visible = False
        .PivotItems("(blank)").Visible = False
    End With
    ActiveSheet.PivotTables("MSP").PivotCache.Refresh

ActiveSheet.PivotTables("FSP").PivotCache.Refresh
    ActiveSheet.PivotTables("FSP").PivotFields("count").ClearAllFilters
    ActiveSheet.PivotTables("FSP").PivotFields("count").ShowAllItems = True

    With ActiveSheet.PivotTables("FSP").PivotFields("count")
        .PivotItems("0").Visible = False
        .PivotItems("(blank)").Visible = False
    End With
    ActiveSheet.PivotTables("FSP").PivotCache.Refresh

A: Something along the lines of (not tested, just typed into here)
    dim ws as Worksheet
    set ws = ThisWorkbook.Worksheets("Analytics Admin")
    dim pt as PivotTable
        For Each pt In ws.PivotTables
'            Debug.Print Pivot.Name
            pt.PivotFields("count").ClearAllFilters
            pt.PivotFields("count").ShowAllItems = True

            With pt.PivotFields("count")
              .PivotItems("0").Visible = False
              .PivotItems("(blank)").Visible = False
            End With
            pt.PivotCache.Refresh
            pt.refreshTable
            pt.Update
        Next

A: If you have Excel 2010 or later, and most (hopefully all) of these Pivots share the exact same data source, you can do this with little or no looping. Simply set up a Slicer on the "count" field and then connect it to all the PivotTables (right click on the Slicer, and select "Report Connections". Then you only need to run the code on one of those PivotTables, and all the others will update automatically.
You can hide the Slicer somewhere if you don't want users to click it.


text:
Q: need a regex to parse a csv file with double quotes in php Trying to parse a csv file that has all the data wrapped in double quotes, because there may be commas in the double quotes.
Looks like this:
$songs = '"1, 2, 3, 4 (I Love You)","Plain White T's","CBE10-22",15,"CBE10-22","","","CB",984,"","10/05/10"';

$regResult = preg_match( "", $songs, $matches );

I can't figure out a regex that will return the data between the quotes as the matches.  I'm sure there is some regex master that can help me with this.

A: you dont need no stinkin regex to parse a csv file in php.
see fgetcsv() and str_getcsv()


text:
Q: How to replicate a Visual Tree without using XamlReader? I've got a Visual Tree that I want to replicate. Since DependencyObjects cannot be (and should NOT be) cloned, I would like to know a good way to generate another tree based on it, preserving the structure and copying all the properties of each node (or remapping if necessary).
How could I do it?
EDIT: I cannot use DataTemplates. In fact, this question is because I have to re-implement them in an Open Source Project that intends to be a cross-platform WPF.


text:
Q: How to include externally loaded script to all bundles created by React.lazy? I wanted divide my project into two bundles. Here's my simplified App.js
import React, { Suspense, useState, useEffect, useRef } from 'react';
import loadGif from './images/731.gif';

const HospitalDashboard = React.lazy(() => import('./HospitalDashboard'));
const OperatorDashboard = React.lazy(() => import('./OperatorDashboard'));

function App () {

    const [credentials, setCredentials] = useState(null);

    return (
        <Suspense fallback={}>
            {credentials.role == 'operator' ?
                <OperatorDashboard/> :
                <HospitalDashboard/>}
        </Suspense>
    );
}

export default App;

and here's my simplified index.html
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
    <title>Dashboard</title>

Both in OperatorDashboard and HospitalDashboard I am using daterangepicker followingly:
import $ from 'jquery';
...
useEffect(()=>{
    $('#datePicker').daterangepicker(initOptions,onCallback)
},[])

In HospitalDashboard everything works fine but in OperatorDashboard I am getting this error:
jquery__WEBPACK_IMPORTED_MODULE_1___default(...)(...).daterangepicker is not a function
It is somehow related to React.lazy and bundles but I don't know how to solve it. If I use ordinary import without React.lazy, everything works fine again. Thanks for help!


text:
Q: Why is my ListViewItem not deleting? I have some code that lets the user add a day (each day is a ListViewItem), and the day is sent to a custom adapter with a delete button. In the adapter , I call an event when the delete button is clicked. The first item I delete deletes with no problem, but for the next one I get a NullReferenceException. Im suspecting it has to do with an incorrect index or something.
This snippet is from the fragment. It recieves the event sent from the adapter. The first item I delete deletes like It's supposed to, but it's the only one.
        Adapter1.OnDayDeleted += (o,e) =>
        {
            Day day = e.Day;
            DM.ListOfDays.Remove(day);
            Adapter1.NotifyDataSetChanged();
            Adapter1 = new Adapters.DayObject(Activity, DM.ListOfDays);
            ListViewDays.Adapter = Adapter1;

            Helpers.Common.SetListViewHeightBasedOnChildren(ListViewDays);

        };

This snippet is from the adapter. It sends an event back to the fragment.
        Button buttonRemoveDay = row.FindViewById<Button>(Resource.Id.buttonRemoveDay);
        buttonRemoveDay.Click += delegate
        {
            var day = myItems[position];

            //Console.WriteLine(day.Name);
            OnDayDeleted.Invoke(this, new OnDayDeletedEventArgs(day));
        };

A: I found out why. Just remove the line
Adapter1 = new Adapters.DayObject(Activity, DM.ListOfDays);


text:
Q: Plotting specific variables from a tibble I am hoping to make a plot from a large tibble, which only contains specific terms. Specifically, I have a column titled "media" where there are 7 types of media. I want to plot only the media types that contain "SW" (I have both DW and DW75). I was able to plot each media individually as well as all media together, but not calling specific terms from the media column.
Each unique chemical listed under "chem" should be its own plot. This is the script I used to plot the combined plots.
PlotChem<-function(MatrixDataCompiled){
  ggplot(data=MatrixDataCompiled,aes(x=LogConc, color = Media))+
    theme_bw()+
    geom_point(aes(y = LogArea))+
    geom_smooth(aes(y = LogArea), method = lm, se = TRUE)+
    ggtitle(paste("Calibration curve for",MatrixDataCompiled$Chem[1]))
}

for(i in unique(MatrixDataCompiled$Chem)){
  ChemDataComplied<-MatrixDataCompiled[MatrixDataCompiled$Chem==i,]
  loglm75<-lm(data=ChemDataComplied,LogArea~LogConc)
  PlotChem(ChemDataComplied)
  ggsave(PlotChem(ChemDataComplied),filename=paste(ChemDataComplied$Chem[1],"Chemical Cal Curve.png"))
}
``

A: This sample of the dataset only has one chemical (FOSA), so this output may not be exactly what you're looking for. It should produce one facet (individual chart) for each chemical in 'Chem'. I didn't see any DW75 in this chunk of the data so I am filtering for STD, just to demonstrate this one approach more clearly. You can substitute DW75 or other specific media from your full data set of course.
df %>%
  filter(Media == "DW" | Media == "STD") %>%
  ggplot(aes(LogConc, LogArea, color = Media)) +
  theme_bw() +
  geom_point() +
  geom_smooth(method = lm, se = TRUE) +
  facet_wrap(. ~ Chem)

A: You can also use facet_grid() to get a matrix of the combinations of Chem and Media without the need for the separate plot titles.
df %>%
    dplyr::filter(Media %in% c("DW", "DW75")) %>%
    ggplot(., aes(x=LogConc, color = Media)) +
        theme_bw() +
        geom_point(aes(y = LogArea)) +
        geom_smooth(
            aes(y = LogArea), method = lm, se = TRUE, formula = "y~x"
        ) +
        facet_grid(Media~Chem)


text:
Q: Mysql date function in QueryDSL Here is my sql
select count(*) date(date) as pub_date from table group by pub_date;

DateExpression do not have a function to get date only. The date column in table is DATETIME, I just want to group by DATE only, but how in querydsl ?
EIDT
Done by DateTemplate.create(Date.class, "date({0})", $.date)

A: you have to use SQLExpressions::date. The resulting expression can be used as a parameter to the groupBy or other methods of a com.querydsl.sql.SQLQuery.
import com.querydsl.sql.SQLExpressions;
SQLExpressions.date(QTable.table.date)

A: For date only need to cast it in group by as below,
Try ;
 select count(date), date as pub_date from table group by CAST(date AS DATE);

A: try
to_date(date, 'yyyy-mm-dd')

with the second parameter being whatever format you need.


text:
Q: Can Android App shortcut on new process (after killing app from background) first go to splash screen and then to desired activity I made four dynamic app shortcuts. When starting the app, on splash screen I have some task to be initialized from server and after that app is starting to show real screen for user. When i go back to home screen and enter app via shortcut it works as expected bcs splash screen made its init calls. When i kill app from background list and go to enter app again via shortcut it sends me to desired activity but the only problem is bcs of the logic in code, when there is a new process (and there is bcs app is killed from background) the app is first send to splash screen to make init call. Bcs of that app shortcut is not sent to desired activity. Is there a way on new process to send app shortcut first to splash and then to desired activity.

A: I solved the problem just by sending shortcut intent first to splashscreen to make init calls from server and then after init is made further to desired activity.


text:
Q: sort the results from `apt-cache search ` Is there a way to sort the results from apt-cache search <keywords>?

A: Pipe the result to sort:
apt-cache search keyword | sort

The vertical bar is called pipe. It takes the output from apt-cache and transfers it to the input of sort.

A: You can pipe the output of apt-cache search to popsort.py (see footnotes) which sorts it in the increasing order of popularity and displays a popularity rank at the beginning.
For example, a typical apt-cache search run might look as
$ apt-cache search sqlite browser
alice - Web browser (WebKit or Gecko) based IRC client
gtkcookie - editor for cookie files
hoteldruid - web-based property management system for hotels or B&Bs
nova-consoleauth - OpenStack Compute - Console Authenticator
ruby-http-cookie - Ruby library to handle HTTP Cookies based on RFC 6265
sqlitebrowser - GUI editor for SQLite databases

If the output is piped to popsort.py
$ apt-cache search sqlite browser | popsort.py
66341 hoteldruid - web-based property management system for hotels or B&Bs
58787 nova-consoleauth - OpenStack Compute - Console Authenticator
43444 alice - Web browser (WebKit or Gecko) based IRC client
36506 gtkcookie - editor for cookie files
8052 ruby-http-cookie - Ruby library to handle HTTP Cookies based on RFC 6265
7114 sqlitebrowser - GUI editor for SQLite databases

which shows that sqlitebrowser, ruby-http-cookie are popular by an order of magnitude compared to others.
Footnotes

*

*popsort.py is a python script I wrote. It requires Python3. The latest version can be found here or just
wget https://gitlab.com/d3k2mk7/rutils/raw/master/bin/popsort.py

*Latest documentation

*The script gets the popularity rankings from popcon.debian.org/by_inst which is good enough for Debian users. You may have to edit it accordingly for Ubuntu.

*I had to break the URLs since the website does not allow new users to post URLs unless they have 10 reputation points (which I do not!).


text:
Q: Change magento theme I want to change theme in magento 2. The problem is that the client dont want the website to go down for 3 days so I have time to fix the new design and add clients images and information.
If I build the site in subdomain how can I move it to root folder and after that connect the database of the old site without losing any data or do something wrong?
I didn't try anything. I am new to magento so I cant figure out what to do

A: I suggest you to setup git on your project.
Here is an explanation of how to setup git in an existing project
Add Magento Existing project to Github repository
When you are finished and the project is in a repo.
Clone the repo to your local environment, also take a database dump from the server and setup the project in the local environment.
And finally you can work and test your code independently without affecting production and when you have finished, with the help of git you can easily transfer to the production instance


text:
Q: Which value changed in Child_changed firebase My function is listening if any value of users is changing. But I want it to be more specific to trigger only if specific value is changed.
For example, I want it to trigger if only phone is changed (do not trigger if anything except phone is changed).
Current code is below:
var usersref = firebase.database().ref('users');
usersref.on("child_changed", function(snapshot) {
   var userid = snapshot.key;
   var user = snapshot.val();
   console.log("The updated user name is " + user.name);
});

If phone of user is changed, it should trigger. How do I do it?

A: You could create another root node called /user-phones, and update the corresponding user's phone number there and in their profile, or you could use Cloud Functions to fan-out the changes made to /users/$uid/phone to /user-phones/$uid/phone automatically.
Now instead of listening for child_changed on /users, you listen to /user-phones which will only trigger when a user changes their phone number.


text:
Q: how to accessing sqlite database from java class I have created sqlite database using phonegap.
I am able to access that databse within the javascript.
But I want access that sqlitedatabase from java class. It is possible?

A: I don't know about PhoneGap compatibility, but, as far as Android, WebView control and JavaScript is concern, you do have a solution.
You should consider using WebView's addJavascriptInterface.. This will expose any of your Java objects as a JavaScript object. So, you could create a class that encapsulate the SQLite functionality you want expose and sent it through.

A: For PhoneGap --SQLite  you can use Pluggin available on GIT HUB.
there is javafile also.please check out the link:Sqlite Database

A: As said above in the answer by BicycleDude. U need to create a class and expose it and use it inside javascript.
http://groups.google.com/group/phonegap/browse_thread/thread/eb9c4a350482f86f
This link contains the reference to make toast inside javascript.U can use this similarly to access database.One problem is how u handle the returned cursor.may be u can use JSON


text:
Q: How to solve the problem of my screen being pushed due to the keyboard generated by the android phone? I encountered a layout error caused by a mobile phone!
I have a page that is a form, and the settings are like this!
When the user uses an android phone, the phone keyboard will pop up when entering the name. At this time, the entire screen will be pushed up by the keyboard and cannot be pulled down for the user to continue filling in. However, it is normal on an iOS phone, because the iOS phone keyboard will Covering my screen will not cause screen pushing. I don't know if anyone has solved this problem. I have seen some javascript solutions on the Internet. Can I solve the problem through CSS?
If this problem still requires javascript, I hope you can tell me some simple ways, because my javascript ability is a bit poor, thank you for your help!

.demo{
  background-color: #f9cf5a;
  position:fixed;
  top:0;
  bottom:0;
  left:0;
  right:0;
  display: flex;
  justify-content:center;
  align-items:center;
}

.form{
  background-color: #0ecaf9;
  width: 400px;
  height: 500px;
  border-radius:70px 180px 90px 80px;
}

.content{
  height: 100%;
  display: flex;
  flex-direction:column;
  justify-content:center;
  align-items:center;
}

        name:
        <input type="email" placeholder="name" >

        phone:
        <input type="tel" placeholder="name" >


text:
Q: Conditional Statement with Decision variables and Multiple relations This is from CPLEX.
I tried doing this but getting no results. Basically my model need a forall statement with these two conditions using decision variables and multiple relations under that. All the equality constraints. Can anyone explain what is the problem in my syntax.
Error : Function operator<(dvar float+,float) not available in context CPLEX.
Some of the screenshots and actual equation from the document is provided alongwith the problem.
Regards,
Debtirthaenter image description here
// code from the model.
enter image description here
 forall (a in A, j in Ji[a], n in N: j==jbreak)
     {Ts[a][j][n] < tbreak && Tf[a][j][n] > tbreak} => (yvr1[j][n] == yv[j][n]);// && wvr1[a][n] == wv[a][n] && Balr1[a][j][n] == Bal[a][j][n] && Tsr1[a][j][n] == Ts[a][j][n] &&Tfr1[a][j][n] == Tf[a][j][n]);

     forall (b in B: b==jbreak,i in Ij[b], n in N) ctTBRD[i][b][n]:
     Tsr1[i][b][n] >= tbreak + tmaint;

    }

A: strict inequality is not allowed so can you change
Tf[a][j][n] > tbreak

into
Tf[a][j][n] >= tbreak+1

?

A: Expanding on Alex's answer: the problem is indeed that strict inequality is not supported. However, Alex's solution will only work if tbreak is an integer variable. According to your error message, tbreak is a float+ variable, though. So the fix should be something like this:
Ts[a][j][n] <= tbreak - eps

where eps is a small constant, like 1e-6.
However, working with these tolerances is always a bit shaky, so you may want to double-check whether you can get around this. For example, by making tbreak an integer variable or by reverting the condition so that a strict less-than becomes a greater-than-or-equal (not sure this can be done but it is worth thinking about).


text:
Q: Rails 3: Add roles to a user I'm using cancan as my authorization engine.
I already have the roles in user:
  ROLES = %w[admin normal author corp]

I also have methods to add and check roles:
#cancan
  def roles=(roles)
    self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
  end

  def roles
    ROLES.reject do |r|
      ((roles_mask || 0) & 2**ROLES.index(r)).zero?
    end
  end

  def is?(role)
    roles.include?(role.to_s)
  end

And I have #  roles_mask           :integer in the User model.
However, I want to have a after_save :add_normal_role which assigns the normal role to the user.
Basically, I'm not being able (don't know) how to assign roles to each user.
This is what I have, which doesn't work:
private

  def add_normal_role
    self.roles=(ROLES[1])
  end

Thanks

A: You should try using a before_create callback ensuring the user has a normal role.
The problem with your current callback is since it's an after_save, your modifications aren't saved by default. (Saving in an after_save callback is a bad idea leading to infinite loops...) You could also use a before_save callback (with the same code you already have), which will also work.
However, since you really only need to add a normal role when the object is created (and not on every update), a before_create is better suited.


text:
Q: Best way of storing user notifications? Say on a link-sharing site people can share links and post comments. Users following a link need to be notified when comments are posted there. Users following a category need to be notified when links are shared in that category. What would be the best way to store these notifications?
I could store them individually, in which case fetching them would be simple, but every time a link is posted I'd have to add a notification for each of, say, 10,000 people following that category.
I could also just calculate the notifications each time, in which case I would count the number of new comments since the last time a user logged in and display that. However, then I wouldn't be able to save old notifications.
What are my options?

Okay, here's my database schema:
comments
 - id
 - user
 - link
 - content

links
 - id
 - user
 - content

subscriptions
 - id
 - user
 - link

Every time a new comment is made on a link, all users who are subscribed to that link should have a "notification" that they will receive on their next login.

A: Notifications are usually a highly read object, so you want to be able to get the list of currently unread notifications very quickly, not try and calculate on the fly.  Also, trying to compare against login times does not make for a good user experience.  If the user doesn't notice them initially, or refreshes the page, or clicks on one to view its details all the notifications are gone.
With that in mind, I would suggest having a user_notification table with a read/unread column in it.  While it's good to know where in your program scalablity could be an issue, it won't be until you're well underway (millions of records).  You can index the user column to increase speed, and if you ever do have the need, you can partition by user to help scale across drives/servers.
It's up to you to decide if you want to have notifications be in a separate table, or just part of the users_notifications table and that would be another area to optimize around.

A: Just keep track of the last time they viewed the notifications. Then any posts they subscribe to that were created after that time will be in the notifications for next time they view notifications.


text:
Q: Connecting 3 monitors to stationary Windows PC I am using:

*

*CPU: i5 4460

*ram: 16gb ddr3

*GPU: r9 270x

I would like to connect my PC to 3 displays simultaneously, 2 LG PC monitors and a Toshiba LCD TV. Currently, I am only able to connect 2 displays simultaneously: if I turn off the TV, the 2 monitors work and if I unplug one of the monitors the second monitor and the TV will work. When I connect all 3 monitors at the same time, my PC just ignores one of the monitors. I tried using a combination of VGA, DVI, and HDMI to connect and one using 2 DVI and HDMI, all with the same effect. Is it possible to get all monitors working at the same time?


text:
Q: why the printf statement is executed once inside the for loop while its indentation match the for loop indentation? Consider the following code:
int main()
{
   char a[100]="axc axb cxa";
    int i,j=0;
    while (a[j]!='\0')
        j++;

    for(i=j;i>=0;i--)
        if(a[i]=='\0' || a[j]==' ')
    printf("%d\n%c",i,a[i-1]-32);

    return 0;
}

In the above code, my understanding says the printf will be executed after completing the for loop and the value of i will be '-1'. According to output, the value of i is 11. But why? Can anyone please explain?


text:
Q: Including Helper Functions in Separate JS File (Client-Side) First off, I know this is probably pretty low-level for the most part, I'm sorry for not really trying anything before asking this.
What methods would you guys suggest for including helper functions in separate files?  I'm used to node.js's module interface for doing this, but I'm not 100% on how to achieve similar functionality client-side.
Small example of what I'd like to abstract into its own file:
var helpers = (function() {
  var _helpers = {};

  _helpers.buildDateFromDelta = function(delta) {
    date = new Date();
    date.setDate(date.getDate() - delta);
    date.setHours(0, 0, 0, 0);

    return date;
  };

  return _helpers;
})();

A: The way I had my helper functions coded were already set up in such a way I could include them in a separate file easily.
HTML
<script src="/javascript/helper.js" type="text/javascript">
<script src="/javascript/file-using-helpers.js" type="text/javascript">

helper.js
var helpers = (function() {
  var _helpers = {};

  _helpers.buildDateFromDelta = function(delta) {
    date = new Date();
    date.setDate(date.getDate() - delta);
    date.setHours(0, 0, 0, 0);

    return date;
  };

  return _helpers;
})();

file-using-helpers.js
var date = helpers.buildDateFromDelta(0);
console.log(date.getFullYear());  // Works

var otherIIFEExample = (function(lib) {
  console.log(lib.buildDateFromdelta(0).getFullYear());
})(helpers);

This works because when declaring the helper variable, it was set on the global scope (I'm assuming).  Other top-scoped files included after that file are able to use that variable as well.

A: Not sure if this is what you're looking for but, this is what I would do (This is assuming you're running this on a HTML page)
var s = document.createElement("script");
s.src = "external.js";
document.getElementsByTagName("head")[0].appendChild(s);

This code goes in the main js file.
Hope that helps!


text:
Q: Remove Windows 7 windows decorations (non-client area) I would like to remove the border of the windows.
I want to have all windows without their window decorations, just the content (like using a theme without borders).
I know that then I wouldn't be able to resize any window by dragging its border, but that's fine. I just want the border to be gone.
It would be also great to remove the title bar if possible.
As a note, I'm not writing an application where I need a custom UI for its windows, but I'm opened to write any kind of program if necessary.
Any help would be appreciated.
edit: all newly created windows should start without titlebar and borders.


text:
Q: Neural net with non standard input I want to make a neural net which takes image+image+value as an input and performs convolution+pooling on images and then a linear transform on results. Can I do that in keras?

A: Suppose your image is RGB type, the shape of the image is (width,height,3), you can combine two images with numpy like:
    import numpy as np
    from PIL import Image

    img1 = Image.open('image1.jpg')
    img2 = Image.open('imgae2.jpg')

    img1 = img1.resize((width,height))
    img2 = img2.resize((width,height))

    img1_arr = np.asarray(img1,dtype='int32')
    img2_arr = np.asarray(img2,dtype='int32')

    #shape of img_arr is (width,height,6)
    img_arr = np.concatenate((img1_arr,img2_arr),axis=2)

Combine two images in this way, we only increase the channels, so we can still do convolution on the first two axis.
UPDATE:
I guess you mean Multi-Task Model, you want to merge two images after convolution,Keras has concatenate() can do that.
    input_tensor = Input(shape=(channels, img_width, img_height))
    # Task1 on image1
    conv_model1 = VGG16(input_tensor=input_tensor, weights=None, include_top=False, classes=classes,
                  input_shape=(channels, img_width, img_height))
    conv_output1 = conv_model1.output
    flatten1 = Flatten()(conv_output1)
    # Task2 on image2
    conv_model2 = VGG16(input_tensor=input_tensor, weights=None, include_top=False, classes=classes,
                  input_shape=(channels, img_width, img_height))
    conv_output2 = conv_model2.output
    flatten2 = Flatten()(conv_output2)
    # Merge the output
    merged = concatenate([conv_output1, conv_output2], axis=1)
    merged = Dense(classes,activation='softmax')(merged)

    # add some Dense layers and Dropout,
    final_model = Model(inputs=[input_tensor,input_tensor],outputs=merged)

A: This is architecturally similar to Craig Li's answer but is in the image, image, value format and does not use VGG16 and just a vanilla CNN. These are 3 separate networks whose outputs are concatenated after being processed individually and the resulting concatenated vector is passed through the final layers, including information from all inputs.
input_1 = Input(data_1.shape[1:], name = 'input_1')
conv_branch_1 = Conv2D(filters, (kernel_size, kernel_size),
                 activation = LeakyReLU())(conv_branch_1)
conv_branch_1 = MaxPooling2D(pool_size = (2,2))(conv_branch_1)
conv_branch_1 = Flatten()(conv_branch_1)

input_2 = Input(data_2.shape[1:], name = 'input_2')
conv_branch_2 = Conv2D(filters, (kernel_size, kernel_size),
                 activation = LeakyReLU())(conv_branch_2)
conv_branch_2 = MaxPooling2D(pool_size = (2,2))(conv_branch_2)
conv_branch_2 = Flatten()(conv_branch_2)

value_input = Input(value_data.shape[1:], name = 'value_input')
fc_branch = Dense(80, activation=LeakyReLU())(value_input)

merged_branches = concatenate([conv_branch_1, conv_branch_2, fc_branch])
merged_branches = Dense(60, activation=LeakyReLU())(merged_branches)
merged_branches = Dropout(0.25)(merged_branches)
merged_branches = Dense(30, activation=LeakyReLU())(merged_branches)

merged_branches = Dense(1, activation='sigmoid')(merged_branches)

model = Model(inputs=[input_1, input_2, value_input], outputs=[merged_branches])

#if binary classification do this otherwise whatever loss you need

model.compile(loss='binary_crossentropy')


text:
Q: Weird black line on top of list view I am creating a layout with a ListView and at the very top of the list there is this weird black line that I can't seem to figure out how to get rid of!  It's part of the ListView because it moves up and down as I size the ListView.  Has anyone ran into this before?

I couldn't get DDMS to take a screen capture for some reason so I took a picture of the screen with my G1, so please forgive the quality!  As you can see the line is there at the top of the fade out in the list.
alt text http://dl.dropbox.com/u/3618586/2010-05-07%2014.25.50.jpg

A: The problem is not the divider.
I was also looking for a solution to this and I found one :
You can do your own theme with this
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Theme" parent="android:Theme">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

</resources>

And setting the theme to your manifest xml file and it works.
The windowContentOverlay to null fix the problem.

A: if you specify attribute dividerHeight in ListView
<ListView
     android:dividerHeight="0.0px"
     android:id="@+id/listview"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>

in layout xml it is not working for Android 2.2 for some reason
Google groups say that it will be fixed in next cupcake
function ListView.setDividerHeight(0) works fine

A: It is probably coming from the divider of ListView. Check out and play with setting
setDividerHeight(0)

as well as check header/footer dividers are off or use
setFooterDividersEnabled(false)

You can also set these in xml of course. e.g.
android:dividerHeight="0"


text:
Q: Install error with Kurento on ubuntu I have gone through all the Kurento questions on Stackoverflow and this error dose not seem to have arisen before.
I have installed the Kurento media-server and java client examples according the installation guides.
I have the media-server running. The problem arises when i go to run the client application. The same issue comes up not matter which one I choose.
This the Error that is generated:
[INFO] Scanning for projects...
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project org.kurento.tutorial:kurento-hello-world:6.1.1-SNAPSHOT (/root/kurento-tutorial-java/kurento-hello-world/pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for org.kurento.tutorial:kurento-tutorial:6.1.1-SNAPSHOT: Could not find artifact org.kurento:kurento-parent-pom:pom:6.1.1-SNAPSHOT and 'parent.relativePath' points at wrong local POM @ org.kurento.tutorial:kurento-tutorial:6.1.1-SNAPSHOT, /root/kurento-tutorial-java/pom.xml, line 5, column 10 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException

This is my pom.xml file
<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>

        <parent>
                <groupId>org.kurento.tutorial</groupId>
                <artifactId>kurento-tutorial</artifactId>
                <version>6.1.1-SNAPSHOT</version>
        </parent>

....... more stuff

  <!-- Kurento -->
                <dependency>
                        <groupId>org.kurento</groupId>
                        <artifactId>kurento-client</artifactId>
                        <version>6.1.1-SNAPSHOT</version>
                </dependency>
                <dependency>
                        <groupId>org.kurento</groupId>
                        <artifactId>kurento-utils-js</artifactId>
                </dependency>

I have tried following this tutorial for managing nightly builds but this hasn't change anything either.
In the installation guidelines there is no "SNAPSHOT" in the pom.xml sample, I have also tried removing this and but this still had no effect.
I am using a Ubuntu 14.04 system. I am wondering could someone point me in the right direction to solving this issue?

A: All Kurento tutorials assume that you are working with stable versions. For working with development (i.e. SNAPSHOT) versions you need to add the Kurento maven archiva to your settings.xml file, because SNAPSHOTS are not published to maven central.
The procedure is explanined here. See the section "Kurento Java Client".
Basically, you need to edit your ~/.m2/settings.xml file and add the appropriate repositories there.

A: Copied from the duplicated post here
You have checked out the development version of the tutorials, 6.1.1-SNAPSHOT, which depends on other development versions of kurento artifacts. Those artifacts are not published in maven central, so you have three options here

*

*Check out kurento-java and all related projects, such as kurento-module-creator and a bunch more. You can pull the thread from the pom, they are about 5 projects. You'll have to compile and install all of them in your local .m2 repository

*Use our internal archiva repository

*Checkout a tag containing a release version (i.e. git co 6.1.0)

In any case, the version of the tutorials should match the version of your KMS, so if you are using a development version of KMS, please use the development version of the tutorials. But if you are using a stable version of KMS, you should be using the matching release version of the tutorials.
You can find more info on how to work with development versions here

A: I have resolved this error by replacing the 6.1.1 snapshot POM.xml with the 6.0.0 POM.xml. The version of the kurento-media server I was using was 6.0.0 and I needed to get the pom.xml that matched this.
This is a link to the GITHUB commit of the 6.0.0 pom.xml which I used to replace the current snapshot version.
Link


text:
Q: Causation vs Correlation( question about a specific case of faulty logic) My question concerns the first two paragraphs of the text. Isn't the author falsly equating causation(austerity e.t.c leads to pathological lending patterns) with correlation( countries which display more austerity e.t.c will have more pathological lending patterns)?
edit: I am specifically refering to the part where he says that for the theory to be correct there must be some differences in pathological lending patterns among the countries

edit: After reading the text again my problem now is more that I don't really understand what exactly the author is saying. When he refers to the observable implications required for the theory to fit together what theory is meant?

A: From my reading, the author does not talk about austerity, but about different saving behavior in US/UK compared to other countries. I think you are right in pointing to the fact that it might not be the political economy / the design of the economy / the lack of regulating institutions which cause people to get indebted easily. More likely, both is a result and a cause of some deeper cultural identities. Whether the author claims the causal link you are citing, I'm not so sure however.


text:
Q: Based on crash in a program while running In the below program, when the user enter the input as 720 the program crashes. Why?
main()
{
  for (;;)
  {
    int depth,i,j;
    printf("enter the depth");
    scanf("\n%d",&depth);
    printf("first");
    int arr[depth][depth];//at this line the program get crashed //
    printf("first1");
    for(i=0;i<depth;i++)
    {
      for(j=0;j<=i;j++)
      {
        arr[i][j]=i+1;
      }
    }
    for(i=0;i<depth;i++)
    {
        printf("\n");
        for(j=0;j<=i;j++)
        {
          printf("%d\t",arr[i][j]);
        }
    }
  }
}

A: An array like that is allocated on the stack. If the user enters 720, you get an array with a size of 720*720*sizeof(int) bytes. On a system with 32-bit int, that's almost 2MB. And you likely get exactly what this site is named after: a stack overflow!
Instead, allocate on the heap:
int **arr = malloc(depth * depth * sizeof(int));

You need to release the memory with free(arr); later on.


text:
Q: Proving $~\sum_\text{cyclic}\left(\frac{1}{y^{2}+z^{2}}+\frac{1}{1-yz}\right)\geq 9$ $a$,$b$,$c$ are non-negative real numbers such that $~x^{2}+y^{2}+z^{2}=1$
show that $~\displaystyle\sum_\text{cyclic}\left(\dfrac{1}{y^{2}+z^{2}}+\dfrac{1}{1-yz}\right)\geq 9$

A: By C-S we obtain:
$$\sum_{cyc}\left(\frac{1}{y^2+z^2}+\frac{1}{1-yz}\right)=\sum_{cyc}\left(\frac{(3x+y+z)^2}{(3x+y+z)^2(1-x^2)}+\frac{(y+z)^2}{(y+z)^2(1-yz)}\right)\geq$$
$$\geq\frac{25(x+y+z)^2}{\sum\limits_{cyc}(3x+y+z)^2(1-x^2)}+\frac{4(x+y+z)^2}{\sum\limits_{cyc}(y+z)^2(1-yz)}.$$
Thus, it remains to prove that
$$\frac{25(x+y+z)^2}{\sum\limits_{cyc}(3x+y+z)^2(1-x^2)}+\frac{4(x+y+z)^2}{\sum\limits_{cyc}(y+z)^2(1-yz)}\geq9.$$
The last inequality we can prove by the $uvw$'s technique.
Indeed, let $x+y+z=3u$, $xy+xz+yz=3v^2$ and $xyz=w^3$.
Hence, we need to prove that
$$\frac{25u^2}{\sum\limits_{cyc}(3u+2x)^2(9u^2-6v^2-x^2)}+\frac{4u^2}{\sum\limits_{cyc}(3u-x)^2(9u^2-6v^2-yz)}\geq\frac{1}{9u^2-6v^2},$$
which  is eighth degree, which says that it's a quadratic inequality of $w^3$
and the rest is smooth, but a lot of work.
The starting inequality is a known unsolved problem and you can be first, which ends a proof.
Good luck!

A: Letting $a = x^2, b = y^2, c = z^2$,
it suffices to prove that, for all $a, b, c > 0$ with $a + b + c = 1$,
$$\sum_{\mathrm{cyc}} \left(\frac{1}{b + c} + \frac{1}{1 - \sqrt{bc}}\right) \ge 9.$$
We have
$$\frac{1}{1 - \sqrt{bc}} = \frac{1 + \sqrt{bc}}{1 - bc}
\ge \frac{1 + \frac{2bc}{b + c}}{1 - bc} = \frac{b + c + 2bc}{(b+c)(1-bc)}.$$
It suffices to prove that
$$\sum_{\mathrm{cyc}} \left(\frac{1}{b + c} + \frac{b + c + 2bc}{(b+c)(1-bc)}\right) \ge 9$$
or
$$\sum_{\mathrm{cyc}} \frac{(1+b)(1+c)}{(b+c)(1-bc)} \ge 9.$$
The last inequality is killed by BW (Buffalo Way).
This proof is not nice. Hope to see a nice proof.


text:
Q: Show and Hide javascript function not working with multiple functions I am having trouble with this javascript function - when I do the first paragraph by itself it functions normally, but when I create and run the second paragraph, the first show and hide function (ABOUT THE PROJECT) toggles the text to appear on the second paragraph (dialogueOne). Tried renaming id's and the show and hide function and it's not working. I'm running this through cargo collective, the images are hosted through CC and so are called image 4 and image 5.
A link to the page: https://alexabunnell.com/deathspins-spun

ABOUT THE PROJECT 

{image 4}

{image 5}

Text to be shown and hidden

A: You have two functions both named ShowAndHide. The second declaration replaces the first one, so any time you invoke it you'll get the behavior of the latter one.
One solution would be to pass the ID in as an argument to the function instead of hard coding it.
function ShowAndHide(id) {
  const element = document.getElementById(id);
  // …do whatever you need to do with element
}

…

…


text:
Q: What is the functionality of the <% operator? Recently, I looked at the example of implicit chain, implicit def foo[C3 <% C](c: C). I think I am confused about the difference between <% and (implicit c : C).
If I write implicit def bToC[C3 <: C](c: C)(implicit c3 : C3), it gives a compilation error, but why is that, implicit def should be in the scope?
Edit:
Can someone explain why
implicit def aToB[A1 : A](a: A1)(implicit ev: Int => A1): B = new B(a.n, a.n)
and
implicit def aToB[A1 <: A](a: A1)(implicit ev: Int => A1): B = new B(a.n, a.n)
are not working ?
Many thanks in advance

A: [C3 <% C] means implicit ev: C3 => C. In other word, an implicit function that converts C3 to C. So all C3 objects in the scope can be C objects.
def intPlus1[A <% Int](a: A) = a + 1
// def intPlus1[A](a: A)(implicit ev: A => Int) = a + 1

implicit def string2int(s: String) = s.toInt // String => Int

intPlus1("100")
intPlus1("100")(string2int)
// the result bark bark

Note that A <% A for any A, because an implicit function A => A is Predef'ed, thus B <% A if B <: A too, as @rightfold mentions in the comment. :)


text:
Q: Need to change all contents of a KnockoutJS observable array I have a knockoutJS observable array which I created in the usual way:
var MyGridModel = function(items) {
var self = this;
this.items = ko.observableArray(items);
...

I would like to change the array to a new one based on new information. I need to change the entire array (or if I can, the entire contents to the new array, whichever is easier).
My attempt to do this is done in the following code:
    this.setData = function(newData)
   {
       var grid = ko.observableArray(newData);
       self.items([]);
       self.items(grid);
   }

Unfortunately, I am getting a blank grid when I perform this operation.
Clearly I am missing something. How do I make this change work?
Someone please advise...

A: To update the contents of an observable array, just call it and pass the new contents to it:
this.setData = function(newData) {
    self.items(newData);
}

A: Try this:
this.setData = function(newData)
{
    self.items.removeAll();
    for(int i=0; i<newData.length; i++){
        self.items.push(newData[i]);
    }
}

Note: Each push will update observers.


text:
Q: The distribution of the sum of i.i.d random variables, each of which equally likely takes value from 1 to 5 Recently, I got stuck with the following task

The player twists 50 times a roulette wheel (a circle with 5 sectors of equal size, on these sectors there are numbers from 1 to 5) and each time equally likely he gets a number from one of these sectors. This is his profit. Find the probability that he'll win at least $170.

I'm accustomed that problems of the theory of probability are about patterns recognition, and each problem we should reduce to the problem that we already know how to solve, to some known "story" or distribution. But that task doesn't look like smth I've ever came across. And I didn't manage to think up, how to solve it.
Could you please give me any hints for solving, or references to similar problems' solution (if that problem is a known one).
Thanks a lot in advance!

A: Let $X_1, \ldots X_{50}$ denote the value of the individual rolls. You are then looking at the distribution of $S = \sum_{k=1}^{50} X_k$.
If you define $Y_i = aX_i+b$ and find $a,b \in \mathbb{R}$ such that $Y_i$ has 0 mean and unit variance, you would be able to approximate $S/{50}$ using a standard normal distribution using the Central Limit Theorem.


text:
Q: Remove line with specific word using tclsh I have a paragraph like this:
"Nothing is worth more than the truth.
I like to say hello to him.
Give me peach or give me liberty.
Please say hello to strangers.
I'ts ok to say Hello to strangers."

I want to result:
"Nothing is worth more than the truth.
Give me peach or give me liberty."

if a line uses the word "hello" then remove that line and take only the line without that word.
I find some information in reference:
enter image description here
so I think ít as follow: regexp "^[^hello]" $line
but it doesn't work

A: There are several problems with your attempt of:
regexp "^[^hello]" $line

*

*A good practice with Tcl regular expressions is to put your regex inside curly braces instead of double quotes.   Square brackets inside double quotes will be evaluated by Tcl as a command.

*^ means the beginning of the line in regular expression.

*Characters inside square brackets in a regular expression are considered a "character-class".   [^hello] does not mean the opposite of matching "hello".   Instead, it matches a single character that is not h, e, l, or o.

*Do you care about case?  If not, then add -nocase.
A Tcl expression, which you can use in an if statement to check that a line does not include "hello" (or "Hello") is simply this:
![regexp -nocase {hello} $line]


text:
Q: Kendo Scheduler Mobile Mode display Invalid data events
I am developing a calendar view using kendo scheduler and need to view this from web and apple iPad mini. When displaying the data in tablet it display the entered events in wrong places simply out of the calendar time ranges. But working correctly in web. I use the same code except the additional code line Mobile(MobileMode.Tablet), please refer the attached images and my code line for more details.
@(Html.Kendo().Scheduler<Portal.Presentation.Web.BoundedContext.QC.MVC.Areas.Razor.Models.LeavePlanModel>()
              .Name("scheduler")
              .ShowWorkHours(true)
              .WorkDayStart(08,30,00)
              .WorkDayEnd(19,30,00)
              .WorkWeekStart(1)
              .WorkWeekEnd(5)
              .Date(@DateTime.Now)
              .StartTime(08,30,00)
              .EndTime(19,30,00)
              .Height(600)
              .Views(views =>
                         {
                             views.DayView();
                             views.WorkWeekView(workWeekView => workWeekView.Selected(true));
                             views.WeekView();
                             views.MonthView();
                         })
              .Events(e =>
                          {
                              e.Save("scheduler_save");
                              e.Remove("scheduler_remove");
                              e.Edit("scheduler_editMobile");
                              e.MoveStart("scheduler_moveStart");
                              e.ResizeStart("scheduler_resizeStart");
                              e.DataBound("scheduler_dataBound");
                              e.Cancel("scheduler_cancelLeave");
                          })
              .Mobile(MobileMode.Tablet)
              .Timezone("Etc/UTC")
              .Resources(resource =>
                             {
                                 resource.Add(m => m.OwnerId)
                                     .Title("Resource")
                                     .DataTextField("Text")
                                     .DataValueField("Value")
                                     .DataColorField("Color")
                                     .DataSource(datasource => datasource.Read("GetInspectors", "LeavePlan"));

                                 resource.Add(m => m.LeaveType)
                                     .Title("Leave Type")
                                     .DataTextField("Text")
                                     .DataValueField("Value")
                                     .DataColorField("Color")
                                     .DataSource(datasource => datasource.Read("ReadLeaveType", "LeavePlan"));
                             })
              .DataSource(d => d
                                   .Model(m =>
                                              {
                                                  m.Id(f => f.OwnerId);
                                                  m.Field(f => f.Title).DefaultValue("No title");
                                                  m.Field(f => f.OwnerId).DefaultValue(1);
                                                  m.Field(f => f.Title).DefaultValue("No title");
                                                  m.RecurrenceId(f => f.RecurrenceId);
                                              }).Read(x => x.Action("Read", "LeavePlan").Data("SchedulerFilter.OnSearch"))))
            </div>


text:
Q: ASP.Net MVC: Localized texts with new line? I've an Asp.Net MVC 3 website, which will be localized.
I've several resx files which contains my texts, and I've in my views some

@My.NameSpace.Through.My.LocalizationFile.Key

But I can't make it represent the new line.
I tried:

*

*Shift+enter: I've got the new line in the resource file, but not in my browser

*\r\n : I see the \r\n in my browser

*\n : Same

*
 : I see the
 in my text

So what should I do to have a new line?
Edit: I know that I could use Html.Raw, but I just can't ask to translators to put html code in their translation.

A: You can put the
 for the line breaks and use the @Html.Raw() method to show the string with the line break instead of the
 string.

A: I think you should use a combination of Shift+Enter and the CSS white-space property instead of potentionally opening up to XSS vulnerabilities, as you would do using @Html.Raw() solution.
@My.NameSpace.Through.My.LocalizationFile.Key

I don't know the specific case, but it could be that you might find that pre-wrap suits your case better. Read more about the different white-space properties here

A: To be honest, I know it's not the nicest thing in the world, but it's fool-proof and it means your translators don't have to put any code in their translations:
Building upon the answers already given, why don't you just use Html.Raw, but before doing so, replacing the \r\n that using Shift+Enter in the resource file results in, with a

So say for example you had the string named Welcome in the resource file ApplicationMessage, you could do:
@Html.Raw(ApplicationMessage.Welcome.Replace("\r\n", "
")

That will give you what you need. Here's a similar question:
HTMLencode HTMLdecode

A: You should probably use
 and render the output with Html.Raw()

A: Yeah, thanks to mattytommo.
You can use
First line
 second line

in resource, or
resource.Replace("\r\n", "
")

in code and Shift + Enter in resource editor.
Both works fine, but you have to use
@Html.Raw();