text:
Q: Android/Java - Issue The code is like this:
private DatabaseHelper mOpenHelper;
@Override
public boolean onCreate() {
  mOpenHelper = new DatabaseHelper(getContext());
  System.out.println("done");
  return true;
}

Now Eclipse is showing me an error warning on the first line of this code "private DatabaseHelper mOpenHelper", that the object mOpenHelper is not used anywhere, whereas in the very next lines of code, I am initializing it. Please tell me why is this happening?
Thanks,
-D

A: Yes eclipse is right, You have initialized it and not using it anywhere. It would not complain if you use that mOpenHelper say in a getter method.

A: The warning doesn't say not be USED anyone, it's saying not being READ anywhere. And it's not. You're declaring it, assigning it, but not reading it.


text:
Q: Unexpected character in input: '\' (ASCII=92) state=1 My client says he is getting this error using my script:
Warning: Unexpected character in input: '\' (ASCII=92) state=1 in /path/to//header.php  on line 34
Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or '(' in/path/to/header.php  on line 34

The line 34 in header.php is just use \Main\Class;
Now, I told him he has to have PHP >= 5.3.0 and he says his PHP version is 5.3.24
What could be the problem?
EDIT: The lines before and after
30. // Define absolute path
31. define("ABSPATH", $abs_path);
32. $_SESSION["abs_path"] = ABSPATH;
33.
34. use \CNS\main\CNS;
35. $cns = new CNS();

EDIT 2:
He sent me this:
Program     Version
Apache:     2.2.24
CentOS:     CentOS release 6.4 (Final)
cPanel:     11.36.1 (build 8)
Curl:       7.12.1
MySQL       5.5.30
phpMyAdmin  3.5.5
Python:     2.6.6
Program     Version
Perl:       5.8.8
**PHP:        5.3.24**
ionCube Loader:     4.2.2
Zend Optimizer:     3.3.9
Ruby:       1.8.7
Rails:      3.2.8
OpenSSL:    1.0.0-fips

A: This happens if you are trying to use namespaces but do not have PHP 5.3. PHP 5.2 and below don't support namespaces and throw this error when they see the backslash.
--
Edit: mixed up the versions. It's 5.2 and below that don't have namespaces, if I'm not mistaken.

A: If you get 'unexpected T_STRING' error after your mentioned error, you need to install PHP 5.4+

A:
Now, I told him he has to have PHP >= 5.3.0 and he says his PHP version is 5.3.24
What could be the problem?

His PHP version is actually < 5.3.0, whether he knows that or not.
See the error occurring on many PHP versions.

A: Ask him to create a file with phpinfo(). He probably doesn't have PHP version >= 5.3.0.

A: <FilesMatch "\.(inc|php|php3|php4|php44|php5|php52|php53|php54|php55|php56|phtml|phps)$">

 AddHandler x-httpd-php53 .php

</FilesMatch>

in .htaccess

A: Like other users say: use of namespaces are only valid for PHP versions greater than 5.3.0 so my solution for be able to include an optional use of a library using namespaces is to check the php version and use the eval() function to avoid that lower versions of PHP shoot an error, even on compilation time.
Something like this:
if ( phpversion() > '5.3.0' ){
    include_once('/path/to/Library.php');
    eval("Library\Foo::bar();");
}

A: I ran the same problem, and doing some research I managed to fix it.
In my case, I use PHP7, and what I had to do is edit the file laravel located in ~/.composer/vendor/laravel/installer/, where the shebang line was #!/usr/bin/env php I changed to #!/usr/bin/env php7
After run again the artisan, I got it working:
-bash-3.2$ laravel
Laravel Installer version 1.3.3

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  help  Displays help for a command
  list  Lists commands
  new   Create a new Laravel application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Applying a scaling factor to decimal data so it can be stored in decimal format I am using some processing software that produces radiance data from digital numbers.
I can apply a radiance multiplier with this software which is a scaling factor used for storing decimal radiance values in integer format. The default scaling value is 10000. Why would you do this? What is the advantage of integer over decimal formats?


text:
Q: How to interconnect the LAN of two houses
Possible Duplicate:
Connecting networks for two buildings

I want to interconnect the LAN of two houses. They are just across each other on the same street.
With WLAN I had a quite high network latency.
Are there faster, inexpensive alternatives?

A: So you want to have one Internet connection in one house and share that connection with another house.
If I read your question correctly, it sounds like you have tried this and have some latency problems.
I assume you have a wireless router in the home (A) with the Internet connection and wireless devices in the other house (B). And I assume the distance between the two houses is perhaps 250 feet or less.
The latency could be caused by interference and low signal strength causing failed data transmissions requiring many retries for each successful data transmission.
First, make sure the specs on the router indicate it should work for the distance you are dealing with (probably not the issue, but check anyway). Perhaps a better router will solve all your problems.
Try re-positioning the router in (A) and a device in (B) to see if the latency can be improved. For example, try putting the router (A) and a device (B) near the front of each house.
Things like Aluminum siding, or a metal shed between the router and the devices in the other house will significantly reduce signal strength.
A "Repeater" or "Range-Extender" could significantly help and are fairly inexpensive. Try to find a place to put one outside (you only need to run power to it). Could be under a car-port, under the roof-overhang, or garage, or a shed, or under an awning. If all else fails, consider putting it in a small bird-house hanging from a tree or poll or above a fence (remember you need to run power to it).  The weather in your area may affect what you can do with this.
You could first, as a trial, place the range-extender out in the open at various places around your property to get an idea if it will work, and to find the best place to put it before you make it a "permanent" installation. In extreme cases, you may need to have a range-extender on both properties.


text:
Q: How to pass argument with no information for ggplot I am creating a function that plots a plot using ggplot2. I intend to use a loop to plot different data.frames. Most of the time I will be passing a vector of lines (using the argument lines) to be used with geom_vline:
+ geom_vline(xintercept = lines)

This works great assuming the particular plot should have lines. But one of the plots has no lines. Is there any vector I can pass in lines that will not produce any lines?


text:
Q: clear() method leaves one unknown character in the input field using SeleniumWebdriver When clearing a input field using clear() method for chromedriver version 100.0.4896.127, leaves this special char in the field


This occured only on this chromedriver version.
Anyone else encountered this?

A: There is a work around solution:
element.sendKeys(Keys.chord(Keys.CONTROL,"a", Keys.DELETE)

Or
while (!inputField.getAttribute("value").equals("")) {
        inputField.sendKeys(Keys.BACK_SPACE);
       }

A: Ideally while invoking clear() you need to induce WebDriverWait for the elementToBeClickable() as follows:
new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("elementCssSelector"))).clear();


text:
Q: using matplotlib with ipython console (spyder) fails I'm attempting to run the following code in Spyder (which uses an IPython console):
import numpy as np
import matplotlib as plt

labels = ['python\nloop', 'numpy\nbroadc.', 'sklearn', 'fortran/\nf2py', 'scipy', 'cython', 'numba']
timings = [13.4, 0.111, 0.0356, 0.0167, 0.0129, 0.00987, 0.00912]
x = np.arange(len(labels))

ax = plt.axes(xticks=x, yscale='log')
ax.bar(x - 0.3, timings, width=0.6, alpha=0.4, bottom=1E-6)
ax.grid()
ax.set_xlim(-0.5, len(labels) - 0.5)
ax.set_ylim(1E-3, 1E2)
ax.xaxis.set_major_formatter(plt.FuncFormatter(lambda i, loc: labels[int(i)]))
ax.set_ylabel('time (s)')
ax.set_title("Pairwise Distance Timings")

However, I get the following error:
Traceback (most recent call last):

  File "<ipython-input-1-46193480d26c>", line 1, in <module>
    runfile('C:/Users/owner/.spyder-py3/temp.py', wdir='C:/Users/owner/.spyder-py3')

  File "C:\Users\owner\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "C:\Users\owner\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/owner/.spyder-py3/temp.py", line 9, in <module>
    ax = plt.axes(xticks=x, yscale='log')

TypeError: 'module' object is not callable

Am I missing something? As far as I know, this code works fine in IDLE, however I could not install NumPy with PIP so I took an easy route and installed Anaconda.

A: You seem to use the pyplot module of matplotlib (that's what plt usually stands for). It should be imported like:
import matplotlib.pyplot as plt

If I change that line, your code works wonderfully for me :)


text:
Q: How do I grab an image on a server and display on a html page? I am trying to get a canvas that I have saved to pop up in my html window. Not sure how to grab it on the html page because the save generates a random name for the image.
The Save code:
function saveImage() {
cursor.visible = false; stage.update();
var canvasData = testCanvas.toDataURL("image/png");
window.open(("../popup.html"));
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
cursor.visible = true; stage.update();
}

else if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
alert (nameOfFile);
ajax.open('POST', 'testSave.php', false);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.send("imgData="+canvasData);
}

The PHP:
<?php
// requires php5
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:images/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>

The popup.html

Image to display below

A: Your PHP is already returning the $file that was created on the server.
So, you could POST with jQuery and add a callback that receives that unique filename created on the server (or the error message if an error occurred).
// create a dataUrl from the canvas
var dataURL= canvas.toDataURL();

// post the dataUrl to php
$.ajax({
  type: "POST",
  url: "upload.php",
  data: {image: dataURL}
}).done(function( respond ) {
  // you will get back the temp file name
  // or "Unable to save this image."
  console.log(respond);
});


text:
Q: Google Maps Speed Limit I'm trying to create a speed limit guide app (city-wide coverage). I've been researching and I found out that to access speed limit data in Google Maps API, you need to subscribe to a premium plan and access the speed limit data via Roads API. I'm just wondering if there are other ways to do a speed limit app that automatically adjusts depending on where the user is currently? Maybe hard code that if the user is somewhere between these 2 points on the road, its speed limit is etc. or an alternative map, I'm not really sure.
Hoping for your kind response, thanks.


text:
Q: Baseball XML to SQL query - optimize source data looks comes from the following, freely available XML files describing major league baseball games.
http://gd2.mlb.com/components/game/mlb/year_2013/month_04/day_09/gid_2013_04_09_atlmlb_miamlb_1/inning/
I have created a SQL Server table that contains a row for every GamePK/inning, with an XML column named PBP. Each file in the folder above becomes a row in this table. The query below is my attempt to parse the XML into a record set.  It works but is very slow for a large number of rows, and very repetitive - seems like there should be a better way to do this without the UNION clause.  Any help in improving/optimizing is appreciated
select
 i.GamePK
 ,inn.value('@num', 'int') as inning
 ,itop.value('1', 'int') as IsTop
 ,itop.value('@num', 'int') as abNum
 ,itop.value('@batter', 'int') as batter
--  clip

 ,itoppit.value('@des', 'varchar(32)') as pitdesc
 ,itoppit.value('@id', 'int') as seq
 ,itoppit.value('@type', 'varchar(8)') as pittype
