text:
Q: Lambdas vs functions+function pointers for UI events I have a game engine which includes a built-in in-game editor. the editor is it's own class that is used only as a single object that gets instantiated when the in-game editor is invoked. I also have a (fairly) complete UI system separate from the editor (will be used in the game as well). The editor has UI elements such as buttons that call functions on the editor class, but the UI system will also be used for other non-editor things. So in order for the buttons to access the editor functions and other things not in the editor class, I have to use function pointers, not class method pointers. that function then calls the appropriate editor->Method().
So this is what I have been doing:
void MyButton_Click( void ) { if ( editor ) editor->AppropriateMethod(); };
Button some_button( "Button Label", &MyButton_Click );

I just learned about lambdas in C++11 and realized I can get rid of all those global functions if I use lambdas instead when instantiating my buttons, like:
Button some_button( "Button Label", []() { if ( editor ) editor->AppropriateMethod(); } );

However, since I've never used lambdas before today, I want to know if this is even a good idea. I think that so long as I don't need more than one button to call the same editor function, I won't be duplicating code anywhere (the lambda). If I needed to, I'd just declare a global EditorFunction_Click() function like I have been doing.
So other than that, whats the better design here? Lambdas or global functions that are friends to the editor class? Is there any glaring negative attribute about one or the other that I'm overlooking?

A: Why not use std::function and allow the user to decide whether to use a lambda, function pointer, function object, etc? It adds a bit of overhead but it allows for a lot of flexibility.
For example,
typedef std::function<void (void)> handler_func;

class Button {
    // stuff...

    Button(std::string label, handler_func func);

    // stuff...
};

Then you can create a button that uses any callable object in C++, for maximal flexibility. If it looks like a function, you can use it.


text:
Q: SQL Join - displaying table, even if second joined table has no relevence I have two tables, one with persons and the other with various dogs that each person owns. I would like to only query the database once.
I would like to always display the active people, even if they don't have any dogs attached to their id. How would I query this?
SELECT person.*, dog.*
FROM person
LEFT OUTER JOIN dog ON person.id = dog.person_id AND
WHERE person.active=true and dog.active=true

A: Move the condition to the join (on clause); that way you will left join any records that match both the person_id and the active flag. If no active dog is found, the person is still present in the result.
If you add the condition in the where clause, first the left join is evaluated, and then all records that are not active dogs (including those that don't have a dog at all) are filtered out. It effectively turns your left join into an inner join if you do that.
SELECT
  person.*,
  dog.*
FROM
  person
  LEFT JOIN dog ON person.id = dog.person_id AND dog.active=true
WHERE
  person.active=true

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where does the child process start after call fork()? Accroding to the book named 'Advanced Programming in the UNIX Environment', after we call fork(), child process call exec() to run a new process. exec() would use a new process to replace the old one, and the new one would start at main().
But we all know, when we call fork(), both the father process and child process start at fork() function. So, how do we understand the book's opinion?

A: Maybe their was some confusion in the wording of the book:

• We call fork to create a new process, which is a copy of the caller.
  We say that the caller is the parent and that the newly created
  process is the child. Then fork returns the non-negative process ID of
  the new child process to the parent, and returns 0 to the child.
  Because fork creates a new process, we say that it is called once—by
  the parent — but returns twice—in the parent and in the child.
• In the child, we call execlp to execute the command that was read
  from the standard input. This replaces the child process with the new
  program file. The combination of fork followed by exec is called
  spawning a new process on some operating systems. In the UNIX System,
  the two parts are separated into individual functions. We'll say a lot
  more about these functions in Chapter 8.

On a successful fork() call, we return twice. Once as the parent process, and again as the child.
Calling exec() will change the program the process is running. This is often paired with the child process after calling fork(), but that is completely optional.
For simplicity, fork() creates (duplicates) processes, and exec() changes our processes.
fork(2) man page
exec(3) man page

A: I guess this can go into the answer as well: There might be some confusion. New process comes to existence with fork(). exec() replaces the program being run... but does not create or start new process. I suspect the term process might be used a bit loosely? You can also refer to execve(2) man page for a clearer nomenclature and explanation:

execve() executes the program pointed to by filename.  This causes the program that is currently being run by the calling process to be replaced with a new program, with newly initialized stack, heap, and (initialized and uninitialized) data segments.

A: The fork() creates a child process by duplicating the calling process. The process that invoked fork() is the parent process and the newly created process is the child process. So, fork() splits a process in two, and returns 0 to the child process and the PID of the child process to the parent process, or -1 if the fork failed.
The child process and the parent process run in separate memory spaces. At the time of fork() both memory spaces have the same content.
When you call exec() from a process, it runs an executable file in the context of an already existing process, replacing the previous executable. The new program is loaded into the same process address space. The current process is just turned into a new process and hence the PID is not changed, this is because we are not creating a new process we are just replacing a process with another process in exec.
There is concept called Copy-on-Write, its good to have knowledge about it-

Copy-on-Write is an optimization where the page tables are set up so that the parent and child process start off sharing all of the same memory, and only the pages that are written to by either process are copied when needed.

If the process does not modify any memory and immediately executes a new process, replacing the address space entirely. Thus, it would be wasteful to copy all of the process's memory during a fork, and instead the copy-on-write technique is used.


text:
Q: Sandbox App File Access Type Location Writing Files I am testing file access on macOS Big Sur Xcode Obj-C with a sandboxed app. Because the app is sandboxed, I had to give read/write access to the folder my app writes files to  - in this case the user's Music Directory.
This is located at Targets / Signing & Capabilities in the Info Tab under App Sandbox and File Access Type.
My app is writing files using:
NSString* fileLocation = [NSString stringWithFormat:@"%@/Music/Sample Files", NSHomeDirectory()];

This all works file. My sandbox app has no problems working with files within the user's /Music/Sample Files/ folder.
My question is: if the user has moved their default Music folder location (which I believe is an option in macOS?) I don't think this would worlk. Since my app has ~/Music/Sample Files  - how can I write it so that it would still work if the user has moved their default Music Folder to somewhere else?
Bonus question: Why are the file access options so limited in the File Access Type for a sandbox app? It seems to be limited to Downloads / Pictures / Music / and Movies folders. Shouldn't the user's Documents folder (at the very least) be included in this list?

A: Better to use NSMusicDirectory in URLForDirectory of NSFileManager,
Then store the URL as with a security scope so you don't have to ask user after a second launch for access.

A: OK so I believe Music is a folder that can't be removed even if a music library is moved via the Music app. I guess if a music library is moved or changed, the default Music folder will still remain and usable by the app.
Therefore,
NSString* fileLocation = [NSString stringWithFormat:@"%@/Music/Sample Files", NSHomeDirectory()];

Should work regardless?
https://support.apple.com/en-lb/guide/music/mus69248042d/mac
https://apple.stackexchange.com/questions/100341/is-it-possible-to-remove-or-delete-the-music-folder


text:
Q: Retrieving XML data using a web service in Java I'm in need of some help regarding a Web Service that has to retrieve and check a valid element from a XML file. The web service method should look like this - translate ("flower","english","russian") and the client should be able to allow you to enter the desired word, the original Language and the target Language. If these exist in the XML file the translation of it will be displayed on the client side, if not, it will display an error message.
I've create a standard web service method - add(int a, int b) and created also the client part using a normal java application, added a swing GUI, connected with the wsdl link and the method works nicely. How would it be best for me to make this program work? Please advice.
The service looks like this:
@WebMethod(operationName = "translate")
    public String translate(@WebParam(name = "word") String word,
            @WebParam(name = "originalLanguage") String originalLanguage,
            @WebParam(name = "targetLanguage") String targetLanguage)
            throws Exception {

        XMLSource dataLSource = new XMLSource();
        return dataLSource.getTranslation(word);

    }

Considering that the XML file should look like this: translation.xml
<?xml version="1.0" encoding="UTF-8"?>
<translation>
    <word>
        <english>car</english>
        <russian>avtomobil</russian>
    </word>
    <word>
        <english>flower</english>
        <russian>tsvetok</russian>
    </word>
    <word>
        <english>butterfly</english>
        <russian>babochka</russian>
    </word>
</translation>

Also the XML source class:
public class XMLSource {

    private Document readData() throws Exception{

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        File xmlFile = new File("translation.xml");
        return db.parse(new FileInputStream(xmlFile));

    }

    public String getTranslation(String original) throws Exception{

        Document doc = readData();
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xp = xpf.newXPath();
        XPathExpression xpe = xp.compile("/translation/word/russian[../english"
                + "/text()='"+original+"'] ");
        String translated = (String) xpe.evaluate(doc, XPathConstants.STRING);
        return translated;

    }
}

The client GUI sample of the program

A: You can use this as a starting point and modify to suit your need. It means you need to load your file with an InputSource object and then use an XPath to extract the data from your XML file. There are plenty of examples and tutorials on the web on how to do this. The below snippet is from Simplest way to query XML in Java.
String xml = "<resp><status>good</status><msg>hi</msg></resp>";

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

InputSource source = new InputSource(new StringReader(
xml));
String status = xpath.evaluate("/resp/status", source);

System.out.println("satus=" + status);

A: public class XMLSource {
    public String getTranslation(String original) throws Exception{
        Document doc;
         try {
            doc = readData();
            XPathFactory xpf = XPathFactory.newInstance();
            XPath xp = xpf.newXPath();
            XPathExpression xpe = xp.compile("/translation/word/russian[../english"
                    + "/text()='"+original+"'] ");
            String translated = (String) xpe.evaluate(doc, XPathConstants.STRING);
            if ("".equals(translated)) return " word not found";

            return translated;
         } catch (Exception ex) {
             Logger.getLogger(XMLSource.class.getName()).log(Level.SEVERE, null, ex);
             return "Error";
         }
     }

    private Document readData() throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        File xmlFile = new File("translation.xml");/*enter the absolute path to the XML file.for example"C:\\Users\\User\\Documents\\NetBeansProjects\\WebServiceTranslate\\src\\java\\service\\translation.xml"*/
        return (Document) db.parse(new FileInputStream(xmlFile));
    }
}


text:
Q: How to upload local image by drag and drop on selenium I'm trying to upload local image on Selenium.
The website can accept file only drag and drop.
Selenium IDE works well.

but I can't upload image by elesemnt.sendKey();
driver.findElement(By.xpath("//input[@name='image1']")).clear();
driver.findElement(By.xpath("//input[@name='image1']")).sendKeys("/Users/trmt_8/Desktop/BUYMA/1.png");
driver.findElement(By.xpath("//input[@name='image2']")).clear();
driver.findElement(By.xpath("//input[@name='image2']")).sendKeys("/Users/trmt_8/Desktop/BUYMA/38565487.png");

How can I upload image?

A: When I used Google chrome and chorome_driver, I could upload image.(^^)
You can download form here --->
ChromeDriver - WebDriver for Chrome


text:
Q: Is it ok to use "async" with a ThreadStart method? I have a Windows Service that uses Thread and SemaphoreSlim to perform some "work" every 60 seconds.
class Daemon
{
    private SemaphoreSlim _semaphore;
    private Thread _thread;