-- clip

 from tblInnings i
       cross apply PBP.nodes('/inning') as inn(inn)
       cross apply inn.nodes('top/atbat') as itop(itop)
       cross apply itop.nodes('pitch') as itoppit(itoppit)
union
select
 i.GamePK
 ,inn.value('@num', 'int') as inning
 ,ibot.value('0', 'int') as IsTop
 ,ibot.value('@num', 'int') as abNum
 ,ibot.value('@batter', 'int') as batter
-- clip

 ,ibotpit.value('@des', 'varchar(32)') as pitdesc
 ,ibotpit.value('@id', 'int') as seq
 ,ibotpit.value('@type', 'varchar(8)') as pittype
--clip

 from tblInnings i
       cross apply PBP.nodes('/inning') as inn(inn)
       cross apply inn.nodes('bottom/atbat') as ibot(ibot)
       cross apply ibot.nodes('pitch') as ibotpit(ibotpit)

A: If you're using a recent version of SQL Server, there's a new column data type (XML).
You can apply xpath to it, making querying the column much easier.
Instead of trying to store the XML as a string in your DB, I'd suggest you actually store it as XML, and treat it as XML.
There is a learning curve. You'll need to be familiar with XPATH, but it's not rocket science.
an example:
SELECT Id, PartitionMonth, EmailAddress, AcquisitionCodeId, FieldValues.value('
declare namespace s="http://domain.com/FieldValues.xsd";
data(/s:FieldValues/s:item/@value)[1]', 'varchar(200)')
FROM Leads.Leads WITH (NOLOCK)
 WHERE Id = 190708

Another example retrieving values by key:
SELECT r.EmailAddress, ar.Ip, ar.DateLog,
  ar.FieldValues.value('
  declare namespace s="http://domain.com/FieldValues.xsd";
  data(/s:FieldValues/s:item[@key="First Name"]/@value)[1]', 'varchar(20)') FirstName,
  ar.FieldValues.value('
  declare namespace s="http://domain.com/FieldValues.xsd";
  data(/s:FieldValues/s:item[@key="Last Name"]/@value)[1]', 'varchar(20)') LastName
FROM Records.Records r WITH (NOLOCK)
JOIN Records.AcquisitionRecords ar WITH (NOLOCK) ON r.Id = ar.Id
WHERE ar.AcquisitionCodeId IN (19, 21, 30, 34, 36)
AND ar.DateLog BETWEEN '1-mar-09' AND '31-mar-09'

A good place to get started on XML in SQL Server
http://msdn.microsoft.com/en-US/library/ms189887(v=sql.90).aspx


text:
Q: Change label text in the navigation bar I added a label to my NavigationBar with this code:
let navigationBar = self.navigationController?.navigationBar

let moneyFrame = CGRect(x: 330, y: 0, width: (navigationBar?.frame.width)!/2, height: (navigationBar?.frame.height)!)

let moneyLabel = UILabel(frame: moneyFrame)

moneyLabel.text = "\(money)"

navigationBar?.addSubview(moneyLabel)

The problem is: when I want to change the value of the variable "money", I always came with the solution to add another label. I just want to change the text of the label in the NavigationBar.

A: In the class scope define a label like this:
var moneyLabel: UILabel?

then in your function or wherever the code you posted sits in the class, do this:
func myFunctionThatSetupNavigationLabel() {
    let navigationBar = self.navigationController?.navigationBar

    let moneyFrame = CGRect(x: 330, y: 0, width:
    (navigationBar?.frame.width)!/2, height: (navigationBar?.frame.height)!)

    moneyLabel = UILabel(frame: moneyFrame)

    moneyLabel.text = "\(money)"

    navigationBar?.addSubview(moneyLabel)
}

Now just add this function to edit the title label:
func updateTitle(title: String) {
    if let myTitleView = self.moneyLabel {
        myTitleView.text = title
    }
}

A: You could add the label to the navigation bar as a custom view.
In the class scope define a label:
var label = UILabel()

then in viewDidLoad:
    override func viewDidLoad() {
    super.viewDidLoad()

    let textlabel = UIBarButtonItem(customView: label)
    navigationItem.rightBarButtonItem = textlabel
    label.text = "money"
    }

then whenever you want to change the text label you could simply just write the next code:
label.text = "whatever you want"


text:
Q: TypeError: __init__() got an unexpected keyword argument 'progress_bar_refresh_rate' I tried resolving this issue since two days however still facing this issue any leads would be helpful.
Please refer the link for screenshot

A: Please try by deleting the progress_bar_refresh_rate=5 argument, since this keyword argument is no longer supported by the latest version (1.7.0) of PyTorch.Lightning.Trainer module. Check this screenshot for clarity.


text:
Q: Identifying Bold Text in PDF using pyPdf I am using pyPdf to extract text from a PDF. I would like to be able to know which text is bold in order to identify bold section headers. How can I identify bold text?

A: pypdf has no direct support for it - it's not impossible, but it would require significant effort from your side. As pypdf is no longer maintained, this will not change.
PyPDF2 also does not have this at the moment (May 2022), but I'm open to a PR adding this support.


text:
Q: What's the difference between the SharedAccessBlobPermissions values Add, Create and Write? The possible values for SharedAccessBlobPermissions are:

*

*None (0)

*Read (1)

*Write (2)

*Delete (4)

*List (8)

*Add (16)

*Create (32)

What are the differences between Add, Create and Write? I can't find any documentation that clarifies this.

A: You can find information about these permissions here: https://msdn.microsoft.com/en-us/library/azure/dn140255.aspx.
From what I understand reading about these permissions:

*

*Add: Add permission is only applicable for append blobs. You use this permission to add a block to an append blob. No other operation is possible using this permission.

*Create: Create permission only allows creation of blobs or in other words you can't update a blob with this permission. This would include writing a new blob, take a snapshot of an existing blob, or copy a blob to a new blob.

*Write: Write permission allows creation and updation of blobs. This would include create or write content, properties, metadata, or block list, take a snapshot or manage lease on a blob and resize the blob (page blob only).

In our application, we use Shared Access Signature extensively and we make use of Write permission almost exclusively on all the blob related operations.


text:
Q: Setting up Aptana Studio 3 on ubuntu using RVM I've set up rails using RVM in my user profile and its working perfectly fine from the terminal and using Gedit. But I wanted to use more powerful IDE which led me to Aptana Radrails. I have downloaded the latest binaries and am running it from the home/Softwares/ folder but anytime I am creating a new Rails project from the template the rails generate command does not generate anything but from command line it does. Please guide me upon how to set up Aptana Studio 3 with rails already set up using RVM. Some visual guides would really help.
OS - Ubuntu 11.04
Rails - 3.1.0
Ruby - 1.9.2

A: Open the terminal and type rvm use 1.9.2
then, in the same terminal, change directories to where Aptana is installed and launch Aptana using the following command ./studio3
This will solve your problem until the next time you use Aptana. For a permanent solution, write a bash file having these commands and launch it when you wish to use Aptana.

A: May be just add your rvm rails binary's path to your /etc/environment file and export it and relogin your gnome session and try it?

A: do u have any other ruby versions installed in your system.?
find it using which ruby before executing


text:
Q: zIndex does not work on ANY element in react-native-maps I already saw that there were posts where you were trying to solve zIndex defects of react native maps for markers. But it does not work on ANYTHING in react native maps, including Polygon, Polyline. Is there any solution to solve this huge problem?
Thank you for your suggestions.

A: try to do this :
 <MapView
      //ref={_map}
      initialRegion={{
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      }}
      style={{
        flex: 1,
        ...StyleSheet.absoluteFillObject, // <-- add this style to map
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
      }}
      //provider={PROVIDER_GOOGLE}
      >
      <Marker
        coordinate={{latitude: LATITUDE,longitude: LONGITUDE,}}
        title={'itle'}
      />
    </MapView>
    <View style={{marginVertical: 20, flexDirection: 'row',}}>
      <TouchableOpacity
        onPress={() => {}}
        style={[styles.bubble, styles.button]}>
        <Text>Press me</Text>
      </TouchableOpacity>
    </View>
  </View>


text:
Q: Modulus Meteor Microservices Subscriptions not working We are moving our app from Rackspace to Modulus. We have 2 apps configured as microservices using meteorhacks:cluster package. It seems like Meteor Methods (server1 to server2) call is working but Meteor subscription (client2 to server1) is not working. I am trying to figure out if it is a Cross domain request issue.
// https://github.com/meteorhacks/cluster#microservices

//server2/app.js
Cluster.register(process.env.APP_NAME,{endpoint:process.env.ROOT_URL});
mainApp = Cluster.discoverConnection("server1");
Cluster.allowPublicAccess("server1");

//client2/app.js
mainApp = Cluster.discoverConnection("server1");
ContentLibrary= new Meteor.Collection('content_library',   {connection:mainApp,idGeneration : 'MONGO'});

//client2/home.js
mainApp.subscribe('contentDocuments','all',function(e){
  if(!e)
    doSomething();//Never gets called
});

//server1/publish.js
Meteor.publish("contentDocuments", function(){
 return ContentLibrary.find({});
}

ContentLibrary collection on the client is never populated.
Our apps works on Rackspace as expected.

A: i'm not using meteorhacks:cluster but i am running microservices for my meteor app.  it's on DO, so the setup may be different, but here is how i'm doing it.
i'm using reactive-publish to help with server side reactivity
// client ------
/server/lib/ddp-setup.js
ContentLibrary = DDP.connect('10.123.455.332:3000')

/server/publications.js
Content = new Mongo.Collection('content', {connection: ContentLibrary})
Meteor.publish('content', function(opts){
  check(opts, Object)
  this.autorun(()=>{
    let sub = ContentLibrary.subscribe('content', opts)
    if( sub.ready() ){
      return Content.find({})
    }
  })
})

// server1 @ 10.123.455.332:3000 -------

/server/publications.js
Meteor.publish('content', function(opts){
  check(opts, Object)
  // do something with opts...
  return Content.find({})
})

the idea is that your client is only ever talking to it's own server, but the server then talks with all of your other microservices.  this affords you the increased security of allowing servers to speak to each other on a private network (as i have my setup with digital ocean).
letting servers talk to each other over the private network is security at its best and the network latency almost zero between servers.  setting it up like this also means that you only have to worry about sticky sessions between your client browser and the web-facing app/service.
this may or may not answer your question, but hopefully it will give you some insight into setting up the architecture.


text:
Q: Kafka and microservices - Architecture questions In a Microservices based architecture, who writes to Kafka? services themselves or the Microservices databases? I've been thinking about this and see pros and cons to both approaches but leaning towards having database write to Kafka topics because

*

*Database and data in the Kafka topic won't go out of sync in case write to Kafka fails for whatever reason

*Application teams won't have to have one more step to worry about

*Applications can keep focusing on the core function rather than worrying about Kafka.

Thanks for your inputs

A: As cricket_007 has been saying, databases typically cannot write to Apache Kafka themselves; instead, you'd need a change data capturing services such as Debezium in order to stream data changes from the database into Kafka (disclaimer: I'm the lead of Debezium).
Such an approach allows to ensure (eventual) consistency between a service's own database and Kafka messages sent to other services. On specific CDC application I'd recommend to look into is the outbox pattern. The idea there is to not capture changes to the service's actual business tables, but instead work with a separate "outbox table", into which the service writes specific messages meant for consumption by other services. CDC would then be used to sent these events from that table to Kafka.
This approach avoids exposing internal data structures to outside consumers while also avoiding the issues of "dual writes" which a service would suffer from when directly writing to its database and Kafka. In Debezium there's some means of built-in support for the outbox pattern via a message transformation that helps to route the events from the outbox table into event-type specific Kafka topics.

A: Not all services need a database, they just emit data (logs, metrics, sensors, etc)
So, the answer would be either.
Plus, I'm not sure what database directly can export to Kafka, so you'd have some other service like Debezium deployed which would be polling those CDC records off the database
Application developers still have to "worry" about how to deserialize their data, how many partitions are in the topic so they can scale out consumption, manage offsets, among other things


text:
Q: UISegmentedControl like in iTunes/App Store apps I'm trying to get a UISegmentedControl like is in the iTunes app and App store app,
where you select between Top Paid, Top Free and Top Grossing, its a bar style except more blue. It goes above a table view

A: Use the normal UISegmentedControl class and use the property to change the style as needed.
(See Style popup menu on the right!)

You can also set the segmentedControlStyle property of the control to one of the following values:
typedef enum {
   UISegmentedControlStylePlain,
   UISegmentedControlStyleBordered,
   UISegmentedControlStyleBar,
   UISegmentedControlStyleBezeled,
} UISegmentedControlStyle;

A: segmentedControl.segmentedControlStyle = 7;


text:
Q: How to return back the function call and its parameters within the same function in JavaScript Without using anything that has been deprecated and without passing as a parameter to the function call, can we return the entire function call with the exact parameters?
For example, we have:
function MyFunction(param1, param2, param3) {
    var f = function() {
        MyFunction(param1, param2, param3); // Made an edit here.  This would make more sense.
    }

    return(f); // I really don't want to define f.
}

var capture = MyFunction(1, 2, 3);

capture();

Instead of hard coding the function call to the f variable, can we use some keyword or JavaScript function instead and thus require no maintenance?

A: Why not return another function inside function?
function MyFunction(param1, param2, param3) {
    return function() {
        return param1+param2+param3;
    }
}

var capture = MyFunction(1, 2, 3);

capture();

A: This can't be fully generalized, a function can refer (only named functions) itself with its name, there's no common reference to the currently executed function. The snippet below does what you need, when you're having a named function, which is not a method of an object.

function captureFn(fn, args) {
  return function() {
    fn.call(null, ...args);
  };
}

function MyFunction(param1, param2, param3) {
  console.log(param1, param2, param3);
  return captureFn(MyFunction, arguments);
}

var capture = MyFunction(1, 2, 3);

capture();

In the return statement of MyFunction you've to change the first argument to the name of the function on every function this return value is used.
This is easy to expand to cover object methods too. Just pass this as an argument to captureFn, and pass the passed this instead of null in fn.call. When calling from an object method, the function can be also anonymous, the function name can be replaced with a reference to the method (this.methodName). See this variation working at jsFiddle.

A: You can use a generator function to call the function multiple times.
Using Promise.then

async function* func(...props) {
  for (let i = 0; i < props.length; i++) {
    const result = await new Promise((resolve) =>
      setTimeout(() => resolve(props[i]), 1000)
    );

    yield result;
  }
}

let generator = func(1, 2, 3);

generator.next().then((val) => {
  console.log(val);
});

generator.next().then((val) => {
  console.log(val);
});

generator.next().then((val) => {
  console.log(val);
});

Using Async/Await

async function* func(...props) {
  for (let i = 0; i < props.length; i++) {
    const result = await new Promise((resolve) =>
      setTimeout(() => resolve(props[i]), 1000)
    );

    yield result;
  }
}

(async () => {
  let generator = func(1, 2, 3);

  console.log(await generator.next());
  console.log(await generator.next());
  console.log(await generator.next());
})();


text:
Q: Would you italicize chapatis? I guess "chapati" is foreign word and should be italicized in a text. But what about plural? The foreign word is actually chapati, and the plural is made using the English "s" (even if, maybe, chapati is like "bread", singular). What's correct?

A: noun: chapatti; plural noun: chapattis
http://google.com/#q=define:+Chapati
But http://en.wikipedia.org/wiki/Chapati uses chapatis.
You could use any/both. Google search shows chapatis as more frequently used variat.

A: Regarding chapatti itself, I recall that the word was not set off either in quotes or italics the first time I read it in a novel several decades ago.

This may be due to the fact that it's a British novel that deals with a former British possession, or that it's a first-person narrative by a character who is no Oxford don, but I incline toward the feeling that certain words, especially those relating to food, are not subject to the usual arm's-length treatment other words might be. We refer to tortillas, empanadas, brioche, linguini, sauerbraten and borscht all without that crutch, and we get along just fine.
Normally we reserve italics for foreign words for which we already have a ready English equivalent (frisson for "thrill"), or for which no comparable word exists in English (gemütlichkeit), or which the writer or editor decides is too recondite (kulturny)—and it is worth noting that the decision really rests on the person or organization who puts the words up for publication.
It is sometimes hard to avoid the suspicion that italicization can be overdone, or used as an affectation. And styles do vary. The New Yorker seems to italicize foreign words within an inch of their lives, while other publications take a much milder stance on the matter.
Full disclosure: I have asked a question similar to this one and came away feeling no real sense of closure on the subject.


text:
Q: Java Beginning Scanner I am a novice programmer and I am trying to do projects that I find fun to help me learn more about the language then my school classes have been able to provide.  I have wanted to try reversing a string but instead of having the string defined in a string I have added a scanner to be able to allow a user to input what they want.  After searching for any help I haven't been able to find my issue that I am having.  So far I have this:
import java.util.ArrayList;
import java.util.Scanner;

public class Reverse {

    static ArrayList<String> newString = new ArrayList();

    static int inputLength = 0;
    static String PlaceHolder = null;
    static String beReturned = null;
    static int lengthArray = 0;
    static String ToBeReversed;
    static String hold = null;

    public static void reversal(){
            inputLength = ToBeReversed.length();
        for (int e = 0; e <= inputLength; e++)
        {
                PlaceHolder = ToBeReversed.substring(inputLength -1, inputLength);
                newString.add(PlaceHolder);
        }

    }

    public static String putTogether()
    {
        int lengthcounter = 0;

        lengthArray = newString.size();
        for (int i = 0; i <  lengthArray; i++)
        {
            beReturned = beReturned + newString.get(lengthcounter);
            if (lengthcounter < lengthArray)
            {
            lengthcounter++;
            }
        }
            return beReturned;
        }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); //create a new scanner

        ToBeReversed = input.nextLine();
        Reverse.reversal();
        Reverse.putTogether();

        }

}

For any input that I input there is no result.  I don't get an Error Message or any form of return... The output is blank.  I am just wondering if I made a mistake with the scanner or if it is how I am trying to store the characters/access them from the ArrayList I created.  I am trying to not have others give me the answer completely with all the fixes, I hope I can just get a pointer or a hint to where I am messing up.   Thank you for your time and help.

A: You need to print the output, for example
public static void main(String[] args) {
    Scanner input = new Scanner(System.in); //create a new scanner

    ToBeReversed = input.nextLine();
    System.out.println("ToBeReversed = " + ToBeReversed);
    Reverse.reversal();
    System.out.println("newString = " + newString);
    System.out.println(Reverse.putTogether());

}

I don't want to give a complete answer, as that would spoil your fun (and steal an opportunity for your to get started with using a debugger), but here are some hints...

*

*You can use String#charAt to get an individual character from a String at a given index

*Java is generally 0 indexed, that means that things like arrays, String, List start at index 0 and go through to length - 1

*null + String = nullString ;)

*You can run a loop backwards.  for-loop doesn't have to run from 0-x in ascending order, they can run x-0 in descending order ;)


text:
Q: Disable 'hide toolbar' in Finder Is it possible to permanently overwrite the 'Hide Toolbar' and 'Hide Sidebar' setting in the Finder, particularly in DMG images with downloaded Applications, so that the toolbar and sidebar are always visible?
That way it would be possible to drop applications directly into the Applications folder.


text:
Q: Get one Windows to work on two different motherboards I use Windows 7.
I'd like to be able to move my SSD hard disk, back and forth from a Dell laptop motherboard to an MSI desktop computer motherboard, without having to reinstall every program.
From here, you can skip to the answer
I first tried just to boot with the MSI motherboard, but Windows 7 crashed with a BSOD (Blue screen of death). I let Windows 7's repair tool try to recover the startup, but it couldn't fix it. I tried installing Windows from the MSI motherboard, then booting Windows from the Dell laptop, but I got a BSOD again.

Attempt:
I'm know asking myself if it's possible to get it working by manually swapping the startup files whenever I want to change my hard disk of computer. I can get the said startup files by making one more fresh install of Windows 7 on the Dell laptop, but I won't know which ones I should pick.
It's here I need your help: Which are the files I should copy ? i.e. Which are the files specific to the motherboard, on a Windows 7 setup ?
For sure the drivers will be different, but once I'll have installed both system drivers on my disk, it should be fine.
I read that the HAL and IDE control drivers should be re-installed, (at least for Windows XP and Windows 2000: there). So I consider backing them, and manually replacing them each time I want to change of computer.
I could find a file named hall.dll in \Windows\system32, but I could not find anything like a location for IDE file(s). Should I just backup/replace the whole system32 folder ?
Maybe I should try doing two fresh installs, then using a diff tool to try to guess the filepaths I look for.
Thank you for reading. Thank you for any help in advance.

A: Use sysprep.
run>sysprep>enter>select Audit mode+tick generalize>select shutdown>select OK.
Remove HDD, place in 2nd pc and boot it up, install drivers, reboot.
Everytime you sysprep it to another machine you will need to install somedrivers (generally speaking) . Keep in mind machines that have been upgraded need a upgrade key to be removed form the reg before sysprep will run.
A simplier solution would be to follow the sysprep audit proceedure, clone the drive to another HDD using somethign like YUMI & PartitionWizardFree, and have essentially 2 identical Windows installs. Keep in mind unless you're running legal volume lisences, you will need an additional Win and possibly Office (365 provides 5 licenses) depending on the version.

A: Sysprep solution
I tried sysprep, I got good results. (I use Windows 7)
sysprep.exe is in Windows\system32\sysprep folder. The latter is reachable by typing sysprep in the windows run prompt-box (open it by pressing win+r).
Edit the register
First, in order to give to sysprep the desired behavior, you may change some keys of the register. (Using regedit):
The three keys are descendants of HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.