    public void Stop()
    {
        _semaphore.Release();
        _thread.Join();
    }

    public void Start()
    {
        _semaphore = new SemaphoreSlim(0);
        _thread = new Thread(DoWork);
        _thread.Start();
    }

    private void DoWork()
    {
        while (true)
        {
            // Do some work here

            // Wait for 60 seconds, or exit if the Semaphore is released
            if (_semaphore.Wait(60 * 1000))
            {
                return;
            }
        }
    }
}

I'd like to call an asynchronous method from DoWork. In order to use the await keyword I must add async to DoWork:
private async void DoWork()

*

*Is there any reason not to do this?

*Is DoWork actually able to run asynchronously, if it's already running inside a dedicated thread?

A: You can do this, but it wouldn't be a good idea. As soon as the first await hits that is not synchronously completed, the rest of the work will be done on a continuation, not the thread you started (_thread); the thread you start will terminate at the first such await. There is no guarantee that a continuation will go back to the originating thread, and in your scenario, it cannot - that thread is now toast. That means that:

*

*_thread is meaningless and does not represent the state of the operation; as such, your Stop() method with a _thread.Join(); doesn't do what you expect it to do

*you've created a thread (allocating threads is expensive, in particular because of the size of the stack) only to have it exit almost immediately

Both of these issues can avoided by using Task.Run to start such operations.


text:
Q: R Shiny - Rendering multiple image or plot in 1 page (multiple as in 1000+) I need to render multiple image or plot (whichever faster works for me) in Shiny web app. By multiple I mean about 1000+ image. I am trying to create a kind of dashboard of heat-o-meter gauges to show the status of a server whether it is in healthy condition or not. I am aware of how to render multiple image and plot in Shiny but to scale up to 1000+ and render them in a short amount of time is a challenge. Is there any way to do it in faster?
I have tried several methods such as:

*

*creating multiple plots, putting them into list, and display them
    using grid.arrange from gridExtra package. Problem here is
    grid.arrange() takes a lot of time to render for 1000+ images.

*creating multiple plot in 1 image, save them to png, and display the png file. Also same problem like grid.arrange() method. It takes a lot of time.

*Render and save the plot for every servers beforehand in multiple image and display the image when any of the server is
called. Would like to know how esp for 1000+ image? and to render that many images I am afraid there
    will be performance issue also.

*Any other method? I am wondering if Shiny is able to pre-render all the plots once then let the users see it when they go into the Shiny web-app website. But that does not seem how Shiny works. The web-app process is re-started whenever user access the website.


text:
Q: Django OneToOneField relation with to_field and db_column been ignored on makemigrations files

Even after reading the docs on db_column and Django' recomendations I was not able to accomplish the desired results with this feature.

This is part of my code
class DefaultBaseModel(models.Model):
    slug = models.SlugField(primary_key=True,
                            unique=True,
                            null=False,
                            blank=False)

class Bill(DefaultBaseModel):

class Payment(DefaultBaseModel):
    bill = models.OneToOneField(Bill,
                                related_name='payments',
                                on_delete=models.CASCADE,
                                to_field='slug',
                                db_column='bill_slug')

What I expect to do is the following on Django's shell:
from apps.bills.models import Payment
p = Payment.objects.first()
p.bill_slug

However I get the error:
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Payment' object has no attribute 'bill_slug'

Well,
p.bill_id

gives me the slug value but it is still creating the column with the suffix _id.

*

*I tried to delete makemigrations (migrate) files (those initial.py and others) and create it again

*Moved from Sqlite to Postgres

*Looked into Django's makemigrations files and db_column='bill_slug' was there.

Any ideas?

A: There isn't anything called "branch_slug" is there? A Bill has a slug though. In your example code, I don't see branch anywhere. Try to be less verbose with column and table names and see if it's working:
class DefaultBaseModel(models.Model):
    slug = models.SlugField(unique=True,)

    class Meta:
        abstract = True

class Bill(DefaultBaseModel):

class Payment(DefaultBaseModel):
    bill = models.OneToOneField(Bill, on_delete=models.CASCADE,)

Now this should work:
from apps.bills.models import Bill, Payment
b = Bill.objects.first()
b.slug

p = Payment.objects.first()
p.bill.slug