*

*SkipRearm key
Path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProtectionPlatform
In order to avoid trial clock re-arming depletion, you'll want to set the SkipRearm key to to 1. Three re-armings are allowed. So if the key wasn't set, the fourth time you'll run sysprep, it will block and output an error whenever you eventually set the key. Warning: this key is reset after each sysprep execution. I'd get used to setting it just before I execute sysprep.

*PersistAllDeviceInstalls and DoNotCleanupNonPresentDevices keys
Path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\Sysprep\Settings\sppnp
To keep the drivers from both motherboards installed, set the keys PersistAllDeviceInstalls and DoNotCleanupNonPresentDevices to 1 as well.
Execute Sysprep
Either double-click sysprep file to use the graphical mode or execute sysprep.exe /generalize /oobe /shutdown. Let the computer poweroff.
Change your hard drive of motherboard. Start it on the other computer. The missing drivers will be installed. You will be asked to create a user account, and name your computer. (Re-?)Name your computer as you want. I suggest that you just create a fake account, then log in your original user account, and deleted the other (fake) user account.
This is it, the transfer is done. (It takes around 10 minutes once you are used to doing it).
Remarks:

*

*Some Windows settings are reset to default.

*If you use audit mode rather than out-of-the-box-experience mode (i.e. you replace /oobe by /audit in the command line I gave), you are automatticaly logged in an administrator account whose settings are reset at each boot. But you can still log in your account, where modifications will be kept. This behavior remains until you execute sysprep with the oobe option.

Thank you for reading, I hope this helped.


text:
Q: Entity Designer missing As the title says, somehow the entity designer disappeared from my installation of Visual Studio 2010.
When trying to open an .edmx file, it only opens it in the XML editor. When i choose "Open With...", the Entity designer doesn't show up in the list.
It has worked before, and i don't know of anything i could have done to remove it from the list. Does anyone know how i can re-add it? Thanks!

A: First thing to check is, is this a problem with your project or with your VS installation.

*

*Try creating a new project and see if the entity designer is in the list

If it is you have two options

*

*Move your files to the new project

*Try to repair your project file

The way it works is that there are a set og Guids in the project file that control what is available in that project. So you can open the project files in notepad, find out which is missing and then move them over.


text:
Q: Migrating puppet from 3.x to 4x I have existing puppet modules written in hiera. Basically, data module with param.pp pattern. Everything works fine in puppet 3.x. But after setup with puppet 4.x and ran puppet agent, following error return for hash keys.
Error: Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Evaluation Error: Error while evaluating a Resource Statement, Evaluation Error: Error while evaluating a Function Call, Failed to parse template wso2ei/conf/carbon.xml.erb:
  Filepath: /etc/puppetlabs/code/environments/production/modules/wso2ei/templates/conf/carbon.xml.erb
  Line: 138
  Detail: undefined method `[]' for nil:NilClass
 at /etc/puppetlabs/code/environments/production/modules/wso2base/manifests/push_templates.pp:23:16 at /etc/puppetlabs/code/environments/production/modules/wso2base/manifests/configure.pp:59 on node puppet4-aa54a7f2-83a6-43d2-b8d7-c15a42591e88.openstacklocal

The particular section of carbon.xml.erb looks like below
<%- if @ports['offset'] -%>
        <Offset><%= @ports['offset'] %></Offset>
<%- else -%>
        <Offset>0</Offset>
<%- end -%>

hieradata set as below in yaml file
wso2::ports:
  offset: 0

param.pp written to read the data
   $ports                    = hiera('wso2::ports')

init.pp set value as below
  $ports                  = $wso2ei::params::ports,

Template not giving any error for a single line data. For an example in carbon.xml.erb
<% if @hostname %>
    <HostName><%= @hostname %></HostName>
<%- else -%>
    <!--HostName>www.wso2.org</HostName-->
<% end %>

hieradata in yaml file
wso2::hostname: "%{::fqdn}"

All hash keys getting the same error. When I Google, found that @ has to replace with scope like below. But there are lots of places to change.
<%- if scope['wso2ei::params::ports']['offset'] -%>
        <Offset><%= scope['wso2ei::params::ports']['offset'] %></Offset>
<%- else -%>
        <Offset>0</Offset>
<%- end -%>

Is there a way to preserve existing param.pp data module pattern in puppet 4? Appreciate your help.


text:
Q: root frame not responding in tkinter Willing to develop a media player which will show 'lyrics', guitar and piano code when a song is played, but getting no idea how to begin with. I have started with the following code, which is giving me 'filedialog not defined' error when add_play_list button is pressed for the fist time, on second run this error disappears. Code can play songs in the folder but the root frame window is 'not responding' until all songs are played. How can I solve these problems? How can I add lyrics and guitar code in labels? Your guidance will help. Thanks.
import os
from tkinter import *
import tkinter.filedialog
import mutagen
import pygame

root= Tk()
root.title("AVPlayer")
root.geometry("500x250")

top_frame= Frame(root, bg='red')
top_frame.pack(fill=BOTH, expand=True)

playlist= Listbox(top_frame, relief='flat',
font=("Arial",8),fg='white', bg='red')
playlist.pack( fill=BOTH, expand=True,
padx=10, pady=10)

vscroll=Scrollbar(playlist)
vscroll.pack(side=RIGHT, fill=BOTH)
vscroll.config(command=playlist.yview)
playlist.config(yscrollcommand=vscroll.set)

midl_frame=Frame(root, bg="red", height=50)
midl_frame.pack(fill=BOTH)

add_play_list= Button(midl_frame,text="+",
bg='red', font=('Arial', 15),
relief='flat', borderwidth=2, fg='white',
command=playlistitems)
add_play_list.pack(padx=10, side=LEFT)

nextbtn=Button(midl_frame, text='>|',font=
('Arial',15),bg='red',fg='white',
relief='flat',borderwidth=2)
nextbtn.pack(side=RIGHT, padx=10)

prvsbtn=Button(midl_frame, text='|<',font=
('Arial',15),bg='red',fg='white',
relief='flat',borderwidth=2)
prvsbtn.pack(side=RIGHT, padx=10)

pausebtn=Button(midl_frame, text='||',
bg='red', font=('Arial',15), relief='flat',
borderwidth=2, fg='white')
pausebtn.pack(side=RIGHT, padx=10)

playbtn= Button(midl_frame,text='>',
bg='red', font=('Arial',15), relief='flat',
borderwidth=2, fg='white',
command=playaudio)
playbtn.pack(side=RIGHT, padx=10)

songlist=[]

def playlistitems(event):
    global flpath
    flpath= filedialog.askdirectory()

    for i in os.listdir(flpath):
        if i.endswith(".mp3"):
        title=
       mutagen.File(os.path.join(flpath,i))
        playlist.insert(END,title['TIT2'][0])
        songlist.append(i)

def playaudio(event):
    for x in songlist:
        pygame.mixer.init()
        pygame.mixer.music.load
        (os.path.join(flpath,x))
        pygame.mixer.music.play()

       while pygame.mixer.music.get_busy():
           pygame.time.Clock().tick(100)

root.mainloop()


text:
Q: facebook messenger with ibm watson emoji input I now currently doing facebook integration using IBM Watson. In facebook, documention didn't provide anything about emoji. How emoji going works when Watson conversation receive emoji from facebook messenger?

A: Watson conversation will do nothing with emojis. If you have them in your training data, it may use it in the learning, but more as "keywords" then actual meaning.
Watson Tone analyser should understand emojis though, at least from a tone perspective.


text:
Q: React-Leaflet: Cannot display leaflet map properly after toggling by using functional component When I click the button "Search heritage", I want to display the map on my webpage. However, the Leaflet Map cannot show properly as below:
Webpage display
The map can be fully displayed without any problem once I resize my webpage. I have found some solutions that can solve this problem based on class component but I have no idea to solve it when using functional component.
Here is my current code.

*

*leaflet.tsx

import "./leaflet.css";

import { MapContainer, TileLayer, useMap, Popup, Marker } from "react-leaflet";

export default function Leaflet() {
  const mapRef: any = createRef();

  useEffect(() => {
    const map = mapRef.leafletElement;
    setTimeout(() => {
      map.invalidateSize();
    }, 1000);
  }, [mapRef]);

  return (

      <MapContainer
        center={[22.3193, 114.1694]}
        zoom={10}
        scrollWheelZoom={false}
        ref={mapRef}
      >
        <TileLayer
          attribution='© OpenStreetMap contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={[50.5, 30.5]}>
          <Popup></Popup>
        </Marker>
      </MapContainer>

  );
}

2.leaflet.css
  font-family: sans-serif;
  text-align: center;
}

.leaflet-container {
  height: 600px;
  width: 100%;
}

.leaflet-div-icon {
  background: transparent;
  border: none;
}

I am using react-leaflet ^4.0.0


text:
Q: asp.net asmx Webservice can't start I have a legacy asp.net web service who is part of a asp.net WebFroms application who is hosted on a WinServer 2008 R2. The asmx contains only this code:
<%@ WebService Language="VB" CodeBehind="~/Src/FooWebService.vb" Class="FooWebService" %>

The FooWebService file is in the Folder Src and the service file itself is called FooWebService.asmx.
The FooWebService.vb has the following structure:
Imports System.Data.SqlClient
Imports System.Web.Script.Services
Imports System.Web.Services
Imports Microsoft.VisualBasic.CompilerServices

<ScriptService> _
<WebService(Namespace := "http://tempuri.org/")> _
<WebServiceBinding(ConformsTo := WsiProfiles.BasicProfile1_1)> _
<DesignerGenerated>
Public Class FooWebService
    Inherits WebService

    <WebMethod>
    Public Function GetPLZ(prefixText As String) As String()
        ...
    End Function

    <WebMethod>
    Public Function GetStrasse(prefixText As String, contextKey As String) As String()
        ...
    End Function

    <WebMethod>
    Public Function HelloWorld() As String
        Return "Hello World"
    End Function
End Class

When I try to access the WebService the following error message appears:

What is wrong here?


text:
Q: Limit with cos and fraction I have been asked to find:
$\lim_{x\to 0} \, \cos \left(\frac{\pi -\pi  \cos ^2(x)}{x^2}\right)$$=-1$
Without using l'Hôpital's rule. But I have no idea how to due it, could someone show a step by step process all the way to the answer?

A: Hint: We have
$$\frac{\pi -\pi\cos^2 x}{x^2}=\frac{\pi\sin^2 x}{x^2}=\pi \left(\frac{\sin x}{x}\right)^2.$$

A: Notice that:
$$\frac{\pi -\pi\cos^2 x}{x^2}=\frac{\pi\sin^2 x}{x^2}=\pi \left(\frac{\sin x}{x}\right)^2.$$
As you know, the limit:
$$\lim_{x\to 0} \, \left(\frac{\sin x}{x}\right)=1$$
Therefore, our answer is:
$$\pi*1 = \pi$$
And
$$\cos(\pi) = -1$$


text:
Q: How to write plugins for a production RCP application? I want to write a plugin for an existing, production RCP application. As it is in production, I don't have access to the source or project files. However it has clearly defined plugins with plenty of extension points.
I've been reading tutorials on RCP development but most of these work with sample projects. How do I set-up an eclipse project so that I can contribute to this applications extension points?


text:
Q: Batch file error? I'm getting a weird error with one of the codes in my batch file "(1 was unexpected at this time)"
@echo off
md tmp
echo made tmp folder
pause
for %%a (1,2,3) call Do_asst %%a

i'm new to batch files but haven't been able to find the problem yet, anyone know why it won
t call the other batch file (Do_asst) and crashes instead?

A: This should be:
@echo off
md tmp
echo made tmp folder
pause
for %%a in (1,2,3) do call Do_asst %%a

Note the missing "in" and "do"...


text:
Q: QGIS web client - Setting up WSGI search (mod_wsgi) I am trying to set up the QGIS Web Clients WSGI search. I've succefully set up my QGIS WebClient on a windows OS. Now I tried installing the mod_wsgi.so module in the Apache modules directory, added the line LoadModule modules wsgi_module / mod_wsgi.so always in apache but as soon as I plug in the conf apache:
 #mod_wsgi

 WSGIScriptAlias / WSGI "C: \ OSGeo4W \ apache \ htdocs \ qgis-web-client-master \ WSGI"      WSGIScriptAliasMatch ^ / WSGI / ([^ /] +) "C: \ OSGeo4W \ apache \ htdocs \ qgis -Web-client-master \ $ 1.wsgi"

The apache server does not reboot. I'd like to understand what am I doing wrong and how to further set up my apache to execute wsgi files?

A: QGIS Web Client's WSGI search requires you to configure your Apache into executing wsgi scripts. Firstly you'll need to install the correct module (When downloading a wsgi module please be sure to check the correct Apache version).
On the windows OS the configuration file can be found in the folder OSGeo4W/apache/conf/httpd.conf
Enable your module:
LoadModule wsgi_module modules/mod_wsgi.so

Now within the file OSGeo4W/httpd.d/httpd_qgis.conf we will configure our qgis application. This folder can contain definitions for qgis or any other kind of applications.
We will be adding 2 definitions, first one is the alias for wsgi:
Alias /wsgi/ C:\OSGeo4W/wsgi/  #**NOTE
#This will allow to change the path of the wsgi folder (which contains your wsgi/python scripts) to a shorter one -> /wsgi/

The second one is how and where we handle/execute these scripts:
<Directory "C:\OSGeo4W/wsgi/">
  SetHandler wsgi-script
  Options ExecCGI
  Order allow,deny
  Allow from all
</Directory>

**NOTE I've moved the wsgi scripts and the qgiswebclient/wsgi folder because the qwc_connect.py contains a database string, which is information I wouldn't like to share with the people using my Apache server
After these simple steps the Apache should reboot. If the Apache successfully rebooted the wsgi scripts are now supported.
The next step is setting up the wsgi scripts inside the /wsgi folder.
In the file qwc_connect.py, we will now need to set up our database string:
DB_CONN_STRING="host='hostname' dbname='DATABASE_NAME' port='5432' user='myuser' password='mypassword'"

After we got our database string set, it is time to set the searchtables within the file search.wsgi, where we jump to line 32 and set:
searchtables = [sheme_name.table_name,...];

Now that we have our searchtable names set, we should define the views inside our database. Here is an example of create view script for PostgreSQL from michele's table:
CREATE OR REPLACE VIEW view_name_here AS --if you're using pgAdmin, remove this line
SELECT
concat ('Layer catasto_terreni: ', c.id,'-', c.foglio, '\', c.part_cat, ' ', c.comune) AS displaytext,
--this is the display text in your search box
concat(c.id,'\', c.foglio,'\', c.part_cat, '\', c.comune) AS search_category,
concat(c.part_cat, '/', c.foglio, '/', c.comune) AS searchstring,
--we perform searching by entering values parc_cat/foglio/comune, we can concat them to form more even complex strings, but I use a different view for each "type" of search
concat('') AS showlayer,
c.geom AS the_geom --this field is the most important one since it will zoom to this geometry
FROM catasto_terreni c;

This is an example of a search:


text:
Q: GeoServer SLD applying two styles for one layer How can I apply two styles (NamedStyle and UserStyle). When executing a query, only the top one is applied. How can I apply both styles?
This sld_body:
 <?xml version="1.0" encoding="UTF-8"?>
        <StyledLayerDescriptor version="1.0.0" xsi:schemaLocation="http://www.opengis.net/sld StyledLayerDescriptor.xsd" xmlns:gml="http://www.opengis.net/gml/3.2.1" xmlns="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
           <NamedLayer>
              <Name>${this.selectedValue.name}</Name>
              <NamedStyle>
                <Name>sld_well_o</Name>
              </NamedStyle>
              <UserStyle>
                 <Title>Heatmap</Title>
                 <Abstract>A heatmap surface showing GLOB distribution</Abstract>
                 <FeatureTypeStyle>
                    <Transformation>
                       <ogc:Function name="vec:Heatmap">
                          <ogc:Function name="parameter">
                             <ogc:Literal>data</ogc:Literal>
                          </ogc:Function>
                          <ogc:Function name="parameter">
                             <ogc:Literal>weightAttr</ogc:Literal>
                             <ogc:Literal>${selectedField.name}</ogc:Literal>
                          </ogc:Function>
                          <ogc:Function name="parameter">
                             <ogc:Literal>radiusPixels</ogc:Literal>
                             <ogc:Function name="env">
                                <ogc:Literal>radius</ogc:Literal>
                                <ogc:Literal>${radius}</ogc:Literal>
                             </ogc:Function>
                          </ogc:Function>
                          <ogc:Function name="parameter">
                             <ogc:Literal>pixelsPerCell</ogc:Literal>
                             <ogc:Literal>10</ogc:Literal>
                          </ogc:Function>
                          <ogc:Function name="parameter">
                             <ogc:Literal>outputBBOX</ogc:Literal>
                             <ogc:Function name="env">
                                <ogc:Literal>wms_bbox</ogc:Literal>
                             </ogc:Function>
                          </ogc:Function>
                          <ogc:Function name="parameter">
                             <ogc:Literal>outputWidth</ogc:Literal>
                             <ogc:Function name="env">
                                <ogc:Literal>wms_width</ogc:Literal>
                             </ogc:Function>
                          </ogc:Function>
                          <ogc:Function name="parameter">
                             <ogc:Literal>outputHeight</ogc:Literal>
                             <ogc:Function name="env">
                                <ogc:Literal>wms_height</ogc:Literal>
                             </ogc:Function>
                          </ogc:Function>
                       </ogc:Function>
                    </Transformation>
                    <Rule>
                       <RasterSymbolizer>
                          <Geometry>
                             <ogc:PropertyName>geom</ogc:PropertyName>
                          </Geometry>
                          <Opacity>${opacity}</Opacity>
                          <ColorMap type="ramp">
                             <ColorMapEntry color="#70ff00" quantity="0.0" label="nodata" opacity="0" />
                             <ColorMapEntry color="#8b8b8b" quantity="0.001" label="minValue" opacity="0" />
                             <ColorMapEntry color="${colorStart}" quantity=".1" label="start" />
                             <ColorMapEntry color="${colorEnd}" quantity="1.0" label="end" />
                          </ColorMap>
                       </RasterSymbolizer>
                    </Rule>
                 </FeatureTypeStyle>
              </UserStyle>
           </NamedLayer>
        </StyledLayerDescriptor>

call WMS:
let sldBody = xmlRequest.replace(/\s\s+/gm, '');
this.heatMapLayer = (L as any).nonTiledLayer.wms(`${this.selectedValue.source.url}/wms`, {
  tileSize: L.point(map.getSize().x, map.getSize().y),
  format: 'image/png',
  sld_body: sldBody,
  version: '1.3.0',
  transparent: true,
  layers: this.selectedValue.name,
  cql_filter: `${selectedField.name} > 0`
});

Version GeoServer 2.15.0
I am using Lealflet

A: You can only apply one style per layer in a WMS request so you will need to request the layer twice with the two styles.
So something like:
let sldBody1 = xmlRequest1.replace(/\s\s+/gm, '');
let sldBody2 = xmlRequest2.replace(/\s\s+/gm, '');
this.heatMapLayer = (L as any).nonTiledLayer.wms(`${this.selectedValue.source.url}/wms`, {
  tileSize: L.point(map.getSize().x, map.getSize().y),
  format: 'image/png',
  sld_body: sldBody1,sldBody2,
  version: '1.3.0',
  transparent: true,
  layers: this.selectedValue.name,this.selectedValue.name,
  cql_filter: `${selectedField.name} > 0`, `${selectedField.name} > 0`
});


text:
Q: Splash Screen not showing up until all the steps of updating label in it is complete I have created a splash screen for a WinForm app. Everything works well until the splash screen is just a form with a background image and a label which has a static text - "Loading..."
I want to update the label continuously (with small delay in between) with texts - "Loading","Loading.","Loading.." and "Loading...". For this I have put the following code in my SplashScreen form:
private void SplashScreen_Load(object sender, EventArgs e)
{
    lblLoading.Refresh();
    lblLoading.Text = "Loading.";
    Thread.Sleep(500);
    lblLoading.Refresh();
    lblLoading.Text = "Loading..";
    Thread.Sleep(500);
    lblLoading.Refresh();
    lblLoading.Text = "Loading...";
    Thread.Sleep(500);
}

Now the Splash Screen doesn't appear until the label in it gets updated to "Loading..."
Please help to let me know what I am doing wrong.
Code in my HomeScreen:
public HomeScreen()
{
    //....
    this.Load += new EventHandler(HandleFormLoad);
    this.splashScreen = new SplashScreen();
}

private void HandleFormLoad(object sender, EventArgs e)
{
    this.Hide();
    Thread thread = new Thread(new ThreadStart(this.ShowSplashScreen));
    thread.Start();

    //...Performing tasks to be done while splash screen is displayed

    done = true;
    this.Show();
}

private void ShowSplashScreen()
{
    splashScreen.Show();
    while (!done)
    {
        Application.DoEvents();
    }
    splashScreen.Close();
    this.splashScreen.Dispose();
}

EDIT:
As suggested by some users here I have put the startup tasks in background thread and now I am displaying the Splash Screen from the main thread. But still the same issue persist. Here is the updated code of HomeScreen form:
    public HomeScreen()
{
    //...
    this.Load += new EventHandler(HandleFormLoad);
}
private void HandleFormLoad(object sender, EventArgs e)
{
    this.Hide();
    SplashScreen sc = new SplashScreen();
    sc.Show();

    Thread thread = new Thread(new ThreadStart(PerformStartupTasks));
    thread.Start();

    while (!done)
    {
        Application.DoEvents();
    }

    sc.Close();
    sc.Dispose();
    this.Show();
}

private void PerformStartupTasks()
{
    //..perform tasks
    done = true;
}

and here's the Splash Screen :
    private void SplashScreen_Load(object sender, EventArgs e)
    {
        lblLoading.Update();
        lblLoading.Text = "Loading.";
        Thread.Sleep(500);

        lblLoading.Update();
        lblLoading.Text = "Loading..";
        Thread.Sleep(500);

        lblLoading.Update();
        lblLoading.Text = "Loading...";
        Thread.Sleep(500);
}

A: You want a BackgroundWorker that posts ProgressChanged event, which will update the splash screen. The progress changed object could be a string, for example, that you'll display on your splash screen (back on the GUI thread).

A: You should handle the splash screen in the main thread, and the background work of initialising in the background thread (just as logixologist commented).
That said, the reason that your changed message doesn't show up is because the main thread is busy so it doesn't handle the events that redraws the control. Calling DoEvents in a background thread will only handle messages in that thread, and the messages to update the splash screen is in the main thread.
The Refresh method only invalidates the control, which would cause it to be redrawn if the main thread handled the event. You can use the Update method to force the redraw of the control:
private void SplashScreen_Load(object sender, EventArgs e)
{
    lblLoading.Text = "Loading.";
    lblLoading.Update();
    Thread.Sleep(500);
    lblLoading.Text = "Loading..";
    lblLoading.Update();
    Thread.Sleep(500);
    lblLoading.Text = "Loading...";
    lblLoading.Update();
}

But, this is only a workaround for the current code. You should really make the main thread handle the messages.

A: Thanks to all for answering my questions. Finally my issue is solved ! I changed my code such that start-up tasks are now being performed on a separate thread and splash screen is displayed from the Home Screen (main) thread. In the home screen I made use of Backgroundworker to update the 'Loading...' label.
I am posting my code here hoping it may also help someone in future..
For the Home Screen code plz see the EDIT part in my question. Here's the code of Splash Screen :
public SplashScreen()
    {
        InitializeComponent();
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.WorkerSupportsCancellation = false;
        lblLoading.Text = string.Empty;
    }

    private void SplashScreen_Load(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        while (true)
        {
            for (int i = 1; i <= 20; i++)
            {
                System.Threading.Thread.Sleep(200);
                worker.ReportProgress(i);
            }
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        string dots = string.Empty;
        for (int k = 1; k <= e.ProgressPercentage; k++)
        {
            dots = string.Format("{0}..",dots);
        }
        lblLoading.Text = ("Loading" + dots);
    }

A: You have to define a background worker in your splash screen form.
Here is an example of what your splash screen could look like :
public partial class SplashScreenForm<T> : Form
{
    private BackgroundWorker _backgroundWorker;
    private Func<BackgroundWorker, T> _func;

    private T _funcResult;
    public T FuncResult { get { return _funcResult; } }

    public SplashScreenForm(Func<BackgroundWorker, T> func)
    {
        this._func = func;

        InitializeComponent();

        this.label1.Text = "";

        this._backgroundWorker = new BackgroundWorker();
        this._backgroundWorker.WorkerReportsProgress = true;
        this._backgroundWorker.DoWork += new DoWorkEventHandler(_backgroundWorker_DoWork);
        this._backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(_backgroundWorker_ProgressChanged);
        this._backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_backgroundWorker_RunWorkerCompleted);

        _backgroundWorker.RunWorkerAsync();

    }

    private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        var worker = sender as BackgroundWorker;
        if (worker != null)
        {
            _funcResult = this._func.Invoke(worker);
        }
    }

    private void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        if (e.UserState != null)
        {
            this.label1.Text = e.UserState.ToString();
        }
    }

    private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        this.Close();
    }
}

You can design it the way you want, maybe a pretty gif image, or whatever you can think of.
Call it this way :
private void HandleFormLoad(object sender, EventArgs e)
{
    this.Hide();
    var splash = new SplashScreenForm<bool>(PerformTask);
    splash.ShowDialog(); // function PerformTask will be launch at this moment
    this.Show();
}

private bool PerformTask(BackgroundWorker worker)
{
    //...Performing tasks to be done while splash screen is displayed
    worker.ReportProgress("loading..");

}


text:
Q: How does max(list, key = list.count) work? If I have a list named as dataset, then I use max(dataset, key = dataset.count) to find the mode. Can someone tell me how max(dataset, key = dataset.count) works? It would be of great help!

A: The key argument tells the max function which max should be used. Default it will use the values of the elements itself.
dataset = [1, 1, 2, 2, 3, 4, 5, 6, 2, 1, 9, 2, 3, 2, 2, 2]
max(dataset) # 9, since 9 is the max value in this dataset
max(dataset, key=dataset.count) # 2 since 2 occurs the most in this dataset

# You can also use this:
sorted(dataset, key=dataset.count)
# [4, 5, 6, 9, 3, 3, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]

In the last example all elements are sorted from low to high based on the count (how often is the value in the dataset).


text:
Q: Replace and Remove character at the same time using regular expression I want to remove all the illegal character and replace the space with underscore so i use this code:
function sanitize_file_name($filename) {
    $filename = preg_replace("/([^A-Za-z0-9_\-\.]|[\.]{2})/", "", $filename);
    return basename($filename);
}

for example i have a filename like "www..//../no way" when i sanitize it, it become 'wwwno_way'.
it work to remove the other character that i want but the problem is i don't know how to replace the space with underscore at the same time using preg_replace. Is it posible? and how i can accomplish it?

A: In preg_replace() function the second param is the param you want to get replaced with.
function sanitize_file_name($filename) {
$filename = preg_replace("/([^A-Za-z0-9_\-\.]|[\.]{2})/", "_", $filename);
return basename($filename);
}


text:
Q: Remove QR Code after being Scanned I've tried reading the documents or search for other similar question to it in stackoverflow or online, but it's either I'm not googling correctly.I'm not sure how to remove the QRCode after it has been scanned.
Is displaying it in a
 tag wrong?
The QR code is generated from a type string not taken from a database.
Am I required to have a database and  a script running with intervals that checks whether the QR code has been read,
Am I assuming wrongly?
//in my file.ts
createCode() {
this.createdCode = this.qrData;
}

My code for displaying the scanned QR
//in my file.html
<ion-card *ngIf="createdCode">
  <ngx-qrcode [qrc-value]="createdCode"></ngx-qrcode>
    <ion-card-content>

Value: {{ createdCode}}

  </ion-card-content>
</ion-card>

If there are any relating questions that you have across please do refer me to it, as I'm not able to pin point over the few hours of looking trough.
Thank you in advance!

A: Never mind, I just had to add span class which handles closing it.
×

         <ion-card *ngIf="createdCode">
           <ngx-qrcode [qrc-value]="createdCode"></ngx-qrcode>
                <ion-card-content>

Value: {{ createdCode}}

                </ion-card-content>
            </ion-card>

and in file.scss add the following to display the closing button.
    .closebtn {
    margin-left: 15px;
    color: white;
    font-weight: bold;
    float: right;
    font-size: 22px;
    line-height: 20px;
    cursor: pointer;
    transition: 0.3s;
    color: black;
}


text:
Q: Option selection with PHP I have a problem, where I want to get a value from the database, and if the value matches the one in my option, the option should be selected.
This is my form:

  Vælg Antal Timer

    <select id="tidspunkt_varighed" name="tidspunkt_varighed" class="form-control">
      <option value="1">1 Time</option>
      <option value="2">2 Timer</option>
      <option value="3">3 Timer</option>
      <option value="4">4 Timer</option>
    </select>

I don't want to make an if clause every line.
Thanks in advance.
Kristian

A: You should use a loop as your values are incremental when check with one if() inside the loop for the checked value.

A: <?php
$options = '';
$valueFromDb = 1;
for($i = 1;$i<=4 ; $i++)
{
 if( $i  == $valueFromDb) {

   $options .= '<option value="'.$i.'" selected="selected">'.$i.'Time</option>';
} else {
 $options .= '<option value="'.$i.'" >'.$i.'Time</option>';
}

}
?>

  V�lg Antal Timer

    <select id="tidspunkt_varighed" name="tidspunkt_varighed" class="form-control">
   <?php echo $options;?>
    </select>

A: I think, you can use an array somehow like that:
<?
$value=YOUR_VALUE_FROM_DB
$selected[$value]="selected";
?>
<option value="1" <?=$selected[1]?>>1 Time</option>
<option value="2" <?=$selected[2]?>>2 Timer</option>

etc.

A: if you are not displaying these options using a loop then you have to put if with every option like
<option value="1" <?php if($dbvalue == 1){echo 'selected="selected"';}>1 Time</option>

and in case you are showing options using a loop you can put a condition in the loop and make a string like
    $selected = 'selected="selected"';
based on the condition, and echo $selected with every option.

A: $val_from_db = 3;

$output = '

  Vælg Antal Timer

    <select id="tidspunkt_varighed" name="tidspunkt_varighed" class="form-control">';

foreach( $values as $key=>$value ) {
    if ( $key==$val_from_db )
        $selected = 'selected="selected" ';
    else
        $selected = '';

    $output .= '<option '.$selected.'value="'.$key.'">'.$value.'</option>';
}

$output .= '</select>

';

echo $output;


text:
Q: Props not displaying from fetch call I am trying to display recipes and not sure if I have this setup correctly. I am pulling recipes from a rails api via get fetch request. At the moment nothing is displaying.
Here is my recipe container:
import React, { Component } from 'react'
import RecipeList from '../components/RecipeList'
import RecipeInput from '../components/RecipeInput'
import { connect } from 'react-redux'
import { postRecipes } from '../actions/postRecipes.js'
import { getRecipes } from '../actions/getRecipes'

class RecipeContainer extends Component{
    constructor(props){
        super(props)
    }

    componentDidMount(){
        getRecipes()
      }

    render(){
        return (

               <RecipeInput postRecipes={this.props.postRecipes} />
               <RecipeList getRecipes={this.props.recipes} />

        )
    }

}

const mapStateToProps = state =>({
   recipes: state.recipes
})

const mapDispatchToProps = dispatch =>{
    return{
    postRecipes: (recipe) => dispatch(postRecipes(recipe)),
    getRecipes: () => dispatch(getRecipes())
    // deleteRecipe: id => dispatch({type: 'Delete_Recipe', id})
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(RecipeContainer)

Here is my get request....notice that I am returning my Recipe component here.
export const getRecipes = () => {

    const BASE_URL = `http://localhost:10524`
    const RECIPES_URL =`${BASE_URL}/recipes`

    return (dispatch) => {
      dispatch({ type: 'START_FETCHING_RECIPES_REQUEST' });
      fetch(RECIPES_URL)
        .then(response =>{ return response.json()})
        .then(recipes => dispatch({ type: 'Get_Recipes', recipes }));
    };

  }