text:
Q: Excel Power Query: How to add data from a spreadsheet? I'm wondering what the best way to do this is:
I have Power Query pull a list of employees from a database and load to a spreadsheet.
From here, users need to add columns next to the employee names (becauase IT won't add this data tot he database, it needs to be done in excel).
So, for example, Column A = employee name (provided by power query) and column B = salary (data entry by users).
Naturally, the database changes over time. Employees are added and removed. Therefore, the data in column B needs to retain it's attachment to the name in column A. If an employee in Column A is removed, so too should the data in column B. However, if the sort order of employee changes in Power query (either new employee are added to the database or someone add a filter in the power query) then the data in column B should organize itself accordingly. Ex: If A1 ends up as A8 because 7 new employees are added then B1 should end up at B8.
The idea is to then take in columns A and B into a new power query for more modelling.
So I wonder how to go about this?


text:
Q: Redirecting page with Iron-Router Currently I am using the accounts packages supplied by Meteor to allow people to sign up for the site I am working on. I want to allow users to have a bio page, whenever I am logged into a particular person a side bar navigation appears with a lot of links one of which says "Bio". I want bio to redirect me from the home page to MY bio page i.e:
localhost:3000/ -> localhost:3000/bio/uSerId23453423434

Currently write now I am using Iron-Router to do this:
...

Bio

...

And in my Router I have:
Router.map(function() {
    ...
    this.route('bio',
               {path: '/bio/:_id',
                data: function () { return {_id: Meteor.userId()} }
               });
    ...

But when I click on the link I am not redirected anywhere. Any ideas as to what I am doing wrong?

A: you don't need the parameter _id in your path since you are already using Meteor.userId(). Iron-router won't render if it can't find the _id parameter in the template. Removing it will fix your issue:
Router.map(function() {
    ...
    this.route('bio',
               {path: '/bio',
                data: function () { return {_id: Meteor.userId()} }
               });
    ...

If you want to keep the path with the _id you should render using {{#with}} to set the data context, for your {{pathFor 'bio'}}
You can view more information at:

*

*https://github.com/EventedMind/iron-router/blob/master/DOCS.md#path-functions-and-helpers


text:
Q: Could not find mapbox vision sdk dependencies I try to set up the Mapbox vision sample app (https://github.com/mapbox/mapbox-vision-android), but not able to test the Mapbox Vision SDK sample app.
Dependency files are not downloading due to the Forbidden error.
Error :
Could not GET 'https://mapbox.bintray.com/mapbox/com/mapbox/navigator/mapbox-navigation-native/7.0.0/mapbox-navigation-native-7.0.0.pom'. Received status code 403 from server: Forbidden
Disable Gradle 'offline mode' and sync project.
Could you please share the details for how to fix this issue?
Followed the instructions mentioned on https://docs.mapbox.com/android/vision/guides/install/ page and used new tokens but the same issue still exists.
Gradle file:
allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://mapbox.bintray.com/mapbox" }
        maven {
            url 'https://api.mapbox.com/downloads/v1/vision/android/maven'
            authentication {
                basic(BasicAuthentication)
            }
            credentials {
                username "mapbox"
                password 'MAP_BOX_KEY'
            }
        }
        maven { url 'http://raw.github.com/saki4510t/libcommon/master/repository/' }
    }

}

Gradle dependency :
implementation "com.mapbox.mapboxsdk:mapbox-android-sdk:$mapbox_sdk"
implementation "com.mapbox.mapboxsdk:mapbox-android-navigation:$mapbox_navigation"
implementation "com.mapbox.mapboxsdk:mapbox-android-navigation-ui:$mapbox_navigation"
implementation "com.mapbox.mapboxsdk:mapbox-android-core:$mapbox_core"
implementation "com.mapbox.vision:mapbox-android-vision:0.13.0"
implementation "com.mapbox.vision:mapbox-android-vision-ar:0.13.0"
implementation "com.mapbox.vision:mapbox-android-vision-safety:0.13.0"

implementation 'com.mapbox.mapboxsdk:mapbox-sdk-turf:5.8.0'
implementation 'com.mapbox.mapboxsdk:mapbox-sdk-geojson:5.8.0'
implementation 'com.mapbox.mapboxsdk:mapbox-sdk-core:5.8.0'

implementation 'com.mapbox.mapboxsdk:mapbox-sdk-services:5.8.0'


text:
Q: Can we use a ScrollView inside a LinearLayout? I need to design a GUI with content at the top of the screen that doesn't scroll, and content below the top part that does scroll. I thought about using a LinearLayout for the non-scrolling part and ScrollView for the scrolling part.  However, when I try to use ScrollView after a LinearLayout I get a runtime error.  Is it possible to add a LinearLayout and a ScrollView to a parent LinearLayout?

A: You can
<LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical"
  >

  <!-- non-scrolling top pane -->
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    >

    <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="This text will not scroll"
      />

  </LinearLayout>

  <!-- scrolling bottom pane -->
  <ScrollView
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    >

    <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      >

      <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This text will scroll if it is long enough..."
        />

    </LinearLayout>

  </ScrollView>

</LinearLayout>


text:
Q: solve a equation in matlab with variable i'm trying to use 'solve' method to solve equations in matlab , i have a matrix which Coefficients of the variables are in it called 'A'
but when i use solve method with this code (i want A(1,1) to be the Coefficients  for x variable) :
W0 = solve('A(1,1)*x+13*y-16*z=1','13*x-10*y+13*z=0','-16*x+13*y-7*z=0')
W0 = [W0.x W0.y W0.z]

i dont get the correct answer and it shows me this for answer:
[ 11/(11*A(1, 1) + 185), 13/(11*A(1, 1) + 185), -1/(11*A(1, 1) + 185)]

meaning the Value of A(1,1) is not recognized in code, can anyone help me getting right answer?

A: How about
W0 = solve([num2str(A(1,1)),'*x+13*y-16*z=1'],'13*x-10*y+13*z=0','-16*x+13*y-7*z=0')

A: Using solve,
W0 = solve(strcat(num2str(A(1,1)), '*x+13*y-16*z=1'),'13*x-10*y+13*z=0','-16*x+13*y-7*z=0');
W0 = [W0.x W0.y W0.z]

A: Avoid solve, and use \ instead.
W0 = ([A(1,1) 13 -16; 13 -10 13; -16 13 -7]\[1;0;0])'


text:
Q: Difference between "-bash" and "bash" I have always been using Bash shell in my terminal (OSX El Capitan) but for some weeks now it states "-bash" and tells me there are 2 "bash-alike" processes as you can see on the image.
Would someone know what it means?

A: From Invoking Bash in the Bash Reference Manual:

A login shell is one whose first character of argument zero is '-', or one invoked with the --login option


text:
Q: Ruby check if nil before calling method I have a string in Ruby on which I'm calling the strip method to remove the leading and trailing whitespace. e.g.
s = "12345 "
s.strip

However if the string is empty nil I get the following error.
NoMethodError: undefined method `strip' for nil:NilClass

I'm using Ruby 1.9 so whats the easiest way to check if the value is nil before calling the strip method?
Update:
I tried this on an element in an array but got the same problem:
data[2][1][6].nil? ? data[2][1][6] : data[2][1][6].split(":")[1].strip

A: I guess the easiest method would be the following:
s.strip if s

A: I'd opt for a solution where s can never be nil to start with.
You can use the || operator to pass a default value if some_method returns a falsy value:
s = some_method || '' # default to an empty string on falsy return value
s.strip

Or if s is already assigned you can use ||= which does the same thing:
s ||= '' # set s to an empty string if s is falsy
s.strip

Providing default scenario's for the absence of a parameters or variables is a good way to keep your code clean, because you don't have to mix logic with variable checking.

A: Method which works for me (I know, I should never pollute pristine Object space, but it's so convenient that I will take a risk):
class Object
  def unless_nil(default = nil, &block)
    nil? ? default : block[self]
  end
end

p "123".unless_nil(&:length) #=> 3
p nil.unless_nil("-", &:length) #=> "-"

In your particular case it could be:
data[2][1][6].unless_nil { |x| x.split(":")[1].unless_nil(&:strip) }

A: ActiveSupport comes with a method for that : try. For example, an_object.try :strip will return nil if an_object is nil, but will proceed otherwise. The syntax is the same as send. Cf active_support_core_extensions.html#try.

A: If you want to avoid the error that appears in the question:
s.to_s.strip

A: You can use method try from ActiveSupport (Rails library)
gem install activesupport

require 'active_support/core_ext/object/try'
s.try(:strip)

or you can use my gem tryit which gives extra facilities:
gem install tryit

s.try { strip }

A: Ruby 2.3.0 added a safe navigation operator (&.) that checks for nil before calling a method.
s&.strip

If s is nil, this expressions returns nil instead of raising NoMethodError.

A: If you don't mind the extra object being created, either of these work:
"#{s}".strip
s.to_s.strip

Without extra object:
s && s.strip
s.strip if s

A: To complete the options shown here, there is the "Existence Check Shorthand", recommended in the Ruby Style Guide:

Use &&= to preprocess variables that may or may not exist. Using &&= will change the value only if it exists [means, is not nil], removing the need to check its existence with if.

So in your case you would do:
s = "12345 "
s &&= s.strip

A: Simply put:
s = s.nil? ? s : s.strip

Tl;dr Check if s is nil, then return s, otherwise, strip it.


text:
Q: Going down fails when $R$ is not integrally closed. In this post there is a counterexample to the going down theorem.

I am pretty sure that the reason why it fails is because $R$ is not integrally closed in $A$, but I don't have any nice argument to show that this is true.

I would appreciate any help!

A: If you want to show that $R = \lbrace f \in K[X,Y] \colon f(0, 0) = f (1, 1) \rbrace$ is not integrally closed, then notice that $X$ is integral over $R$, and $X\notin R$.


text:
Q: How many WFS-T clients exist? I would like to know which applications or libraries (proprietary or open source) offer transactional Web Feature Service (WFS-T) client functionality. Those include:

*

*Desktop or online applications that offer the functionality "out of the box", or

*Libraries that can be used to develop a WFS-T client, like OpenLayers.

A: Desktop GIS

*

*Opensource: udig, QGIS (Releases currently only supports WFS, developer version contains experimental WFS-T support check the QGIS bug tracker.)

*Commercial: Mapinfo Professional

Web GIS

*

*Opensource: OpenLayers, Mapbuilder & Mapbender

*Commercial: Internet Mapping Framework (IMF)

Most information taken from geoserver.org.

A: In the ESRI world, WFS-T is supported starting with version 9.3 in ArcGIS Desktop for visualization of WFS only and ArcGIS Server for publishing and edition through a WFS-T client.

A: Gaia a light client with WFS-T functionality

A: Current development version of QGis suopports WFS-T


text:
Q: How many reducing functions do collection values pass through in a call to transduce? Consider
(transduce (comp (filter even?) (map inc)) conj [1 2 3]) ; => [3]

If we let the return value of the transducer returned by (filter even?) be F, and the return value of the transducer returned by (map inc) be M, then both F and M are reducing functions. In addition, conj is a reducing function.
Question: When the call to transduce is made, is each of the 1, 2, and 3 from [1 2 3] passed through each of the reducing functions F, M, and conj, or is there a single reducing function R (that is somehow the combination of F, M, and conj) that these elements pass through?
(Aside: If it's the former case, then there must be intermediate collections involved behind the scenes. Since I know the purpose of transducers is to avoid the creation of intermediate collections, I'm assuming it must be the latter. Just trying to clarify my understanding tho :)

A: Notice that (comp (filter even?) (map inc)) will produce a single function which will be a composition of two functions (filter and map) so each value will be passed to this single composed function. There won't be intermediate collections between filter and map invocations.

A: It is indeed correct that no intermediate collections are created. However, there are some inaccuracies that worth clarifying.

If we let the return value of the transducer returned by (filter >even?) be F, and the return value of the transducer returned by >(map inc) be M, then both F and M are reducing functions. In >addition, conj is a reducing function.

To be precise, (filter even?) and (map inc) are transducers, or xforms - this is a 'new' type of function introduced with the birth of the transducer concept. A transducer is a function that takes an argument which is a reducing function (e.g., conj, or +), and produces a new reducing function. The transduce function takes a transducer as its first argument, and a reducing function as its second. It then applies the transducer to the reducing function to obtain a new reducing function. This new reducing functions is applied to the elements of the collection exactly as the good old reduce function does.
This means that all to following, for example, are reducing functions:
conj
((map inc) conj)
((filter even?) conj)
((compose (map inc) (filter even?)) conj)

In the later example above, compose applies its arguments in a chain to conj - so (map inc) is applied to conj and this results in a reducing function, which is then fed to (filter even?) to create the final reducing function.
So, to summarize, the transduce function first creates a 'new' reducing function using its first and second arguments. Then it uses it just as reduce does. Every element of the collections is passed, in its turn, to this reducing function. So the reducing operation is done with only one pass over the collection.


text:
Q: Does std::regex support "(?i)" for case insensitivity? I am using Visual Studio 2010.  This...
std::regex pattern("(?i).*a.*");
...throws this...
std::tr1::regex_error - regular expression error
...and I can't find anything that says if std::regex supports the (?i) syntax for case insensitivity or not.
Can anyone confirm/deny that (?i) is not supported as a prefix for case insensitivity by std::regex?

A: The standard only requires conformance to the POSIX regular expression syntax (which does not include Perl extensions like this one) and conformance to the ECMAScript regular expression specification (with minor exceptions, per ISO 14882-2011§28.13), which is described in ECMA-262, §15.10.2. ECMAScript's regular expression grammar does not include the use of modifiers in the form of the (?) syntax, so, by extension, neither does C++11/14, nor do most implementations of TR1.
That does not preclude your standard library from implementing more PCRE extensions, but the standard does not require it, so it's simply not guaranteed.
So, no, it's not supported, per se.
You can, however declare your regular expression as follows:
std::regex pattern(".*a.*", std::regex_constants::icase);

This will declare your pattern to be case-insensitive.

A: boost::regex supports Perl syntax, which has (?i).


text:
Q: How to get a value back to my ajax result from a PHP file I am making a post to a php file like this:
$( document ).ready(function() {
  $(document).on('click', '.menulistnaam', function (){
        var menucatnaam = $(this).attr('id');

      $.post("include/menuinclude.php?menucat="+menucatnaam, function(result){
          $("#menukaart").html(result);
      });
  });
});

All works fine but I would like to send a specific result back to this code.
In my PHP I have the following:
$menucatnaam = $_GET['menucat'];

$menu = "
select
  cnt.catid, cat.id, cnt.title, cnt.introtext, cnt.fulltext, cnt.ordering, cnt.images, cnt.alias, cnt.state, f.item_id, cat.id, cat.title,
  max(case when f.field_id = 8 then f.value end) as nieuw,
  max(case when f.field_id = 7 then f.value end) as beschrijving,
  max(case when f.field_id = 5 then f.value end) as prijs,
  max(case when f.field_id = 4 then f.value end) as inhoud,
  max(case when f.field_id = 3 then f.value end) as media
  from snm_fields_values f
  join snm_content cnt
  on cnt.id = f.item_id
  join snm_categories cat
  on cnt.catid = cat.id
  where cnt.state = 1
  and cat.alias = '".$menucatnaam."'
  group by f.item_id
  order by f.item_id, media, beschrijving, prijs, inhoud, nieuw
";

How can I send back the value of $menucatnaam ?
In the end I want to check what anchor tag was clicked and give it an active class.
I googled a bit and found out I had to create an array and then encode it with json but I couldn't get it to work.
My attempt was this:
$aliasjson = json_encode(array("aliasresult"=>"$menucatnaam"));
echo $aliasjson;

And then my js:
$.post('include/menuinclude.php', {"menucat": menucatnaam}, function (result) {
    $("#menukaart").html(result);
    console.log(result.aliasresult);
}, 'json');

But that didn't give me the result I wanted at all, when I clicked an anchor tag nothing was happening.
How can I do this?

A: In ajax call add below parameter
dataType: "json",//tells jQuery that you want it to parse the returned JSON

and after getting response
result = jQuery.parseJSON(result);//parsing JSON to string
console.log(result.result);

or else
  don't change any jquery code just echo required paramter from PHP
echo $menucatnaam;


text:
Q: How to create dynamic radiobuttons in CodenameOne Using CodenameOne, I created an array of RadioButtons based on the count of records on a database table.
Container searchDisplayContainer = findMyContainer(f);

for(int i=0; i < records.length; i++) {
    RadioButton rdb = new RadioButton();

    rdb.setName("rdb"+i);

    rdb.setText("rdb"+i);

    rdb.setGroup("locations");

    searchDisplayContainer.addComponent(rdb);
}

With this code, a number of RadioButtons are displayed on the simulator screen.
My problem is that after displaying the radiobuttons, I cannot check which one is selected.
Usually I can create the radiobutton in the theme.res and call it in the code with:
RadioButton rdb1 = findRadioButton(f);

and check if the button is selected with if(rdb1.isSelected)
However since I am not creating my radio buttons initially in the theme.res, I cannot use the findRadioButton(f) method.
My question is how do I create a number of RadioButtons within the code and then be able to check if they are selected after the submit button is pressed?

Question Modification
package userclasses;

import generated.StateMachineBase;
import com.codename1.ui.*;
import com.codename1.ui.events.*;
import com.codename1.ui.util.Resources;

/**
*
* @author Your name here
*/
public class StateMachine extends StateMachineBase {

    private Container searchDisplayContainer;
    private final int recordLength = 5;
    private ButtonGroup bg = new ButtonGroup();
    private RadioButton[] rdbs = new RadioButton[recordLength];

    public StateMachine(String resFile) {
        super(resFile);
    }

    /**
     * this method should be used to initialize variables instead of
     * the constructor/class scope to avoid race conditions
     */
    protected void initVars(Resources res) {
    }

    @Override
    protected void beforeMain(Form f) {
        searchDisplayContainer = findContainer1(f);

        for(int i=0;i<recordLength;i++){
            rdbs[i].setName("rdb"+i);
            rdbs[i].setText("rdb"+i);
            //add to button group
             bg.add(rdbs[i]);
             //add to container
            searchDisplayContainer.addComponent(rdbs[i]);

        }
    }
    @Override
    protected void onMain_ButtonAction(Component c, ActionEvent event) {
        System.out.println(bg.getSelectedIndex());
    }
   }

A: You need to create an instance of the ButtonGroup class and add the radio buttons to it in order to associate it to the other buttons in the group.


text:
Q: Saving Docker container state on Windows I create a docker container using
docker-machine.exe create -d virtualbox --virtualbox-memory 2048 default

and I logged into the bash using
docker run -ti ubuntu /bin/bash

and I got something like root@ae78cd536ddf:/# where I did a couple of apt-get installs.
Then, I exited from the bash and when I again logged back in I could not find what I had installed. I wanted to do a docker commit, but I somehow can't figure where my installed stuff is?
UPDATE
Based on the answers I tried creating an image of the container. I have compiled all commands in a gist.

A: With docker run, you create a container from the ubuntu image. The container has the name ae78cd536ddf (in your case). You can inspect images and containers with docker ps -a and docker images respectively.
Each time you run docker run, a new container is created. When using docker run --name Somename, you force the container to be named Somename which prevents you from creating another container with the same name.
Images are immutable which means you can not change them. So when you modify something in the running container, the image stays the same and this you can create more containers from the same image.
So after you stopped a container (docker stop, exit the containerized bash or just reboot), you can run docker start ae78cd536ddf to restart it. But it will be running in background and you won't have a bash (check docker ps to see it's running). Now you just need a bash: docker exec -it ae78cd536ddf /bin/bash will execute a bash in the container you started before.

Just a note about creating images. You might want to install the software you always need (I personally love vim, htop, ...) and then docker commit the container. This will create a new image which you can see in docker images. Now you can run containers from this image by replacing ubuntu with your image name.
To get more reproducable builds (when using a CI for example), you can create a Dockerfile and run docker build.

A: Every docker run command creates a new container. The id in the hostname of the bash shell is the container ID. You can commit that.
To see all containers (including stopped containers), do docker ps -a.


text:
Q: What do hats get me after winter bash is over?
the hats get put back in their boxes on January 4th

Do the hats affect me in any way after the 4th? A badge or something in my profile about how many I unlocked?
Edit: Can I request some form of persistence... please?

A: You'll have to roll your own memories.  Which you can do, and accumulate, from year to year, like this user has:

From that user's "about" text:

That is a Discraft Ultrastar 175g disc (a frisbee) (now wearing a football helmet from WinterBash 2014, a head of hair from WinterBash 2015, some kind of trophy thing from WinerBash 2016, and a baseball cap from WinterBash 2017).

Originally the user used that frisbee as the profile pic.  Then there was a WinterBash and it gained a football helmet.  And then it kept going.

A:
Can I request some form of persistence... please?"

Take a screen-shot of your hat-wearing avatar.
Save the screen-shot as an image file.
Use GIMP to create a new avatar icon from the screen-shot image; Then use it year-round.

A:
Do the hats affect me in any way after the 4th? A badge or something in my profile about how many I unlocked?

Well, only if you choose to put such information in your profile. More realistically, you get the sense of pride that you unlocked X many hats on Y many sites, and that you got to have a little fun on, of all sites, Stack Overflow.
It's fun! Have fun with it! If it lasted all the time, this wouldn't be nearly as special as it is. Besides, never fear -- we might even do this next year!

A: In all likelihood, nothing, except maybe fond memories. The Winter Bash FAQ has this to say:

After January 4th, the sites go back to normal and all hats disappear. This is meant to be a fun end-of-year celebration, not a permanent addition to the site.

Also, when we had the Hat Dash event at Arqade last year, we didn't get to keep anything either. Unlocked hats were displayed publicly on hatdash.com for a while, but eventually that was taken down and consigned to the promos archive.


text:
Q: Php increment Select query one by one In the code given below i am calling get.php?id=inc every time button is clicked Using Ajax.
I want that when every time this get.php is called select query fetch next record in table.
JavaScript File:
xmlhttp.open("GET","get.php?id=inc",true);
xmlhttp.send();

get.php File:
<?php
if(isset($_GET['nextq'])){ //nextq the name of button
$idd= $_GET['id'];
include 'library/php/connect.php';
$q = "SELECT * from hp_questions where id=$idd";
$q = mysqli_query($conn, $q);
while ($row = mysqli_fetch_array($q)){
echo
$row['question'];
}
?>


text:
Q: date picker in two different browsers i am workin on asp.net mvc in that i using partial views. i got one proble ie date picker is working properly on IE but it is not working on Mozilla Firefox. the i have used is:
<link href="<%=ResolveClientUrl("~/Scripts/Themes/ui-lightness/jquery-ui-1.7.2.custom.css")%>" rel="stylesheet" type="text/css" />

and the function on view page is:

                        <input id="txtTransationDate" name="txtTransationDate" type="text" />

please advice me for it. Thank in advance.

A: The code below works every time in each browser.

<title>test</title>

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/ui-lightness/jquery-ui.css" type="text/css"

rel="stylesheet">

Date Picker Test

<input id="txtTransationDate" name="txtTransationDate" type="text" value="Click here to show the date picker!" />

So lets examine the differences between your code and this one.

*

*First off, i'm using the Google CDN
for my js and css files this is
ensuring me in the context of the
test that my files are betting
loaded. It also makes it easier to
test ;)

*I'm also using jQuery 1.4.2 (latest
version) and 1.8.2 latest jQuery UI
version.

*The question is which version of
jQuery are you using? and are the
jQuery UI and jQuery versions
compatible together for each browser?

*Your css version 1.7.x this tends to
suggest that the jQuery UI version
you picked up could also be newer
than the jQuery version.

*I'm using the exact same JavaScript
and the same input tag (with added
attributes for the purpose of this
test).

*It seems obvious that the problem
does not reside in the js and html
you provided here.

*I'm also showing you my whole
context. Firefox is picky, IE also
but not on the same stuff. So would
it be possible that other js or
malformed tags are interfering in FF?
Try running my test in a static htm page. If it works the first thing I'd try would be changing the scripts in the head for the ones I'm using.
On an other note, if you don't want or can't use the Google CDN in your final app. I suggest to use these helper methods to include css and js files. Because it's hard to foresee all the possible url levels (/) a MVC application could have.
///
/// Include a javascript file.
///
/// <param name="path"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string IncludeJavascript(this UrlHelper url, string path)
{
    return "";
}

///
/// Include a css file.
///
/// <param name="path"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string IncludeStylesheet(this UrlHelper url, string path)
{
    return "<link href=" + url.Content(path) + " rel=\"stylesheet\" type=\"text/css\" />";
}

Usage:
<%= Url.IncludeJavascript("~/Scripts/jquery.js") %>
<%= Url.IncludeStylesheet("~/Scripts/Themes/jquery.css") %>


text:
Q: "latex it!" button (add-on for Thunderbird) not accessible? They say here that it works great after..

manually adding the "LaTeX it!" button

But how does on manually adds a "LaTeX it!" button?
without it there is no way to use this add-on. I'm
not sure this is a ubuntu specific issue so if you
know of a better outlet for asking this question,
please let me know.

A: found out:
The first time, you have to compose a new message,
right click on the new message toolbar,
click on customize
and drag the latexit button (which is now visible) to the message toolbar.
It'll stay there afterwards,


text:
Q: java.lang.OutOfMemoryError: Java heap space in allocating array size I am doing very small program in java using Eclipse Kepler IDE.
I am allocating the size of the array at run time using the following statement.
unSortedArray = new int[sizeRow][sizeColumn];

so as per my knowledge the java program runs with some of its own heap space like 32 MB.
And for my program i think this space is enough.
I just given the value sizeRow=3 and sizeColumn=3 at runtime.
And when i pressed enter it gives the following Exception java.lang.OutOfMemoryError: Java heap space
I put this question to understand why it happens and how we can handle it?
I already read the following link.
java.lang.OutOfMemoryError: Java heap space
How to deal with "java.lang.OutOfMemoryError: Java heap space" error (64MB heap size)
EDIT:1
public class ArraySort
{
private int[][]                 unSortedArray;
private int                     sizeColumn, sizeRow;

private final DataInputStream   dataInputStream = new DataInputStream(
                                                        System.in);

public boolean getArraySize() throws IOException
{
    try
    {
        System.out.print("Enter the size of the row:");
        sizeRow = (dataInputStream.readInt());
        System.out.print("Enter the size of the column:");
        sizeColumn = dataInputStream.readInt();
        return false;
    }
    catch (NumberFormatException e)
    {
        System.out.println("Enter valid value for size:");
    }
    return true;
}

public boolean getArrayElement() throws IOException
{
    unSortedArray = new int[sizeRow][sizeColumn];
    for (int i = 0; i < sizeRow; i++)
    {
        for (int j = 0; j < sizeColumn; j++)
        {
            try
            {
                System.out.println("Enter Element [" + i + "," + j + "]");
                unSortedArray[i][j] = dataInputStream.readInt();
            }
            catch (NumberFormatException ne)
            {
                System.out
                        .println("Enter proper Numeric value for Array Element");
                return true;
            }
        }
    }
    return false;
}
}

public class ArraySortProgram
{

public static void main(String[] args) throws IOException
{
    ArraySort arraySort = new ArraySort();

    arraySort.getArraySize();
    arraySort.getArrayElement();
}
}

In my case i am calling these method only once.

A: The problems is here:
dataInputStream.readInt()

This would read a binary value from your input which would be like 2323827382 for your entered "1251" causing the OOM.
Try to use Scanner to read your integers like this:
public class ArraySort{
    private final Scanner scanner = new Scanner(System.in);

    int sizeRow, sizeColumn;

    public boolean getArraySize() throws IOException
    {
        try
        {
            System.out.print("Enter the size of the row:");
            sizeRow = (scanner.nextInt());
            System.out.print("Enter the size of the column:");
            sizeColumn = scanner.nextInt();
            return false;
        }
        catch (NumberFormatException e)
        {
            System.out.println("Enter valid value for size:");
        }
        return true;
    }
    ...
}

A: If the offending code is as you have shown us, then there are possibilities:

*

*Previous to executing this statement, you have allocated other objects and you have consumed nearly all of the available space in doing so.  This statement is the proverbial straw that breaks the camel's back.

*The values of sizeRow and sizeColumn are NOT what you think they are.
We cannot distinguish between these two possibilities without seeing more of your code.

UPDATE - Andrey has found the problem, based on your updated code.  You are reading the sizes incorrectly, resulting in incorrect / very large size values.  That is causing your application to try to allocate a HUGE array of arrays ... which is giving the OOME.


text:
Q: Prevent the line discipline from handling control characters When you send a control character from the terminal, for example if you pressed Ctrl+C, the line discipline will receive the byte representing this control character (which is 0x03 in the case of Ctrl+C).
Now instead of the line discipline sending the byte 0x03 to the program associated with the terminal, it will instead send it the SIGINT signal (or it will do some other action if it is a different control character).
Now is there a way to prevent the line discipline from handling control characters, so what I want is for the program associated with the terminal to receive the actual bytes representing the control characters (0x03 in our case).

A: On linux, you'd use
$ stty intr undef

on the terminal concerned. That sets the interrupt character to nothing ("undef"). To restore you would use
$ stty intr ^c

See man stty for details.

A:
different control character […] control characters

I note the plural.  You are looking for non-canonical input mode, known before the POSIX standard as raw mode.  This is the mode that applications that use GNU Readline, or ZLE, or libedit employ.  Their code sets it with the tcgetattr(), cfmakeraw() and tcsetattr() library functions, or similar.  These are also the underpinnings of stty raw. (Note the existence of stty sane if you play with this.)
Further reading

*

*https://stackoverflow.com/a/39302351/340790

*POSIX terminal interface.  Wikipedia.

*cfmakeraw().  NetBSD Manual pages. 2004.


text:
Q: How to get a list of parents and children depending on the value of their children in Linq? I have two models, Category and ExternalResources:
Category
public partial class Category
{
    public long CategoryID { get; set; }
    public string Name { get; set; }
    public Nullable<long> ParentCategoryID { get; set; }

    public virtual ICollection<Category> Subcategories { get; set; }
    public virtual Category ParentCategory { get; set; }
    public virtual ICollection<ExternalResource> ExternalResources { get; set; }
}

ExternalResources
public partial class ExternalResource
{
    public string DisplayText { get; set; }
    public string URL { get; set; }
    public long CategoryID { get; set; }
    public int ExternalResourceID { get; set; }
    public bool SupportItem { get; set; }
    public bool IsInActivity { get; set; }

    public virtual Category Category { get; set; }
}

The variable called IsInActivity is the one I use to know whether to show on the list or not.
I want to show a list with the parents and just their childrens that has the variable IsInActivity set on true
I made a function that returns the parents that contains at least 1 child that has the value in true, but what I want is that it only returns the children that have IsInActivity in true.
public  List<Category> ContainsResources(List<Category> qry)
{
    List<Category> lstResourceIsInActivity =  qry.Where(p => p.ExternalResources.Any(c => c.IsInActivity = true)).ToList();

    return lstResourceIsInActivity;
}

Is there any way to do this with Linq?.
[UPDATED]
Already resolved my previous doubt, another doubt arose, in this case this returns the subcategories but not the parent categories if this has a subcategory(parent) with a selected child.
I made this function but it returns what I mentioned above:
public List<Category> ContainsResources(List<Category> qry)
{
            List<Category> lstResourceIsInActivity = qry.Where(c => c.ExternalResources.Any(r => r.IsInActivity)).Select(c => new Category
            {
                CategoryID = c.CategoryID,
                Name = c.Name,
                ParentCategoryID = c.ParentCategoryID,
                Subcategories = c.Subcategories.Where(b => b.ExternalResources.Any(r => r.IsInActivity) && b.ParentCategoryID != null).Select(b => new Category
                {
                    CategoryID = b.CategoryID,
                    Name = b.Name,
                    ParentCategoryID = b.ParentCategoryID,
                    ExternalResources = b.ExternalResources.Where(r => r.IsInActivity).ToList()
                }).ToList(),
                ParentCategory = c.ParentCategory,
                ExternalResources = c.ExternalResources.Where(r => r.IsInActivity).ToList()
            })
         .ToList();

            return lstResourceIsInActivity;
}

How to solve this with LinQ?

A: Assuming you don't want to actually modify the Category objects, you'll need to create new ones with the filtered resources in.
For example:
public List<Category> ContainsResources(List<Category> query) =>
    query.Where(c => c.ExternalResources.Any(r => r.IsInActivity))
         .Select(c => new Category
                 {
                     CategoryID = c.CategoryID,
                     Name = c.Name,
                     ParentCategoryID = c.ParentCategoryID,
                     ExternalResources = c.ExternalResources.Where(r => r.IsInActivity).ToList()
                 })
         .ToList();

Note that I haven't populated ParentCategory or Subcategories here. If you need those, you'll need to do significantly more work to make sure you keep referential integrity etc.

A: You can try this to reset your ExternalResources collections only to itens where IsInActivity == true:
public List<Category> ContainsResources(List<Category> qry)
{
    List<Category> lstResourceIsInActivity =  qry.Where(p => p.ExternalResources.Any(c => c.IsInActivity)).ToList();

    lstResourceIsInActivity.ForEach(c => c.ExternalResources = c.ExternalResources.Where(e => e.IsInActivity).ToList());

    return lstResourceIsInActivity;
}


text:
Q: htaccess how to support '/' have or haven't RewriteRule ^([^\/]*)/$ user.php?name=$1 [L,NC]
RewriteRule ^([^\/]*)/([^\/]*)/$ user.php?name=$1&a=$2 [L,NC]
RewriteRule ^([^\/]*)/([^\/]*)/([^\/]*)/$ user.php?name=$1&a=$2&id=$3 [L,NC]

My web site maybe 3 url format.
1. http://www.domain.com/user.php?name=tom
   http://www.domain.com/user.php?name=mary
   etc....

2. http://www.domain.com/user.php?name=tom&a=v
   http://www.domain.com/user.php?name=tom&a=photo
   etc....

3. http://www.domain.com/user.php?name=tom&a=v&id=9889
   http://www.domain.com/user.php?name=tom&a=photo&id=123
   http://www.domain.com/user.php?name=tom&a=data&id=123

Basically, there are only three values
I want url to be 301 url rewrite to domain.com/a/b/c/
These htaccess code is ok. but not perfect.
test1 :
not work
http://www.domain.com/tom    to->   http://www.domain.com/user.php?name=tom
work
http://www.domain.com/tom/   to->  http://www.domain.com/user.php?name=tom
test2 :
not work
http://www.domain.com/mary/v    to->  http://www.domain.com/user.php?name=mary&a=v
work
http://www.domain.com/mary/v/   to-> http://www.domain.com/user.php?name=mary&a=v
test3 :
not work
http://www.domain.com/kate/photo/123  to-> http://www.domain.com/user.php?name=kate&a=photo&id=123
work
http://www.domain.com/kate/photo/123/  to-> http://www.domain.com/user.php?name=kate&a=photo&id=123
I want user type the url more user friendly or more free
so, How to let them to work?? The user can type '/' or not, the same can succeed
http://www.domain.com/tom
http://www.domain.com/mary/v
http://www.domain.com/kate/photo/123
Anyone can give me some suggest? Or more clever code?
More one url rewrite question...   htaccess can set these link if haven't '/' auto add '/' ??

A: the question mark quantifier ? matches an occurrence of zero or one. Which is essentially 'The user can type '/' or not'
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^([^\/]+)/?$ user.php?name=$1 [L,NC]
RewriteRule ^([^\/]+)/([^\/]+)/?$ user.php?name=$1&a=$2 [L,NC]
RewriteRule ^([^\/]+)/([^\/]+)/([^\/]+)/?$ user.php?name=$1&a=$2&id=$3 [L,NC]

Note: this is not SEO friendly, because you are providing two urls for the same content.
If you don't want the user to be wrong when he types the forward slash, then you should redirect them to the non-forward slash url instead of serving them the content on that url.
EDIT:

But if user use not '/' come my site. can I use htaccess to send them to use '/'?

This Redirects the user from non trailing slash url to, urls with trailing slash
# add trailing slash, when not present
RewriteCond %{REQUEST_URI} !(/$)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]

# notice the ? is gone
RewriteRule ^([^\/]+)/$ user.php?name=$1 [L,NC]
RewriteRule ^([^\/]+)/([^\/]+)/$ user.php?name=$1&a=$2 [L,NC]
RewriteRule ^([^\/]+)/([^\/]+)/([^\/]+)/$ user.php?name=$1&a=$2&id=$3 [L,NC]

This is off the top of my head, so give it a try and let me know if it works

A: Use:
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([^\/]+)$ $1/ [R=301,L]
RewriteRule ^([^\/]+/[^\/]+)$ $1/ [R=301,L]
RewriteRule ^([^\/]+/[^\/]+/[^\/]+)$ $1/ [R=301,L]

RewriteRule ^([^\/]+)/?$ /user.php?name=$1 [L]
RewriteRule ^([^\/]+)/([^\/]+)/?$ /user.php?name=$1&a=$2 [L]
RewriteRule ^([^\/]+)/([^\/]+)/([^\/]+)/?$ /user.php?name=$1&a=$2&id=$3 [L]

With one / before user


text:
Q: How can I repeat a function in python 3? So here is my code:
membership_data = open("C:\\Users\\user\Desktop\Pre-release\membership_data.txt", "w")

def ValidateMemberID(MemberID):
    if len(MemberID) !=6:
        return("Wrong Format")
    elif MemberID[:1] == (MemberID[:1]).lower():
        return("Wrong Format")
    elif MemberID[1:3] == (MemberID[1:3]).upper():
        return("Wrong Format")
    elif (MemberID[3:]).isdigit() == False:
        return("Wrong Format")
    else:
        return("Correct Format")

def inputdata():
    Name = input("Please input member name")
    MemberID = input("Please input member ID")
    ValidateMemberID(MemberID)

    if ValidateMemberID(MemberID) == "Correct Format":
           NameID = [Name, MemberID, "\n"]

    else:
        print ("Invalid MemberID")

    membership_data.writelines(NameID)

for _ in range(5):
    do()
    inputdata(_)

membership_data.close

The issue I get is:
Traceback (most recent call last):
  File "C:\Users\user\Desktop\Pre-release\task_3.1.py", line 31, in <module>
    do()
NameError: name 'do' is not defined

What I want to do is to input 5 different records upon the first instance of my program. Essentially I need to run inputdata() for 5 times. However, my for in range do function keeps giving back this error. I tried different ways of writing it but to no avail.

A: I think you must delete 'do()' from your code
for x in range(5):

    inputdata()

membership_data.close()


text:
Q: Permanently change the background color of a pdf book from white to a gentle grey I'm reading a 800-page PDF book, and the white background color burns my eyes. I want to give it a grey shade, for instance this background color.
I'm looking to modify the file, as opposed to using a viewer that can adjust reading colors, because I already have a preferred viewer.
I found a 2015 answer that achieved it with something like this:
gs -o gray.pdf -sDEVICE=pdfwrite -g85x110 -c ".9 setgray 0 0 85 110 rectfill showpage"

pdftk book.pdf background gray.pdf output new-book.pdf

This works, however, it makes the file 3x larger in size, maybe it's adding a background to every single page. I wonder if there's a less hacky way to simply change the background color.

A:
"a preferred viewer"

usually may include that option, Acrobat, SumatraPDF, Okular (the widest set of choices) and several others do, its only browser inbuilt extensions may not.
This was mentioned by @mkl in a previous 2014 answer to a similar opposing question.

The backdrop is nominally white, although varying according to the actual properties of the medium. However, some conforming readers may choose to provide a different backdrop, ... https://stackoverflow.com/a/20946491/10802527

Intrigued that elsewhere you recommend SumatraPDF which has such an advanced options setting that can be switched at will from command line start (agreed it not that easy) via shortcuts.
Simpler as per OP comment

for Sumatra users who find this answer: an easier way is to go to Settings > Advanced Options, then change the "BackgroundColor =" value, to something like #eeeeee. – @ZYinMD

Many users ask how to alter between two states like an on off toggle so for those its easiest to set via command line or two+ shortcuts.

Works in version 3.3.3 but a short term issue with command line affects 3.4.0/1 (should be working again in 3.4.2 onward)
-set-color-range < text-hexcolor > < background-hexcolor >
so at end of a shortcut such as "C:\Program Files\SumatraPDF\SumatraPDF.exe" -set-color-range #------ #------
For natural colours you start with
-set-color-range #000000 #ffffff
For muted background colour you start with
-set-color-range #000000 #c0c0c0

But it will alter the full colour gamut. You can also use hotkey i to invert them.

Another 2 advanced background options are available for outside page boundary too.

A: You can use a BeginPage procedure with Ghostscript to initially fill the page with a colour, and then render the page contents. If you use the pdfwrite device as the output device then you can create a new PDF file where the background is non-white.
Make a text file on disk (eg gray.ps) with this content
%!
<<
/BeginPage
{
pop
0.9 setgray
0 0
currentpagedevice /PageSize get
aload pop rectfill
}
>> setpagedevice

Then invoke Ghostscript like this:
gs -sDEVICE=pdfwrite -o out.pdf gray.ps in.pdf

You should find that 'out.pdf' has the same content as in.pdf, but the page background is now a light gray. For a darker gray change the value of setgray from 0.9, 0 = black, 1.0 = white.
As I said, if the PDF file does something such as filling the entire page with white this will defeat the background painting, because it will overwrite the background. But I suspect that would defeat any trickery with viewer backgrounds too.
The resulting PDF in this case will work with any viewer since the PDF file now has the background 'built in'.


text:
Q: What effect does color on the upper and lower side of umbrella have? This question isn't referring to the general use of umbrella to provide protection from rain rather it concerns the optical effects of the color on lower and upper portion of umbrella.
Umbrella are also used to provide protection from sunlight (at least in regions below tropic of cancer in India) and usually they come in black color on the upper side and silvery on the lower side. What advantage does this provide? Is it just for fashion (I don't think so)? Currently I believe white is more advantageous  due to:

*

*white being a poor absorber of heat (via radiation) I it would cause the clothe to get less warm (than dark colors) and transmitt less radiation and hence providing higher protection.

*white being a good reflector would be beneficial in night (considering that somethimes rain occurs at night) as it would be more visible than dark colors.

A: Kirchhoff's law of thermal radiation says that the absorptivity and emissivity for a given wavelength are equal, so the silvery surface would emit less infra-red radiation.


text:
Q: Select data frame elements from multiple lists inside a list I have a list (IPCs) containing multiple data frames.
here is a sample from my list:
  $ http://www.sumobrain.com/patents/us/Measured-object-support-mechanism-for-unbalance-measuring-apparatus/4981043.html
:List of 1
..$ :'data.frame':  3 obs. of  5 variables:
.. ..$ X1: chr [1:3] "2001826A" "2857764A" "3452604A"
.. ..$ X2: chr [1:3] "1935-05-21" "1958-10-28" "1969-07-01"
.. ..$ X3: chr [1:3] "Russell et al." "Frank" "Schaub"
.. ..$ X4: chr [1:3] "73/478" "73/477" "73/475"
.. ..$ X5: chr [1:3] "Machine for balancing heavy bodies" "Rotor balance testing machine" "BALANCE TESTING APPARATUS HEAD"
$ http://www.sumobrain.com/patents/us/Encoder-with-wide-index/4982189.html
 :List of 1
..$ :'data.frame':  8 obs. of  5 variables:
.. ..$ X1: chr [1:8] "3500449A" "4212000A" "4233592A" "4524347A" ...
.. ..$ X2: chr [1:8] "1970-03-10" "1980-07-08" "1980-11-11" "1985-06-18" ...
.. ..$ X3: chr [1:8] "Lenz" "Yamada" "Leichle" "Rogers" ...
.. ..$ X4: chr [1:8] "341/6" "341/16" "341/6" "341/3" ...
.. ..$ X5: chr [1:8] "ELECTRONIC ENCODER INDEX" "Position-to-digital encoder" "Method for detection of the angular position of a part driven in rotation and instrumentation using it" "Position encoder" ...
$ http://www.sumobrain.com/patents/us/Device-for-detecting-at-least-one-variable-relating-to-the-movement-of-a-movable-body/4982106.html
:List of 1
..$ :'data.frame':  2 obs. of  5 variables:
.. ..$ X1: chr [1:2] "3956973A" "4797564A"
.. ..$ X2: chr [1:2] "1976-05-18" "1989-01-10"
.. ..$ X3: chr [1:2] "Pomplas" "Ramunas"
.. ..$ X4: chr [1:2] "92/5R" "307/119"
.. ..$ X5: chr [1:2] "Die casting machine with piston positioning control" "Robot overload detection mechanism"

I would like to select only the first and fifth elements (X1 and X5) from all data frames, to later construct a further dataset with only these two elements.
I have tried to grab X1 with this:
citations_IPC <- sapply(IPCs, function(x){
y<-x[,1]
return(y)
})

and X5 with:
citations_titles <- sapply(IPCs[[1]], function(z){
e<-z[,5]
return(e)
})

Then I convert citations_IPCs and citations_titles into a single data frame with:
citation_list <-  data.frame(IPC = unlist(lapply(citations_IPC, paste)), title = unlist(lapply(citations_titles, paste)) )

1#problem
If I write the sapply function on an individual list (e.g. IPCs[[1]]) I get the result I want:
citations_IPC <- sapply(IPCs[[1]], function(x){
y<-x[,1]
return(y)
})

result:
> citations_IPC
      [,1]
 [1,] "3415985A"
 [2,] "3916190A"
 [3,] "4088895A"
 [4,] "4633084A"
 [5,] "4670651A"
 [6,] "4860224A"

However, this function doesn't work for the whole lists (IPCs).
The error I get is:
       "Error in x[, 1] : incorrect number of dimensions"
I am guessing the problem might be due to a few lists within my dataset with no data frame, no observations and no variables. In that case I would need a function which allows me to use the sapply() on the dataset despite the lines without data frame.
Please any suggestions would be really appreciated.
Many thanks
str(IPCs)
> str(IPCs)
 List of 19
 $ http://www.sumobrain.com/patents/us/Method-and-apparatus-for-the-quantitative,-depth-differential-analysis-of-solid-samples-with-the-use-of-two-ion-beams/4982090.html       :List of 1
  ..$ :'data.frame':    6 obs. of  5 variables:
  .. ..$ X1: chr [1:6] "3415985A" "3916190A" "4088895A" "4633084A" ...
  .. ..$ X2: chr [1:6] "1968-12-10" "1975-10-28" "1978-05-09" "1986-12-30" ...
  .. ..$ X3: chr [1:6] "Castaing et al." "Valentine et al." "Martin" "Gruen et al." ...
  .. ..$ X4: chr [1:6] "250/309" "250/309" "250/309" "250/309" ...
  .. ..$ X5: chr [1:6] "Ionic microanalyzer wherein secondary ions are emitted from a sample surface upon bombardment by neutral atoms" "Depth profile analysis apparatus" "Memory device utilizing ion beam readout" "High efficiency direct detection of ions from resonance ionization of sputtered atoms" ...
 $ http://www.sumobrain.com/patents/us/Set-on-oscillator/4982165.html
 :List of 1
  ..$ :'data.frame':    2 obs. of  5 variables:
  .. ..$ X1: chr [1:2] "4437066A" "4558282A"
  .. ..$ X2: chr [1:2] "1984-03-13" "1985-12-10"
  .. ..$ X3: chr [1:2] "Gordon" "Lowenschuss"
  .. ..$ X4: chr [1:2] "328/14" "307/523"
  .. ..$ X5: chr [1:2] "Apparatus for synthesizing a signal by producing samples of such signal at a rate less than the Nyquist sampling rate" "Digital frequency synthesizer"
 $ http://www.sumobrain.com/patents/us/Voltage-measuring-apparatus/4982151.html
 :List of 1
  ..$ :'data.frame':    7 obs. of  5 variables:
  .. ..$ X1: chr [1:7] "3419802A" "3419803A" "4446425A" "4603293A" ...
  .. ..$ X2: chr [1:7] "1968-12-31" "1968-12-31" "1984-05-01" "1986-07-29" ...
  .. ..$ X3: chr [1:7] "Pelenc et al." "Pelenc et al." "Valdmanis et al." "Mourou et al." ...
  .. ..$ X4: chr [1:7] "324/96" "324/96" "" "" ...
  .. ..$ X5: chr [1:7] "Apparatus for current measurement by means of the faraday effect" "Apparatus for current measurement by means of the faraday effect" "Measurement of electrical signals with picosecond resolution" "Measurement of electrical signals with subpicosecond resolution" ...

A: Here is an example:
First lets make a list with some random iris columns:
data(iris)
lis = list(iris[1:3], iris[2:4])

using lapply with a custom function to extract columns 1 and 2 from each data frame. If they are not named the same force a rename of the columns for the next step:
b = lapply(lis, function(x){
  z = x[,c(1,2)]
  colnames(z) = c("z1", "z2")
  return(z)
}
)

Now b is a list of only the columns you wish.
rbind the data frames in b:
do.call(rbind, b)

done

A: Here is a way to do what I understand of your question.
First some fake data.
op <- options(stringsAsFactors = FALSE)  # to make sure we have characters not factors
set.seed(9506)

nr <- c(6, 2, 7)
IPCs <- lapply(1:3, function(n){
        res <- as.data.frame(replicate(5, sample(LETTERS, nr[n], TRUE)))
        names(res) <- paste0("X", 1:5)
        res
})
names(IPCs) <- paste0("df", seq_along(dat))
str(IPCs)
options(op)   # put it back as it was

Now the code to extract the 1st and 5th columns of each data.frame and paste them together in order to form a df.
result <- list(
    sapply(IPCs, `[[`, 1),
    sapply(IPCs, function(x) x[[ncol(x)]])
)
result <- as.data.frame(lapply(result, function(x) sapply(x, paste, collapse = "")))
names(result) <- c("citations_IPC", "citations_titles")
result


text:
Q: Canvas splitting image into rgba components I'm trying to split a black and white image into its RGB components and offset each layer setting it to overlay. The idea is to have a hero image slightly out of register and randomly move it slightly.
I am wondering if this is in fact the correct way to approach this.
I tend to crash the browser if I dare add a console log in the function to see where I am going wrong.
Has anyone done this kind of manipulation in the browser and is it viable?
https://github.com/Julieslv/image-shift/blob/master/index.js

A: Splitting image into RGBA channels
First note that you can not separate the channels from an image. You can only set the unwanted channels to zero. However setting the alpha channel to zero will automatically zero all channels. Thus you must keep the alpha channel.
Copy image
To copy an image create a second canvas and draw the original image onto it.
The following function will do that
function copyToCanvas(image) {
    const can = document.createElement("canvas");
    can.width = image.naturalWidth || image.width;
    can.height = image.naturalHeight || image.height;
    can.ctx = can.getContext("2d");
    can.ctx.drawImage(image, 0, 0);
    return can;
}

Removing channel data
Two remove the unwanted channel data from a image copied by the previous method requires two steps.

*

*Use composite operation "multiply" to remove unwanted channel data.

*The above step will set the alpha channel to 255. To put the alpha back you use the composite operation "destination-in" and draw the original image over the new image.

The following function will copy the image, remove unwanted channel data and keep the alpha channel intact.
const channels = {
   red: "#F00",
   green: "#0F0",
   blue: "#00F",
};

function getChannel(channelName, image) {
    const copy = copyToCanvas(image);
    const ctx = copy.ctx;
    ctx.fillStyle = channels[channelName];
    ctx.globalCompositeOperation = "multiply";
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.globalCompositeOperation = "destination-in";
    ctx.drawImage(image, 0, 0);
    ctx.globalCompositeOperation = "source-over";
    return copy;
}

Getting RGB channels
As the alpha channel is maintained you need only separate out red green and blue channels.
Using the previous function the following will create an object the holds the original image and the 3 channels
 function seperateRGB(image) {
     return {
         red: getChannel("red", image),
         green: getChannel("green", image),
         blue: getChannel("blue", image),
     };
 }

Recombining channels
Now that the channels have been separated you can recombine channels by first making a new canvas the same size as the original image plus any offsets you are adding as you recombine the image (if you are not adding back alpha).
function createCanvas(w, h) {
    const can = document.createElement("canvas");
    can.width = w;
    can.height = h;
    can.ctx = can.getContext("2d");
    return can;
}

Then draw the first channel (can be any of the 3) onto the new canvas. Then draw the other two channels using the composite operation "lighter". Then restore alpha using composite operation "destination-in"
const RGB = seperateRGB(image);
const recombined = createCanvas(RGB.red.width, RGB.red.height);
const ctx = recombined.ctx;

ctx.drawImage(RGB.red, -2, -2);
ctx.globalCompositeOperation = "lighter";
ctx.drawImage(RGB.green, 0, 0);
ctx.drawImage(RGB.blue, 2, 2);
ctx.globalCompositeOperation = "destination-in";
ctx.drawImage(image, 0, 0);
ctx.globalCompositeOperation = "source-over";

All done
The canvas element recombined holds the recombined image with the green and blue channels offset by 2 pixels and the original alpha restored.
Note that you do not need to restore the alpha. Restoring the alpha if some channels are offset will remove some of the non overlapping pixels.


text:
Q: wordpress functions, PHP not processing, showing as plain text      <?php
global $current_user;
get_currentuserinfo();

printf( __( 'Username: %s', 'textdomain' ), esc_html( $current_user->user_login ) ) . '
';
printf( __( 'User email: %s', 'textdomain' ), esc_html( $current_user->user_email ) ) . '
';
printf( __( 'User first name: %s', 'textdomain' ), esc_html( $current_user->user_firstname ) ) . '
';
printf( __( 'User last name: %s', 'textdomain' ), esc_html( $current_user->user_lastname ) ) . '
';
printf( __( 'User display name: %s', 'textdomain' ), esc_html( $current_user->display_name ) ) . '
';
printf( __( 'User ID: %s', 'textdomain' ), esc_html( $current_user->ID ) );

I am ultimately trying to do more than the above, but for now I am just trying to start simple since I was having trouble.
I am unable to get this to display processed; it shows as plain text when placed in a code or text module using divi builder or even in the text view of the basic wordpress page editor.
So in the end, I will have custom fields in the user meta table that i will need to print to screen in emails to send to users as well as in a table on my website.
Thank you in advance!
I've seen things like php anywhere plugins but that seems unsafe. Also have seen php shortcode managers, but im not sure i want to go that route or if that would work when building tables.


text:
Q: Sanity intl plugin / Allow GraphQL to query __i18n_lang by removing the underscores from field name GraphQL ignores fields that start with double underscore __i18n_lang and I cant query the language from Sanity. The Sanity Intl plugin has already a solution how to replace the name but the Docs are not very friendly for a Sanity beginner like me.
Please help me implement this code on my Sanity studio.
OR
help me create a new field lang that automatically gets the value of __i18n_lang using sanity api.


text:
Q: Codename one GPS provider and current location I am working on an iOS app with codename one. I want to get the current location and send it by SMS.
I got this code from Java Android Studio, I don't know how to get the current location and also check if GPS is turned on.
I tried below, but without success (I'm not sure how they start the GPS and get the location)
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabledGPS) {
   //alert GPS is off
}
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);

// Initialize the location fields
if (location != null) {
    Toast.makeText(this, "Provider: " + provider, Toast.LENGTH_SHORT).show();
    onLocationChanged(location);
} else {
    //do something
}

The onLocationChanged method:
try {
    StringBuffer smsBody = new StringBuffer();
    smsBody.append("http://maps.google.com/?q=");
    smsBody.append(gpsLocation.getLatitude());
    smsBody.append(",");
    smsBody.append(gpsLocation.getLongitude());

    String phnum="xxxxx";
    String smsbod= smsBody.toString();

    Display.getInstance().sendSMS(phnum,smsbod);
} catch (IOException ex) {
    Dialog.show("Error!", "Failed to start.  installed?", "OK", null);
    ex.printStackTrace();
}

A: You can't start the GPS in codenameone, you can only check if it's turned on and display a message if it's not.
Try the code below:
//Check if location is turned on and your app is allowed to use it.
if (Display.getInstance().getLocationManager().isGPSDetectionSupported()) {
    if (Display.getInstance().getLocationManager().isGPSEnabled()) {
        InfiniteProgress ip = new InfiniteProgress();
        final Dialog ipDlg = ip.showInifiniteBlocking();
        //Cancel after 20 seconds
        Location loc = LocationManager.getLocationManager().getCurrentLocationSync(20000);
        ipDlg.dispose();
        if (loc != null) {
            double lat = loc.getLatitude();
            double lng = loc.getLongitude();
            try {
                Display.getInstance().sendSMS("09123456789", "http://maps.google.com/?q=" + lat + "," + lng, false);
            } catch (IOException ex) {
                Dialog.show("Error!", "Failed to start.  installed?", "OK", null);
                ex.printStackTrace();
            }
        } else {
            Dialog.show("GPS error", "Your location could not be found, please try going outside for a better GPS signal", "Ok", null);
        }
    } else {
        Dialog.show("GPS disabled", "AppName needs access to GPS. Please enable GPS", "Ok", null);
    }
} else {
    InfiniteProgress ip = new InfiniteProgress();
    final Dialog ipDlg = ip.showInifiniteBlocking();
    //Cancel after 20 seconds
    Location loc = LocationManager.getLocationManager().getCurrentLocationSync(20000);
    ipDlg.dispose();
    if (loc != null) {
        double lat = loc.getLatitude();
        double lng = loc.getLongitude();
        try {
            Display.getInstance().sendSMS("09123456789", "http://maps.google.com/?q=" + lat + "," + lng, false);
        } catch (IOException ex) {
            Dialog.show("Error!", "Failed to start.  installed?", "OK", null);
            ex.printStackTrace();
        }
    } else {
        Dialog.show("GPS error", "Your location could not be found, please try going outside for a better GPS signal", "Ok", null);
    }
}


text:
Q: css file not working on the wordpress child theme hello i have a problem with css in my child theme its not working  this is the code i use in functions.php
the problem is the style in file app.css is not applying in the page but when i move the same css to the costomize ( additionnal css) its working perfectely.
if (!function_exists('succulents_qodef_child_theme_enqueue_scripts')){

    function succulents_qodef_child_theme_enqueue_scripts() {

        $parent_style = 'succulents-qodef-default-style';

         wp_enqueue_style( 'customstyle', get_stylesheet_directory_uri() . '/app.css');
        wp_enqueue_style('succulents-qodef-child-style', get_stylesheet_directory_uri() . '/style.css', array($parent_style));
            // wp_enqueue_style('succulents-custom', get_stylesheet_directory_uri() . '/app.css', array($parent_style));

    }

    add_action( 'wp_enqueue_scripts', 'succulents_qodef_child_theme_enqueue_scripts' );
}

when i see the code source of the page i can see the app.css but for some reason its not applying


text:
Q: Window.open with 'noopener' opens a new window instead of a new tab I was using window.open('') with '_blank' as second parameter to open my link in new tab For eg. window.open('http://google.com', '_blank')
But, recently I added the third parameter 'noopener' so that window.opener becomes null in the new tab and the new tab does not have access to the parent tab/window. i.e. window.opener is null
window.open('http://google.com', '_blank', 'noopener')
So the above code solved the security problem, but instead of opening a new tab, a new window started opening which is not what I expected. My browser settings were same and no changes were made to it.
Is there anything I can do to make this code open new tab instead of new window ? I do not want to remove noopener as third parameter

A: Honestly i think your code is fine but you can try a different implementation:
var yourWindow = window.open();
yourWindow.opener = null;
yourWindow.location = "http://someurl.here";
yourWindow.target = "_blank";

A:
https://mathiasbynens.github.io/rel-noopener/

const anchor = document.createElement('a');

Object.assign(anchor, {
  target: '_blank',
  href: 'http://google.com',
  rel: 'noopener noreferrer'
})
.click()

This is the method which feels a bit cleaner. It creates an anchor tag and clicks it, we have to use this workaround as its a user preference.

A: This is the only thing that works cross-browser (IE11, Chrome 66, FF 60, Safari 11.1) for me

function openURL(url) {
  var link = document.createElement('a');
  link.target = "_blank";
  link.href = url;
  link.rel = "noopener noreferrer";
  document.body.appendChild(link); // you need to add it to the DOM to get FF working
  link.click();
  link.parentNode.removeChild(link); // link.remove(); doesn't work on IE11
};

A: Another approach that will solve this in one line is to access the opener property directly and set it to null to make use of the fact that window.open() returns a Window object. This will work across all browsers to open a new tab with a null window.opener.
window.open(url, '_blank').opener = null;


text:
Q: boot Debian default kernel with lilo results in kernel panic I have server with Debian 10 installed.
I am using custom kernel, with lilo boot loader. This is my /etc/lilo.conf:
boot=/dev/sda
root=/dev/sda1
map=/boot/map

lba32

prompt
timeout=50

default=linux

image=/boot/vmlinuz-5.10.46
label=Linux
read-only
append="rootfstype=ext4 net.ifnames=0 loglevel=4 console=tty0 2"

Now I want to boot the default Debian distribution kernel. I have installed the debian kernel image:
apt-get install linux-image-amd64

and added the entry to /etc/lilo.conf:
image=/boot/vmlinuz-4.19.0-17-amd64
label=4.19.0-17-amd64
initrd=/boot/initrd.img-4.19.0-17-amd64
read-only
append="rootfstype=ext4 net.ifnames=0 loglevel=4 console=tty0 2"

However, when I boot this kernel, I get kernel panic.

How can I boot default debian distribution kernel with lilo?


text:
Q: Trying to read bitmap file as hexadecimals #include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define NBRCOLOURS 16
#define COLOURSIZE 8

typedef struct
{
    char colours[COLOURSIZE];

}BITMAP;

//Main Function
void main(void)
{
    int count, count2;
    char bm_file[] = "C:\\Coding\\Bitmap Program\\Sample.bmp";
    FILE *fptr;
    char ch;
    int i = 0;
    BITMAP bm_data[NBRCOLOURS];

    fptr = fopen(bm_file, "rb");
    if (fptr != NULL)
    {
        while ((ch = fgetc(fptr)) != EOF)
        {
            printf("%02X ", ch);
            if (!(++i % 16)) putc('\n', stdout);
        }
    }

    fclose(fptr);

    system("pause");
    return;
}

I am using this code which I found mostly online to try and read the contents of a bitmap file as its hexadecimal values.  For some reason, this code stops right at the end of the header, and unfortunately ultimately I need to count the number of times each colour appears so that I can figure out which occurs most and which occurs least.
If anyone could tell me why this code stops at the end of the header for the bitmap, or lead me towards being able to pull the rest of the hexadecimal data out of the file, I would really appreciate it.
Here is the hex code:
42 4D C6 00 00 00 00 00 00 00 76 00 00 00 28 00
00 00 0A 00 00 00 0A 00 00 00 01 00 04 00 00 00
00 00 50 00 00 00 12 0B 00 00 12 0B 00 00 10 00
00 00 10 00 00 00 FF 00 00 00 00 FF 00 00 00 00
42 00 5A 5A 84 00 00 00 FF 00 FF 00 FF 00 00 FF
FF 00 08 FF FF 00 5A FF FF 00 FF FF FF 00 FF FF
FF 00 FF FF FF 00 FF FF FF 00 FF FF FF 00 FF FF
FF 00 FF FF FF 00 92 59 00 16 47 00 00 00 25 90
01 64 61 00 00 00 59 90 11 64 61 00 00 00 99 00
16 48 11 00 00 00 90 01 64 61 11 00 00 00 00 16
64 61 00 00 00 00 01 16 46 10 09 00 00 00 11 64
41 00 99 00 00 00 16 64 11 09 95 00 00 00 66 48
10 09 53 00 00 00

And here is what prints:
42 4D FFFFFFC6 00 00 00 00 00 00 00 76 00 00 00 28 00
00 00 0A 00 00 00 0A 00 00 00 01 00 04 00 00 00
00 00 50 00 00 00 12 0B 00 00 12 0B 00 00 10 00
00 00 10 00 00 00

Long post, I'm sorry. Any help is greatly appreciated.

A: fgetc returns an int, not a char.  You can't represent EOF with a char, as all of the possible values of a char are valid.  EOF is (I think) -1 represented as an int, or 0xfffffff, so if you read 0xff as a char it's the same as EOF.
Change this:
char ch;

to:
int ch;

A: The number before a format specifier in printf, like %02X only guarantees a minimum number of characters outputted, not a maximum. fgetc returns an int, not a char.  If the int is negative two's complement then the entire bitstring representing the int will get printed, including the FF bytes at the start.  EOF is not representable as a char; only as an int.
In your case we know that the file we're working with is small enough that loading the entire file into a buffer will probably succeed, so we can just use malloc and free instead:
#include <stdio.h>
#include <stdlib.h>

typedef unsigned char byte;

int main(int argc, char *argv[])
{
    FILE *fp = fopen("C:\\Coding\\Bitmap Program\\Sample.bmp", "rb");
    byte *buffer = NULL;
    size_t len;
    int i;

    fseek(fp, 0, SEEK_END);

    len = ftell(fp);
    rewind(fp);

    buffer = malloc(len);
    if(!buffer)
    {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    fread(buffer, 1, len, fp);
    fclose(fp);
    for(i = 0; i < len; i++)
    {
        if(i%16==0) putchar('\n');
        printf("%.2X ", buffer[i]&0xFF);

    }
    free(buffer);
    return 0;
}


text:
Q: how can i make a drop down menu using lists This is my html and css. I want to make a drop down menu on hover but i cannot call the respective class. If anyone can help me with this. I would really appreciate it. and i don't want to use javascript. I only want the solution in css. P.S: I am using
a template for my website .I just need help in calling the header class.

#navigation .navbar {
  background: rgba(255, 255, 255, 0.952941);
  border-radius: 0;
  border-bottom: 0;
  box-shadow: rgba(0, 0, 0, 0.298039) 0px 0px 3px;
  padding-bottom: 8px;
}

#navigation .navbar-toggle {
  margin-top: 20px;
  background-color: #333;
}

#navigation .navbar-brand h1 {
  padding: 0;
  margin: 0;
}

#navigation .navbar-nav.navbar-right li {
  padding: 0 1px;
}

#navigation .navbar-nav.navbar-right {
  margin-top: 28px
}

#navigation .navbar-nav.navbar-right li a {
  color: #43484E;
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  padding: 0;
  text-transform: uppercase;
  -webkit-transition: all .9s ease 0s;
  -moz-transition: all .9s ease 0s;
  -o-transition: all .9s ease 0s;
  transition: all .9s ease 0s;
  padding: 6px 15px;
}

#navigation .navbar-inverse .navbar-nav .active a,
#navigation .navbar-inverse .navbar-nav .active a:focus,
#navigation .navbar-nav.navbar-right li a:hover {
  color: #fff;
  background-color: #ce181e;
}

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
          Toggle navigation
        </button>

About Us

Academics

Admissions

Campuses

Student Life

News & events

Careers

Contact

code

A: H! Using your initial setup a simple css-only dropdown menu can be made by placing a nested ul with options into an li and adding these styles:
#navigation .navbar-nav.navbar-right li ul {
    padding: 0;
    display: inline-block;
}
#navigation .navbar-nav.navbar-right li {
    list-style: none;
}
#navigation .navbar-nav.navbar-right li ul li:not(:first-of-type) {
    display: none;
}
#navigation .navbar-nav.navbar-right li ul:hover li {
    display: block;
}
#navigation .navbar-nav.navbar-right li {
    padding: 5px;
}

#navigation .navbar {
  background:rgba(255, 255, 255, 0.952941);
  border-radius: 0;
  border-bottom: 0;
  box-shadow: rgba(0, 0, 0, 0.298039) 0px 0px 3px;
  padding-bottom: 8px;
}

#navigation .navbar-toggle{
  margin-top: 20px;
  background-color: #333;
}

#navigation .navbar-brand h1{
  padding: 0;
  margin: 0;
}

#navigation .navbar-nav.navbar-right {
 margin-top:28px
}
/* added styles start */
#navigation .navbar-nav.navbar-right li ul {
    padding: 0;
    display: inline-block;
}
#navigation .navbar-nav.navbar-right li {
    list-style: none;
}
#navigation .navbar-nav.navbar-right li ul li:not(:first-of-type) {
    display: none;
}
#navigation .navbar-nav.navbar-right li ul:hover li {
    display: block;
}
#navigation .navbar-nav.navbar-right li {
 padding: 5px;
}
/* added styles end */
#navigation .navbar-nav.navbar-right li a {
 color: #43484E;
 font-family: 'Roboto',sans-serif;
 font-size: 14px;
 padding: 0;
 text-transform: uppercase;
 -webkit-transition: all .9s ease 0s;
 -moz-transition: all .9s ease 0s;
 -o-transition: all .9s ease 0s;
 transition: all .9s ease 0s;
 padding: 6px 15px;
}

#navigation .navbar-inverse .navbar-nav  .active  a,
#navigation .navbar-inverse .navbar-nav  .active  a:focus,
#navigation .navbar-nav.navbar-right li a:hover {
 color: #fff;
 background-color: #ce181e;
}

     <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      Toggle navigation
     </button>

Academics

About Us0

About Us1

About Us2

About Us3

Admissions

Campuses

Student Life

News & events

Careers

Contact

So, I hope you got the idea and now you can play around to achieve what you want. You may check some material on positioning needed to create more complex layouts.


text:
Q: Is it possible to integrate Vaadin with Rails??? If so, how? As i see Vaadin is a Java based UI framework. But it has some really nice set of widgets and a very good layout engine. Is it possible to integrate Rails and Vaadin? JSON perhaps??

A: It sounds like that'd take a lot of work creating an interface between them which will likely only slow things down. By the time you had everything working the way you wanted you could've finished what you wanted in Rails or Vaadin separately.
If you did make an interface, JSON is the way to go. Lightweight and almost everything supports it with little overhead.

A:
is there any alternative to javascript based frameworks?? other than the usual ones (jquery, prototype, sproutcore

Just pointing out, that all rich UI frameworks that run in the browser are JavaScript in the end (not including any plugins like Flash), even Vaadin, which is built on top of GWT on the client side.
I guess you'll have to consider integrating with the Rails backend either on the server side (e.g. with a Vaadin Java servlet) or on the client side with a custom data exchange over HTTP (using JSON) and using some client side framework like GWT, SproutCore, Cappuccino etc.


text:
Q: View existing filters in Cognos 7 (Impromptu) I'm converting some Cognos 7 Impromptu reports into Cognos 8 by recreating them from scratch.
The one thing I'm not sure about are Filters; when I look at Cognos 8 filters I can clearly see where existing filters are. But looking at the Query -> Filter tab in Cognos 7 I can't tell where I would look for existing filters. I can see how to create them, but not view them:

Where do I check for existing filters and their definitions in Cognos 7? I don't need to add/alter them, I just need to see which ones exist (and be able to tell when none exist) and see their corresponding definition.

A: It seems that is the box, any and all filters in Cognos 7 appear to always be in this same text box. Multiple conditions must be chained in the one text field.

I as confused because Cognos 8 splits Filters into "things" which can have more than one condition:

A: You may also want to check the summary filters in Impromptu - change the filter type drop-down to 'Summary.


text:
Q: What is the current going into a resistor-capacitor parallel circuit and the current coming out of it? I'm looking at the circuit below and know that I1 = I2. Can someone explain why those 2 currents are the same?

A: Just apply Kirchoff's current law at the two nodes: $$i_1=i_R+i_C$$$$i_R+i_C=i_2$$ Then combine to get $$i_1=i_2$$

A: Kirchoff's Current Law applies to any isolated part of a circuit. So, draw a box around R and C, and insist that the total current into the box is zero.

A: It might appear that because there is a charge storing device, the capacitor, the two current can be different and a difference in the currents results in the charge stored in the capacitor to change.
However the fact is that the net charge on the capacitor is zero in that a change in positive charge on one plate is always equal in magnitude to the change in negative charge on the other plate.
Since there is no net change in the charge stored in the capacitor the two currents must be equal which, of course, you would expect by applying Kirchhoff's current law to the circuit.