This is where I am trying to render the Recipe component from the get request
import React, {Component} from 'react';
// import { getRecipes } from '../actions/getRecipes.js';
import Recipe from './Recipe.js'

class RecipeList extends Component {

// componentDidMount(){
//   getRecipes()
// }

render() {

   return (

     {this.props.recipes.map(recipe => (<Recipe recipe={recipe} key={recipe.id} />))}

   )

  }
}

export default RecipeList;

Edit: Added reducer
switch(action.type){
        case 'Add_Recipe':
            const recipe = {

                name: action.name,
                ingredients: action.ingredients,
                chef_name: action.chef_name,
                origin: action.origin,
                category: action.category

            }

            return{
                ...state,
                recipes: [...state.recipes, recipe],
            }

          case 'START_FETCHING_RECIPES_REQUEST':
            return {
                ...state,
            recipes: [...state.recipes],
            requesting: true
        }
        case 'Get_Recipes':
            return {
                ...state, recipes: action.recipes,
                requesting: false
            }

          default:
            return state

    }
}

How can I correct this to make it work?

A: Issue
You are not passing the recipes to the RecipeList component that were fetched and presumably stored in state, and fed back to the UI via RecipeContainer.
Solution
Pass the recipe state from RecipeContainer to RecipeList as a prop. and then render/map the recipes from props.
RecipeContainer
class RecipeContainer extends Component{
  componentDidMount() {
    getRecipes();
  }

  render() {
    return (

        <RecipeInput postRecipes={this.props.postRecipes} />
        <RecipeList getRecipes={this.props.recipes} /> // <-- pass recipe state

    )
  }
}

const mapStateToProps = state => ({
  recipes: state.recipes,
});

const mapDispatchToProps = dispatch => {
  return {
    postRecipes: (recipe) => dispatch(postRecipes(recipe)),
    getRecipes: () => dispatch(getRecipes())
  }
};

RecipeList
class RecipeList extends Component {
  render() {
    const { recipes } = this.props;
    return (

       {recipes.map(recipe => (
         <Recipe recipe={recipe} key={recipe.id} />
       ))}

     );
  }
}

A: The actual solution to this was I needed to have an explicit return in my mapStateToProp function.
Eg.
const mapStateToProp = state =>{
  return {
         recipes: state.recipes
    }
}


text:
Q: Min cut using matlab cvx I am trying to detect communities using binary min cut on users' graph. For this purpose I am trying to use a variant of Fiedler method as shown in this paper. This is how they have formalized it:

Now, I am trying to do this using the CVX package in matlab. Here is my code:
tou = ((beta/ (e' * pi1 * e)) * tou1) + (((1 - beta) / (e' * pi2 * e)) * tou2);
n = 6;
cvx_begin
    variable y(n)
    minimize( y' * tou * y )
    subject to
        y' * pi1 * y == e' * pi1 * e
        y' * pi2 * y == e' * pi2 * e
        y' * pi1 * e == 0
        y' * pi2 * e == 0
cvx_end

But it is showing me the following error:
Disciplined convex programming error:
Invalid constraint: {convex} == {real constant}

Error in ==> cvx.eq at 12
b = newcnstr( evalin( 'caller', 'cvx_problem', '[]' ), x, y, '==' );

Error in ==> fiedler at 16
y' * pi1 * y == e' * pi1 * e

Here A1 is a matrix defined as follows:
A1 = [0 3 2 0 0 0; 3 0 3 1 0 0; 2 3 0 0 0 0; 0 1 0 0 4 2; 0 0 0 4 0 3; 0 0 0 2 3 0];

Similarly A2 = A1.
And pi1 is a matrix is a diagonal matrix whose value is equal to sum of all the values of A1 in that particular row. Doing so I get
pi1 = [5 0 0 0 0 0; 0 7 0 0 0 0; 0 0 5 0 0 0; 0 0 0 7 0 0; 0 0 0 0 7 0; 0 0 0 0 0 5];

Similary, pi1 = pi2.
And tou1 = pi1 - A1, and tou2 = pi2 - A2.
Can someone point out what exactly I am doing wrong. It would be of great help. Thanks in advance !

A: This issue is that your constraint
  y'* pi1 * y == alpha

(where alpha = e'*pi1*e ) is not a convex constraint. Consider the two dimensional case where size(y) = [2 1] and pi1 is the identity, then your constraint above is
       y(1)^2 + y(2)^2 == alpha

This is equivalent to requiring y to lie on the radius of a circle. This is not convex constraint.
CVX is designed for disciplined convex optimization. This means that you must build your model up from primitives in a way that ensures the model is convex. Since your model includes a constraint that is not convex CVX issues the error: "Disciplined convex programming error".
It also tells you the problem: "Invalid constraint {convex} == {real constant}". That tells you that you are trying to constrain a convex function to be equal to a constant.
If you want to solve this model with CVX you will need to reformulate the model to be convex. If you can't reformulate it, you might try using a nonlinear (noncovex) solver. For example, fmincon included in MATLAB should be able to handle this constraint. Note that fmincon is designed for fairly small scale models, for large scale nonlinear noncovex models you probably want to use a solver like SNOPT or KNITRO.

A: For the original problem, the equality constraints can be usually relaxed by replacing equal sign (=) with <=. Most of the time, the solution will satisfy the equality constraints (but not guaranteed).
The original problem can e relaxed as follows:
tou = ((beta/ (e' * pi1 * e)) * tou1) + (((1 - beta) / (e' * pi2 * e)) * tou2);
n = 6;
cvx_begin
 variable y(n)
 minimize( y' * tou * y )
 subject to
     y' * pi1 * y <= e' * pi1 * e
     y' * pi2 * y <= e' * pi2 * e
     y' * pi1 * e <= 0
     y' * pi2 * e <= 0
cvx_end

You need to verify if the solution (or pick one of the solutions) satisfies the equality constraint.
Hope it works for the OP.


text:
Q: When test Auto-Renewable subscription Sandbox account ask for credential as app launch. Is this also happen after application live? I implemented Auto renewable subscription using RMStore.
In home screen (After launch) I implement the functionality for verify user.
But with sandbox its ask apple id and password. So how to resolve this.
Also I want to know that the same think happen after application approved by app store ?

A: As i can understand its happening just because of your uncompleted transactions.
So if you want to resolve this issue you must have to finish your all uncompleted transaction.
You can use below code to finish your transactions. Put below code inside
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        for transaction:SKPaymentTransaction in SKPaymentQueue.default().transactions {
            SKPaymentQueue.default().finishTransaction(transaction)
        }
    }


text:
Q: Finding Occurrences In The Future, Periods And Start Dates Okay, I'll simplify this post.
I have a table "tasks" containing, for example, a task name, the date it starts, and a frequency.  Based on these fields I need to be able to specify a date range and return each occurrence of that task for when it's due.  For example, if I have a task with the frequency of M (for monthly) and my date range is today and a year in the future, then I will return twelve occurrences of that task from my output.
You'd think this is simply, but I've spent the last few days bleeding from my eyes trying to figure this one out.  The output needs to also say when the task is next due.

A: How about something like this. You can expand the case to allow for other frequencies
DECLARE @Table TABLE(
        TaskName VARCHAR(10),
        StartDate DATETIME,
        Frequency VARCHAR(10) --let say D,W,M daily, weekly, monthly
)

INSERT INTO @Table (TaskName,StartDate,Frequency) SELECT 'TADA', '15 Jan 2009', 'M'

DECLARE @StartDate DATETIME,
        @EndDate DATETIME

SELECT  @StartDate = '27 Nov 2009',
        @EndDate = '27 Nov 2010'

;WITH cte AS(
    SELECT  TaskName,
            StartDate,
            Frequency
    FROM    @Table
    UNION ALL
    SELECT  TaskName,
            CASE
                WHEN Frequency = 'M' THEN DATEADD(mm,1,StartDate)
            END,
            Frequency
    FROM    cte
    WHERE   StartDate <= @EndDate
)
SELECT  *
FROM    cte
WHERE   StartDate BETWEEN @StartDate AND @EndDate
OPTION (MAXRECURSION 0)


text:
Q: How to get the correct battery status? At this moment, ever since I installed Ubuntu on this machine, the battery status says: not present.
Looking at this answer, however, I find that /proc/acpi/battery/BAT1/info (sometimes its /proc/acpi/battery/BAT0/info, use tab complete to help) has the following info:
present: yes
design capacity: 4400 mAh
last full capacity: 4400 mAh
battery technology: rechargeable
design voltage: 11100 mV
design capacity warning: 300 mAh
design capacity low: 132 mAh
cycle count: 0
capacity granularity 1: 32 mAh
capacity granularity 2: 32 mAh
model number: BAT1
serial number: 11
battery type: 11
OEM info: 11

In accordance to this answer, I've checked the /proc/acpi/battery/BAT1/state file:
present:                 yes
capacity state:          ok
charging state:          charged
present rate:            unknown
remaining capacity:      unknown
present voltage:         10000 mV

The acpi -b command returns:
Battery 0: Unknown, 0%, rate information unavailable

Any suggestions on getting the battery info updated?

A: The acpi -b error you have reported most probably indicate an ACPI type issue.
ACPI is an open-standard for device and power-management.
Some laptops (most googled that I found were Acer) incorrectly report its battery details to Ubuntu.  I'm not sure of your laptop type and model - nor its BIOS version.
Sometimes you need to compile your own kernel with a fixed DSDT table.
Sometimes you need to upgrade your BIOS to the very latest offered by your manufacturer.
If you decide on the latter action you should remember that updating the BIOS of a motherboard or laptop is always a risky operation, because if something goes wrong, the risk of irreparably damaging the hardware is very high.
You will need to follow the instructions for BIOS updates from your manufacturer.

A: I was able to solve this problem using fossfreedom's suggestion to update BIOS.  I have an Acer Aspire TimelineX 4820T, running ubuntu 11.10.  Here's what I did:

*

*sudo apt-get install unetbootin

*inserted blank flashdrive, used diskutil to format it to FAT

*downloaded the CORRECT bios update from Acer (I typed in my serial number and used the latest bios update .exe file)

*used unetbootin to make the USB bootable with FreeDOS

*copied the bios .exe file to the USB drive

*restarted and chose option "5" for FreeDos

*switched to C: drive and ran the bios executable.  (Make sure you have enough power, although this doesn't take very long)

*removed USB drive, rebooted into Ubuntu and battery problem was solved!

Thanks go to 4zzdawg for instructions on how to update the bios!


text:
Q: Virtual Key Code converter (character to int) There's a way to convert a character (@"A") to CGKeyCode (cocoa development)? I've already tried a lot of "solutions", but none worked.
I already implemented the keyCodeForKeyString method, but it is really short and don't include all of the characters in a keyboard.

A: This question appears to answer the same (or very similar) question:
How to convert ASCII character to CGKeyCode?


text:
Q: Hacer una animación con css que al darle click al modal aparezca de izquierda a derecha El código lo pongo en los comentarios; es un modal que se abre al apretar un botón, necesito darle una transición de derecha a izquierda cuando se abra y cuando se cierra de derecha a izquierda.
       .modalSecundario{
            margin-left: 40px;
            position: fixed;
            z-index: 9999;
            top: 0;
            left: 0;
            width: 100%;
            height: 100vh;
            background-color:rgba(0,0,0,0.75);
            display: none;
            justify-content: center;
            align-items: center;

        }

        .fadee{
            transition: opacity .15s linear;
        }

        .modalSecundario.show{
            display: flex;
            // flex-direction: column;
        }

        .modalSecundario-container{
            position: relative;
            padding: 2rem;
            width: 100%;
            height: 100vh;
            overflow-y: auto;
            background-color: #fff;
            //inicializo la transición
            -webkit-transform: translate3d(0%, 0, 0);
            -ms-transform: translate3d(0%, 0, 0);
            -o-transform: translate3d(0%, 0, 0);
            transform: translate3d(0%, 0, 0);
            &.fadee {
                .modalSecundario-container {
                    //creamos la transición
                    right: -320px;
                    -webkit-transition: opacity 0.3s linear, right 0.3s ease-out;
                    -moz-transition: opacity 0.3s linear, right 0.3s ease-out;
                    -o-transition: opacity 0.3s linear, right 0.3s ease-out;
                    transition: opacity 0.3s linear, right 0.3s ease-out;
                }
                &.show {
                    .modalSecundario-container{
                        right: 0;
                    }
                }
            }
        }

        .modalSecundario-close{
            position: absolute;
            top: 22px;
            left: 3.3rem; //izquierda
            background-color: transparent;
            border: none;
        }
        .ARROWLEFT path {
            fill: #001E50;
        }
        .spanBoton{
            color: #000000;
            font-size: 12px;
            font-family:'VWText-Regular';
            margin-left: 8px;
        }

<article className={`modalSecundario fadee ${isOpen ?'show':''}`} onClick={closeModal}>
     <div className={`modalSecundario-container fadee`} onClick={handleModalContainerClick}>
        <button className='modalSecundario-close' onClick={closeModal}>
             <ARROWLEFT />

                  Atrás

        </button>

            {children}


text:
Q: JavaScript: Set background of radio button when deselected (group of radio buttons) I am trying to create a simple interactive form for use with touch screen devices. The majority of the form is made up of radio buttons in groups of 5 (approx. 37 groups). I have a label tag for each radio button, and when selected (clicked),  the background-color property of the label is changed to a highlighted colour using this JavaScript within each label tag OnClick="this.style.background='#5555ff';"
What I want to add to the above, is a JavaScript that will remove the above if the selection is changed within the group. E.g. A user selected radio button A in group 1, then changes their selection to radio button B in group 1. At the moment, both label backgrounds will be changed to the defined colour.
The HTML form is created dynamically by PHP so radio button names, IDs, & values will differ.
I have been unsuccessful trying to complete this task myself, and there doesn't seem to be a simple OnUnClick="xxx" either. I have searched on here for a solution but no questions match mine, although I have tried tweaking existing solutions to similar problems but to no avail.
Thank you for reading!

A: assuming your radio buttons are grouped in a divs like this -

    <INPUT TYPE=RADIO NAME="pizzasize" VALUE="S">small

    <INPUT TYPE=RADIO NAME="pizzasize" VALUE="M">medium

    <INPUT TYPE=RADIO NAME="pizzasize" VALUE="L">large

You can do something like this in jquery -
$('input[type="radio"]').click(function(){
    var parentElement = $(this).parent();
    parentElement.find('input').css('background', '#000000'); //set to your neutral background for radio buttons
    $(this).css('background', '5555ff');
});

A: Here you go:
HTML

        <input type="radio" id="g1v1" name="g1" value="v1" checked="checked"/> V1

        <input type="radio" id="g1v2" name="g1" value="v2" /> V2

        <input type="radio" id="g1v3" name="g1" value="v3" /> V3

        <input type="radio" id="g1v4" name="g1" value="v4" /> V4

Javascript
$(document).ready(function(){
    var selectedRadioColor = "yellow";
    var normalRadioColor = "gray";
    // For changing color while document loads
    $.each($(":radio"), function(){
        //alert( $(this).prop("id")+ $(this).prop("checked") );
        if($(this).prop("checked") == false)
        {
            $(this).parent().css("color", normalRadioColor);
        }
        else
        {
            $(this).parent().css("color", selectedRadioColor );
        }
    })
    // For updating color when user interacts with radio buttons
    $(":radio").click(function(){
        $("[name='"+$(this).prop("name")+"']").parent().css("color", normalRadioColor);
        $(this).parent().css("color", selectedRadioColor );

    })
})

Here is the link to jsfiddle for live demo:
http://jsfiddle.net/dharmavir/6UnDs/


text:
Q: How to get PID of perl daemon in init script? I have the following perl script:
#!/usr/bin/perl

use strict;
use warnings;
use Proc::Daemon;

Proc::Daemon::Init;

my $continue = 1;
$SIG{TERM} = sub { $continue = 0 };

while ($continue) {
        # stuff
}

I have the following in my init script:
DAEMON='/path/to/perl/script.pl'
start() {
    PID=`$DAEMON > /dev/null 2>&1 & echo $!`
    echo $PID > /var/run/mem-monitor.pid
}

The problem is, this returns the wrong PID! This returns the PID of the parent process which is started when the daemon is run, but that process is immediately killed off. I need to get the PID of the child process!

A: The Proc::Daemon says

Proc::Daemon does the following:
  ...
  9. The first child transfers the PID of the second child (daemon) to the parent. Additionally the PID of the daemon process can be written into a file if 'pid_file' is defined. Then the first child exits.

and then later, under new ( %ARGS )

pid_file
  Defines the path to a file (owned by the parent user) where the PID of the daemon process will be stored. Defaults to undef (= write no file).

Also look at Init() method description. This all implies that you may want to use new first.
The point is that it is the grand-child process that is the daemon. However, the childr passes the pid along and it is available to the parent. If pid_file => $file_name is set in the constructor (the daemon's) pid is written to that file.

A comment asks to not have shell script rely on a file written by another script.
I can see two ways to do that.

*

*Print the pid, returned by the $daemon->Init(), from the parent and pick it up in the shell. This is defeated by redirects in the question, but I don't know why they are needed. The parent and child exit right as all is set up, while the daemon is detached from everything.

*Shell script can start the Perl script with the desired log-file name as an argument, letting it write the daemon pid to that file by the above process. The file is still output by Perl, but what matters about it is decided by the shell script.
I'd like to include a statement from my comment below. I consider these superior to two other things that come to mind: picking the filename from a config-style file kept by the shell is more complicated, while parsing the process table may be unreliable.

A: I've seen this before and had to resort to using STDERR to send back the childs PID to the calling shell script.  I've always assumed it was due to the mentioned unreliability of exit codes - but details were not clear in the documentation.  Please try something like this:
#!/usr/bin/perl
use strict;
use warnings;
use Proc::Daemon;

if( my $pid = Proc::Daemon::Init() ) {
    print STDERR $pid;
    exit;
}

my $continue = 1;
$SIG{TERM} = sub { $continue = 0 };

while ($continue) {
    sleep(20);
    exit;
}

With a calling script like this:
#!/bin/bash
DAEMON='./script.pl'
start() {
    PID=$($DAEMON 2>&1 >/dev/null)
    echo $PID > ./mem-monitor.pid
}
start;

When the bash script is ran, it will capture the STDERR output (containing the correct PID), and store it in the file.  Any STDOUT the Perl script produces would be sent to /dev/null - though this is unlikely as the 1st level Perl script does (in this case) exit fairly early on.

A: Thank you to the suggestions from zdim and Hakon. They are certainly workable, and got me on the right track, but ultimately I went a different route. Rather than relying on $!, I used ps and awk to get the PID, as follows:
DAEMON='/path/to/perl/script.pl'

start() {
    $DAEMON > /dev/null 2>&1
    PID=`ps aux | grep -v 'grep' | grep "$DAEMON" | awk '{print $2}'`
    echo $PID > /var/run/mem-monitor.pid
}

This works and satisfies my OCD! Note the double quotes around "$DAEMON" in grep "$DAEMON".


text:
Q: Isolate brown by rgb values I am looking to isolate "brown" colors by rgb values. Not just 1 brown color, but the wide spectrum of colors that are perceived as brown - tan, suede, dirt, etc.
Any ideas on how to do this? I'm thinking that maybe if Red is less than 128, and Green is between 70 and 138, and blue is less than 128, than it appears brown. Something along those lines.

A: A really simple heuristic would be something like, in pythony pseudocode
def isBrown(red, green, blue):

  # Kind of maximum lightness
  if blue > parameter_1
    return False

  # how green or red tinted can it be
  if absolute_value(red - green) > parameter_2:
    return False

  # Light brown is just yellow or orange
  if maximum_of(red, green) > parameter_3:
    return False
  else:
    return True

The tune parameters 1 through 3 until it works nicely. Perhaps replace if absolute_value(red - green) > parameter_2: with if absolute_value(red - green*parameter_2b) > parameter_2a: so that more greeny or reddy ones are selected depending on parameter_2b. Perhaps change maximum_of to something else. etc. etc.

A: It really depends what you consider to be brown. It is a colour category for which there is rather high inter-subject variability and strong contextual effects (colours next to it changes how it looks).
Think you need to use something like this: http://www.colorpicker.com/ and look at the shape of the colours you decide on and then work out how to express that algorithmically.


text:
Q: How Can I Get minute() to Return 00 instead of 0? I am working on pulling time data from a dttm object in R and formatting it in HH:MM. I have been able to accomplish this using
paste(hour(datetime), minute(datetime), sep=':')

with one exception: when the minutes are less than 10. When I do this, the minute function just returns the minutes without a leading 0. For example:
library(lubridate)

datetime = ymd_hms('2018-11-18 14:00:00')

minute(datetime)

This gives an output of
> minute(datetime)
[1] 0

I believe there are options using hms or other packages/functions, or by building an if-then, but I'd like to minimize dependencies and complexity and stick within the particulars of lubridate to accomplish my goal if at all possible.
(Note: I realize the same issue exists for hour(), but all the times I'm using are PM, so it's not as pressing in my case).

A: With format you can get your own custom date format after specifying -
> format(datetime, "%M")
[1] "00"

OR
Thanks @Ronak -
> sprintf("%02d", minute(datetime))
[1] "00"

A: Why are you doing all this extra work? Just get the time directly from your datetime (POSIXct) object.
strftime(datetime, "%H:%M")
# [1] "14:00"