text:
Q: Merge sorted lists I have a few .txt files (in the same directory) that look like this:
   123 carrot
    50 apple
    13 tomato
     5 potato
     2 pear

and
   100 carrot
    10 apple
     3 tomato
     2 potato

I need to merge them into one sorted list. So if I only had two lists above, I'd get
   223 carrot
    60 apple
    16 tomato
     7 potato
     2 pear

Is there an easy way to do this with shell commands, or should I start writing code?
Thank you!

A: Where is the line between "shell commands" and "code"? This example is perhaps beyond that line, but it is just a quick aggregation function in awk that I already had written for another (more elaborate) purpose, so I might as well post it.
Assuming the files are located in the directory dir/, awk could sum them as such:
awk '
    {fruits[$2]+=$1}
    END { for (fruit in fruits) {printf "%6s %s\n", fruits[fruit], fruit} }
' dir/* | sort -rn

Breakdown:

*

*Check every line in all files and add the value of the first field to the existing value of the index of that fruit in the array fruits (or create that index if it does not exist).

*When the files have been traversed, loop over the indices in fruits and print their value and their name in your specified format.

*Array sorting in awk is possible, but it's a lot easier on the eye to just use sort. -rn sorts numerically in descending order.


text:
Q: SQL if i dont give a value it will insert as null.if it has a value it will be inserted onto the database Good morning i want to know how can i insert a null value when the user do not dont give a value in the field but when the user give a value it wil insert onto my database
<?php
require "connect.php";

if($_SERVER['REQUEST_METHOD']=="POST"){
    $data = json_decode(file_get_contents('php://input'), true);
    // echo var_dump($data);
    $response = array();

    $vesselid = $data['vesselid'];

This the datatype of my values anchor and berth are timestamp
this are the values that i want to insert null or not

     $anchor_eta = $data['anchor_eta'];
        $anchor_ata = $data['anchor_ata'];
        $anchor_etd = $data['anchor_etd'];
        $anchor_atd = $data['anchor_atd'];
        $berth_eta = $data['berth_eta'];
        $berth_ata = $data['berth_ata'];
        $berth_etd = $data['berth_etd'];
        $berth_atd = $data['berth_atd'];

   //up to here

checking for my vessel id if my vessel id already exist
  $check = "SELECT * FROM vessel_transaction WHERE vesselid='$vesselid'";
    $result = mysqli_fetch_array(mysqli_query($con,$check));

    if(isset($result)){
        $response['value'] = 2;
        $response['message'] = "Record Already Exist";
        echo json_encode($response);
    }

   else{

this is my insert query
 $insert = "INSERT INTO vessel_transaction(vesselid,anchor_eta,anchor_ata,anchor_etd,anchor_atd,berth_eta,berth_ata,berth_etd,berth_atd) VALUE ('$anchor_eta','$anchor_ata','$anchor_etd','$anchor_atd','$berth_eta','$berth_ata','$berth_etd','$berth_atd')";
    // echo json_encode($insert);
    if (mysqli_query($con,$insert)) {
        $last_id = mysqli_insert_id($con);
        // echo $last_id;
        $queryResult = $con->query("SELECT transaction_id from vessel_transaction where id = $last_id");
            $result = array ();
            while($fetchData = $queryResult->fetch_assoc()){
                $result = $fetchData;
            }
        $response['value'] = 1;
        $response['message'] = $result;
        echo json_encode($response);
    }
    else{
        $response['value'] = 0;
        $response['message'] = "Failed to Add";
        echo json_encode($response);
    }

   }

}

?>

A: Explanation
First, make sure that variables which optional inserted to have a default values.
For instance,
Code Section
PHP CODE SECTION
// String variables
$stringVar = "default value"

//Numerical variables
$numVar = 0

//Boolean Variables
$bool = FALSE //or true depending on your condition
// others
$others = NULL

SQL CODE SECTION
Every time the user leaves this field, there's a default value that will be appended into the database without having any tribble.
But, Make sure your database variables constraints isn't indicate NOT NULL
For Instance,
CREATE TABLE IF NOT EXISTS test(
    Id INT NOT NULL, -- This variable must have value.
    name VARCHAR(30),
    phone INT -- This variable isn't mandatory to have a value.
);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disadvantages of using MARS (multiple active result sets)
Possible Duplicate:
Disadvantages of MARS (Multiple Active Result Sets)?

I am developing an application such that i have to use multiple DataReaders at the same time.
When i say Multiple datareaders i mean MULTIPLE DATAREADERS... there would be a few required at the same time.(something around 10-50 or more)

So one scenario that i came across was to use different connection strings.. but implementing that i feel awkward!!!
Another method is to use MARS which i found it was pretty decent. but my doubt is that do i need to consider or take any precautions when i implement it or is something vicious waiting for me to happen :-)
from my so called research what i was able to find was that by using MARS the server produces data fast, so the client app must receive the data at the same speed it comes in. else the data storage buffer will be filled leading to the processing to stop.. and will be enabled only when the buffer gets empty..

i got lost somewhere around here....
Also i am using only Select statements only for this reqiurement..
so my question is that are there any disadvantages using them??
how much of of data can be stored in the server data buffer such that the processing wouldn't stop??

A: I suggest you use multiple connections, if it's really necessary to read from 100 datasets at once.  I can't see why you'd need to have multiple active datareaders on a single connection.
It's more likely the query or task you are trying to achieve can be done without needing to do this large parallel operation, however.  If you can be more specific with some details perhaps we can work out a good few alternative suggestions.


text:
Q: Elasticsearch painless script orders array items I need a help about getting an array item with indice ([0] e.g.) in elasticsearch. Whatever painless or scriptless behaviour.
Here is my little test mapping, document and results;
"mappings": {
    "tip": {
        "properties": {
            "name": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "props": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            }
        }
    }
}

And I indexed one document like that;
{
    "name": "burak",
    "props": [
        "4",
        "2",
        "3"
    ]
}

When I get "props" values with painless script the values of props fetched as ordered. I don't want this, how can I fix it ?
{
  "script_fields": {
    "FIELD": {
      "script": {
        "inline": "doc['props.keyword']",
        "lang": "painless"

      }
    }
  }
}

The result was;
"fields": {
          "FIELD": [
            "2",
            "3",
            "4"
          ]
        }


text:
Q: How to get php readline() to default to Vim mode? This is on CentOS 7.2, PHP version 5.6.20. According to readline_info():
<?php
print_r(readline_info());

gives
Array
(
    [line_buffer] =>
    [point] => 0
    [end] => 0
    [library_version] => EditLine wrapper
    [readline_name] =>
    [attempted_completion_over] => 0
)

OK, so readline() is using EditLine. I created a ~/.editrc file with:
bind -v

The permission is 664. I then tried:
<?php
    $line = readline('Enter: ');

But it doesn't seem to read the file, and it's not in Vim mode. Doing an Alt-X followed by a manual command of "bind -v" puts it in Vim mode, so I know it has Vim mode.
I read somewhere else that I might need to manually set the path in an environment variable. So tried setting the full path:
$ export EDITRC=/home/work/.editrc

Still nothing. I've also seen that "export EL_EDITOR=vi" is supposed to work, but still doesn't work.
Does anyone have any way to make this work? I really need Vim mode to work.


text:
Q: How can I translate this email attachment to read it in English? I know nothing about coding but received an email attachment as .txt opened and all I can see are a bunch of characters like
 %S^$^%$$////
is there a way to translate it?
Can you direct me to a program that will do this?
I ask because this email came from his work email 2 days before his death.

A: It's possible that the file is a zip or a pdf or a docx or a thousand other things. And you could poke around wikipedia and find the format rules for such file types. Most of them start with a highly recognizable sequence of characters. I blogged about doing this once at http://www.gregcons.com/KateBlog/IDoLoveSolvingAMystery.aspx and recommended Marco Pontello's absolutely cool File Identifier, TrID, which you could try.
BUT - why don't you just hit reply and ask the person what they sent you? If you don't know them, the mystery attachment is probably malicious. Don't open it. If you know them, ask them what's in the attachment.

A: Many office firewalls block the email of certain types of attachments.  He may have renamed the file to avoid this issue.
Try pasting the first few characters into google.. it may be able to tell you the file type.. then rename the .txt file to the true filetype and try opening it.
I would run a virus scanner on it before attempting this though.  It's quite possible it's a malicious worm that your friend didn't know about.

A: It would help to know which email clients were you and your friend using, and the name of the attachment.
It would also help, unless it's too personal, to post the received mail for us.
To save the mail, use Save As in your client (normally in .eml format), or drag the mail to the desktop (if this is supported).
I don't suppose that the attachment is called winmail.dat by any chance?
(Dealing with the winmail.dat file)
Add a comment to this answer, if you do wish me to have a look at this email.

A: There are various applications to identify file types by their content. On Linux/Unix e.g. there's [file][1], which is invoked on the command line simply as
file *unknownfile*

and will tell you the type it guessed. It does not recognize everything, but still a lot.
If you don't have access to a Linux computer, any modern Linux LiveCD (e.g. Ubuntu) will do.
You might also want to consider whether the file is really a text file, but in an uncommon encoding. Do you know which language the text is likely in? If it's some Asian language, it might just be an unusual encoding.

A: It's possible that it could be an encoding problem. Encoding is the way that your computer interprets and displays a file containing text. If the file contains characters that are not supported in a specific encoding, it could create a problem like the one you describe. If you open the file in a text editor with multiple encoding support (other than the default Notepad, unfortunately) you may be able to choose a function such as "Reload As..." and then choose from a list of encodings. Your best bet might be to try to load it as a Unicode (UTF) encoding.
See here for more information about encoding.

A: You can use TrID to identify the file type.


text:
Q: java - reading .properties file and storing it in properties object As mentioned in the title I have to read a .properties file in java and store it in a Properties object. I use a jFileChooser from java swing to get the file, which actually works, then I pass the file to a new window as calling arguments and then I use the load() method to store it in a Properties object but I get the java.lang.NullPointerException error. I hope I was clear as trying to explain it.
This is the code:
    public void actionPerformed(ActionEvent e3) { //when button is pressed
            JFileChooser fc2 = new JFileChooser (new File("C:\\Users\\Ciurga\\workspace\\PropertiesManager"));
            fc2.setDialogTitle("Load Default Values File");
            fc2.setFileFilter(new FileTypeFilter(".properties", "Properties File"));
            int result = fc2.showOpenDialog(null);
            if(result == JFileChooser.APPROVE_OPTION){
                df = fc2.getSelectedFile(); //getting selected file and storing it in "df" which will be passed as calling argument
                defaultNameTextField.setText(df.getName());
            }
        }

This is how I pass the file to the other window:
public void actionPerformed(ActionEvent e1) {
            FormWindow w1 = new FormWindow (df, lf); //when button is pressed, create new window passing the files i got with jFileChooser
        }

And this is how I tried to store it in a Properties object:
private static Properties propDef;
private static Properties propLim;

private void run(File def, File lim) {
    try {
        propDef.load(new FileInputStream(def));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        propLim.load(new FileInputStream(lim));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(propDef.getProperty("name"));

}

Thank you guys, as you said I only had to initialize it and now it seems to work correctly, it was a simple error but I'm actually a beginner in java.
This is what I changed:
private static Properties propDef = new Properties();
private static Properties propLim = new Properties();

A: You never initialised propDef, thats why you get the NullPointerException.
If you did initialise it, please provide the code!

A: Probably, your propDef and propLim are null and when you call  propDef.load(new FileInputStream(def)); you get a NPE because load method is instance method.


text:
Q: Total power measurement in 3-phase unbalanced delta system I have a 3-phase system with an unbalanced delta load, as seen in the figure below.
I want to measure the total apparent and active power consumption and if possible, the respective power consumption for each of the phases, but I am a bit confused.
I am using a 3-phase equipment from National Instruments which shows that Vc = 380V, Vb = 380V and Vc = 0V. I assume that because of the absent neutral, it uses phase A as a reference, thus Vc = Vca, Vb = Vba.
I am also measuring all three line currents.
What is the total apparent power equation? I am aware of Blondel's Theorem, but it is valid only when measuring instant power right?
Also, is it possible to measure the power of each separate phase?

A: *

*The 3 Power meter method uses the meter impedance to create a virtual Y neutral node with 3 V readings

*Thus 3 meter method can measure the P in each phase and total.

*Using scalar VA products in each phase can get any result you need (VAR, PF)

*the total apparent power (scalar product) can also be measured using true Vrms* true Irms

*the reactive power can be computed by vector geometry.


text:
Q: Get raw HTTP response with Retrofit - Flutter How can I get raw http response with Retrofit?
I've tested with Response and ResponseBody, but both of the failed and said:
type 'String' is not a subtype of type 'ResponseBody?'

I'm receiving a tar file, that's why I need to get a raw response to then call Response.body, to parse it with TarReader.
Expected behavior:
be able to get a raw bytes of the response body.
Thanks.

A: You cant try to use HttpResponse from official source - https://pub.dev/packages/retrofit#get-original-http-response
@GET("/file")
Future<HttpResponse> getFile();


text:
Q: Adding a button I want to create a new button. This code is in my MainActivity.
public void method1 (View view)
{
    Button myButton = new Button(this);
    myButton.setText("Press Me");
    LinearLayout layout = (LinearLayout) findViewById(R.id.layout1);
    layout.addView(myButton);
}

I get an error on R.id.layout, saying layoutcan´t be resolved or is not a field. How can I fix it? I am a newbie on Android.
//Edit
my acitvity_main.xml looks like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp"
    android:onClick="neuerTrainingsplan"
    android:text="@string/neuerPlan" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/button2"
    android:layout_alignBottom="@+id/button2"
    android:layout_toLeftOf="@+id/button2"
    android:onClick="TrainingsplanAbrufen"
    android:text="@string/TrainingsplanAbrufen" />

A: The error means that you haven't declared a layout with id layout1. If you have check the import from your class in order to import the correct R class. Should be yourpackage.R not android.R

A: Make sure you made the linear layout in your xml file. And its android:id is layout1.
<LinearLayout android:id="@+id/layout1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />

Add this is in your layout file.


text:
Q: How to fetch line numbers for all 'if' 'else' and 'elif' positions in a python file Example: Suppose, we have a .py file containing the below code snippet. How do we read and extract the positions of if-elif-else
If fisrtconditon:#line 1
    If sub-condition:#line2
       print(line no 3)
elif secnd_condn:#line 4
     Xyz..#line5
     Xyz..#line6
elif third condition:line7
     ...line 8
else:#line 9
    Some content #line10***

Output:
[1,4,7,9]

A: You can use the ast module.
import ast

with open('file.py') as f:
    tree = ast.parse(f.read())  # parse the file

for node in ast.walk(tree):  # walk the tree
    if isinstance(node, ast.If):  # if the node is an If (or an If-else)
        print('If at line', node.lineno)  # print the line number
        if node.orelse:  # if the node has an else
            if isinstance(node.orelse[0], ast.If):  # if the else is an If
                print('Elif at line', node.orelse[0].lineno)  # print the line number
            else:
                print('Else at line', node.orelse[0].lineno)  # print the line number

ast is part of the standard library, so there's no need to install anything. It stands for Abstract Syntax Tree, and it's a representation of the structure of your code. You can find more information in the ast module documentation.

A: A simple solution is to iterate over the lines of the file, using enumerate to help you get the line number:
with open("somefile.py") as f:
    for line_no, line in enumerate(f, start = 1):
        if line[:2] ==  "if" and (line[2].isspace() or line[2] == "("):
            print(line_no, "if")
        elif line[:4] == "elif" and (line[4].isspace() or line[4] == "("):
            print(line_no, "elif")
        elif line[:4] == "else" and (line[4].isspace() or line[4] == ":"):
            print(line_no, "else")

Assumptions: this program assumes that somefile.py has correct syntax. Moreover, if this if statement appears indented, for example, inside a function definition, it would not work. The question's specifications did not dictate this requirement.
This program

*

*opens the file "somefile.py" for reading (the default mode of open);

*iterates over the lines of the file, using enumerate to get an index; by default, indices will start from 0 but we specify the start parameter so that it starts from 1;

*if the line starts with an if plus a (whitespace character or opening paren) or an elif plus a (whitespace character or opening paren) or an else plus a (colon : or a whitespace character), then we print the line number as well as the corresponding if, elif, or else.

*as we exit the with block, Python closes the file for us.

Example

If somefile.py is
if condition:
    if condition:
        something
elif condition:
    something
    something
elif condition:
    something
else:
    something

then the above program outputs
1 if
4 elif
7 elif
9 else

A: one-liner:
indexes = [x+1 for x in range(len(content)) if any(x in ['if', 'elif', 'else'] for x in [list(content[x].lower().replace('#line',' ').replace(':',' ').split(' '))[0]])]

indexes:
[1, 4, 7, 9]

A: The snipped below should do it :)
#!/usr/bin/env python
# get_lines.py

def get_lines():
    lines = []
    with open('file.py') as f:
        f = f.readlines()
    for line in range(len(f)):
        if f[line].startswith(('if', 'elif', 'else')):
            lines.append(line + 1)
    return lines

if __name__ == '__main__':
    print(get_lines())


text:
Q: How to optimize the creation of long html code to be used in javascript string I need to define javascript variables containing very long html code.
Here is a short example:
var text = "Select one item:
";
text += "

";

Since the html is going to be much much longer, I would rather work in pure html rather than append text to a javascript string.
I thought of creating a separate html file, but I guess that would require an Ajax call to fetch its content.
What is the best way to deal with this?

A: As N.Zakas said on "maintainable javascript" book, you should «keep html out of javascript» to promote high mantainability of the code through loose coupling of UI layers.
Beside the ajax solution you could also place the markup as a comment in the html file and read it via javascript (as a regular DOM node) or you could use some kind of microtemplating system (e.g. handlebars) and place your markup in a script block (the idea is to put markup where is expected to be found and not into javascript logic)

A: One possible solution is to use templates. There are a few JavaScript libraries that provide templating, underscore.js is one: http://underscorejs.org/#template, or more details on how to use it for templating http://www.headspring.com/blog/developer-deep-dive/an-underscore-templates-primer/
Plus underscore is great for a number of other things.

A: Instead of constructing HTML in Javascript as a string, I would rather suggest you to emit those html elements in the page itself and hide while loading. Then in Javascript, you could select that container and display it.

A: You could break up the text into actual HTML objects.
var thumbnailsUL = document.createElement('ul');
for (index in {your-thumbnails-list}) {
  var thumbnail = document.createElement('li');
  thumbnail.innerHTML = {whatever you need, more objects or html as text};
  thumbnailsUL.appendChild(thumbnail);
}

Ideally though, there is no reason to build this IN JavaScript - can you not emit it from the server?


text:
Q: Find value of div inside aura iteration on icon click! I am trying to find the value of a div which is inside aura iteration on icon click which is also inside the same aura iteration. Here in this code below I am trying to find the value of the aura:id=streeAddress on the click of the icon below.
<aura:iteration items="{! v.filteredMduInfo }" var="mdu">

{!
                mdu.address.Name+', '+mdu.address.sumchans__city__c+'
                '+mdu.address.sumchans__provinceCode__c+' '+mdu.address.sumchans__postalCode__c }

            <lightning:icon iconName="utility:desktop" alternativeText="Television"
                            size="small" onclick="{! c.tvIconClick }"/>

</aura:iteration>

Controller JS:
tvIconClick : function(component, event, helper) {
    console.log(component.find("streetAddress").get());
},

A: You cannot directly do this with the information you get in the event handler as is. Instead, you can use the index or record Id to find the value.
<aura:iteration items="{! v.filteredMduInfo }" var="mdu" indexVar="mduIndex">

{!
                mdu.address.Name+', '+mdu.address.sumchans__city__c+'
                '+mdu.address.sumchans__provinceCode__c+' '+mdu.address.sumchans__postalCode__c }

            <lightning:icon iconName="utility:desktop" alternativeText="Television"
                            size="small" onclick="{! c.tvIconClick }"/>

</aura:iteration>

tvIconClick : function(component, event, helper) {
  var filteredMdu = component.get("v.filteredMduInfo"),
      wrapper = event.target.closest("[data-record-id]"); // or [data-index]
  // option 1
  console.log(filteredMdu.find(mdu => mdu.Id === wrapper.dataset.recordId));
  // option 2
  console.log(filteredMdu[parseInt(wrapper.dataset.index)]);
},

Either way, these would be appropriate methods for finding the correct record to work with.


text:
Q: How to compare two large data sets using hadoop mapreduce? I am new to hadoop and mapreduce. We have a normal java application where we read a file ( 8 GB in size ) from hadoop file system and we apply some rules on that data. After applying rules we get java hashmap (which is huge in size)  and we keep that data in cache or in buffer. At the same time we get the data from hive by applying a query on it and prepare a java hashmap which is again huge in size. Now we compare both the hashmaps data to prepare final report to check the data accuracy.
In the above process since we are using normal java program to do the stuff we are facing below problems.

*

*To process this huge data it takes ages to complete the job. Because input file contains tens of millions of records in it and we need to apply rules on each row to extract the data. It takes days to complete the job. At the same time hive also contains the same amount of data, query is taking too much time to return the data from hive.

*Since we are keeping the data in buffer we are facing memory issues.
Now we are trying to implement the same in hadoop mapreduce.

*

*What is the best way to achieve the above scenario?

*What are the best ways to implement the above scenario in mapreduce?

*How can I increase the application performance by using mapreduce?

A: 8 GB is a tiny data set. I can fit 4 of these 'data sets' into my Laptop RAM! Just dump it in a any relational engine and massage it as fit until the cows come home. This is not 'big data'.
For the record, the way to do processing of two truly large datasets (say +1 TB each) in Hive is a sort-merge-bucket join (aka. SMB join). Read LanguageManual JoinOptimization, watch Join Strategies in Hive.


text:
Q: Using class library with WCF service in ASP.NET 5 In my project I have a class library that contains connections for WCF services.
In old ASP.NET MVC in order to use service methods I only needed to add bindings in my web.config and it would work properly.
The issue that I am having now is that when I call web service in ASP.NET5 I get this exception:
InvalidOperationException: Could not find default endpoint element that references contract 'xxx' in the ServiceModel client configuration section.
This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

Is there a way that I can add my binding in a similar way as I would do in old MVC apps?

A: I'm using the configuration below from an MVC app. When you add a reference to your WCF service using the add service ref dialog. A client section will get added to your System.ServiceModel section in your web.config. It should specify the endpoint which what seems to be missing based on the error you're getting.
Hope this helps
    <client>

  <endpoint address="http://address.to.your.service.com:8080/V3/ConfigService.svc"
            binding="basicHttpBinding"
            bindingConfiguration="ConfigService.V3.ConfigHttpServiceBinding"
            contract="ConfigService.IConfigService"
            name="ConfigService.V3.ConfigHttpService"/>
    </client

A: I was able to run by programattically config bindings. thanks to @wiktor-zychla comment.
var documentService = new DocumentServiceClient(
                                  new BasicHttpBinding(BasicHttpSecurityMode.None),
                                  new EndpointAddress("http://localhost:60205/DocumentService.svc"));


text:
Q: C# Email embedded image does not display in IE I am using C#.Net to send out a HTML email which contains embedded images. These emails work fine in Firefox and chrome but the images do not show up in Internet Explorer (IE). I know that the IE settings are not causing the problem since embedded images sent using Blat work just fine. Am I missing some option such as character set which is causing this problem? My code is as follows
 MailMessage msg = new MailMessage();
 MailAddress from = new MailAddress("Myemail@MyDomain", "My Name");
 msg.To.Add("Myemail@MyDomain");
 msg.From = from;
 msg.Subject = "My subjecct line";

 AlternateView htmlView = AlternateView.CreateAlternateViewFromString("This is a sample JPG embedded image
", null, "text/html");

 LinkedResource EmbeddedObjects1 = new LinkedResource("PathToImage\\image1.jpg");
 EmbeddedObjects1.ContentId = "image1.jpg";
 htmlView.LinkedResources.Add(EmbeddedObjects1);

msg.AlternateViews.Add(htmlView);
SmtpClient smtpclient = new SmtpClient("mailhost.domain.com", PortNumber);
smtpclient.Send(msg);

A: Maybe it helps if you create the LinkedResource with a ContentType combined with Coding Gorilla's idea of a guid as the content-id:
Guid contentId = Guid.NewGuid().ToString();

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
  "This is a sample JPG embedded image
",
  null, "text/html");

ContentType ct = new ContentType(MediaTypeNames.Image.Jpeg);

LinkedResource EmbeddedObjects1 = new LinkedResource("PathToImage\\image1.jpg", ct);
EmbeddedObjects1.ContentId = contentId;
htmlView.LinkedResources.Add(EmbeddedObjects1);

A: Try adding the following.
msg.IsBodyHtml = true;

Additionally, I usually setup my AlternateView like this.
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(html, new ContentType("text/html"));

A: Embedded images work by creating dataUri schemes. IE < 8 doesn't support those.


text:
Q: Determine variance & mean I am not sure how to determine the variance and mean for the following equation system. I'd greatly appreciate your help!
$
  f_\xi(x) = \left\{
  \begin{array}{l l}
    10k_1x & \quad \text{for $0<x<1$}\\
    0 & \quad \text{for other}\\
  \end{array} \right.
$
$
  f_\eta(x) = \left\{
  \begin{array}{l l}
    4k_2x & \quad \text{for $0<x<1$}\\
    4k_2(2-x) & \quad \text{for $1\leq x<2$}\\
  \end{array} \right.
$
I have determined the following:
$k_1 = \frac{1}{5}$
$k_2=\frac{2}{7}$
... and I believe to have found their individual variance and mean:
$E_\xi(x)=\frac{2}{3}$
$V_\xi(x)=\frac{1}{18}$
$E_\eta(x)=\frac{22}{21}$
$V_\eta(x)=\frac{145}{882}$
Now to the gist of my question: how do I calculate the variance and the mean for $10\xi+2\eta$? Thank you!

A: Let $X$ and $Y$ be random variables, and let $a$ and $b$ be constants.
We have $E(aX+bY)=aE(X)+bE(Y)$.
If $X$ and $Y$ are independent then $\text{Var}(aX+bY)=a^2\text{Var}(X)+b^2\text{Var}(Y)$.
(If $X$ and $Y$ are not independent, one can say little about the variance of the linear combination.)


text:
Q: How to remove alphanumeric character in brackets & all its increasing values I need to erase from a MS Word 2010 paragraphs all characters that contain [P1]...[PXXXXX] mean all P1 (+n) increasing values eg. I would like to delete all words (including the [ and ])
[P1], [P2],[P3], [P4]....,[P250]
Is there a VBA or something to use to quickly delete all these?

A: As suggested by @Twisty, it appears the appropriate wildcard was (\[)P[0-9]*(\])


text:
Q: android camera2 preview is less focused than default camera Preview quality is not as good as default camera app. Check difference in hair in this link.
I implemented camera2 with help of android-Camera2Basic.
Both images are 4:3 ratio. I think is something to do with CaptureRequest that you set for camera.
CaptureRequest.Builder mPreviewRequestBuilder;
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                  CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);                                mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_AUTO);
                               mPreviewRequestBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);
But I just can't get it to work like default camera.
Any tips would be greatly appreciated!


text:
Q: Git log -- how to retrieve only the latest commits of every file in the git history, where each commit only changes one file Arr matey!
Let's say I have 2 files foo.txt and bar.txt.
Let's say that any time I commit to git, I am only allowed to change one of these files. Therefore I have a commit history where each commit corresponds to a change in either foo.txt or bar.txt, but not both. I.e. 1 commit = 1 file change.
Now let's say I have 4 commits so far, 2 for each of the files. When I do git log --oneline I get the following result:
hash1 latest changes in foo.txt
hash2 changes in foo.txt
hash3 latest changes in bar.txt
hash4 changes in bar.txt

Note: git log returns the latest commits first, so the hash1 commit is the latest commit for foo.txt, and hash3 for bar.txt.
Now what I want to do is return only the latest commits for each file, as per the title, using git log. Is there an out of the box filter flag to do that? I.e. I want the output in this case to be:
hash1 latest changes in foo.txt
hash3 latest changes in bar.txt

In the real thing I have thousands of files and not just two.

A: I don't think it's possible with one command but certainly possible with two:
git log -1 --grep=foo
git log -1 --grep=bar

Create an alias or a shell script to easily call these two commands.

A: You can use:
git log --grep=bar.txt -1 --oneline && git log --grep=foo.txt -1 --oneline

If you have many files, you can add with more --grep option.
For thousands of files, you can use a shell script instead (such as test.sh in git repo):
#!/bin/sh

for file in $(git ls-files)
do
{
line=$(git log --grep=$file -1 --oneline 2>&1)
echo $line
}
done

Then you can execute the script by ./test.sh.

A: You can do:
git log --oneline -1 <PATH>

Combined with GNU version of xargs, it could be:
git ls-files -z | xargs -0 -L 1 git log --oneline -1

This command would loop through all tracked files in the given repository and execute the above command on each file.


text:
Q: Close a fancybox using pure javascript After opening a jquery fancy box i'am trying to keep the iframe's content light as much as possible by avoiding the reload of jquery package. so i want to close the fancy box (iframe) using pure javascript, i've tried window.close(); but nothing happened.

A: I think you want to close fancybox on button click from the iframe.
for that you have to do a code like this.
Add this button in your iframe page.
<button class="btn btn-danger" type="button" id="btnCancel" onclick="self.parent.CloseFancyBox()">Cancel</button>

write down below function in your parent file.
function CloseFancyBox() {
    $.fancybox.close();
}

If you want to close without click a button then you can directaly right below function in your iframe page.
function closeFancy(){
 self.parent.CloseFancyBox();
}

A: Problem solved. window.close();  do the job
thank you for your answers


text:
Q: unable to run simple jenkins docker node build (home directories outside of /home are not currently supported) I am using a very simple script mentioned below as per the official docs (https://www.jenkins.io/doc/book/pipeline/docker/):
pipeline {
    agent {
        docker { image 'node:14-alpine' }
    }
    stages {
        stage('Test') {
            steps {
                sh 'node --version'
            }
        }
    }
}

Simple as it is, it outputs follows:
22:58:45  [Pipeline] }
22:58:45  [Pipeline] // stage
22:58:45  [Pipeline] withEnv
22:58:45  [Pipeline] {
22:58:45  [Pipeline] isUnix
22:58:45  [Pipeline] sh
22:58:45  + docker inspect -f . node:14-alpine
22:58:46  Sorry, home directories outside of /home are not currently supported.
22:58:46  See https://forum.snapcraft.io/t/11209 for details.
22:58:46  [Pipeline] isUnix
22:58:46  [Pipeline] sh
22:58:46  + docker pull node:14-alpine
22:58:46  Sorry, home directories outside of /home are not currently supported.
22:58:46  See https://forum.snapcraft.io/t/11209 for details.
22:58:46  [Pipeline] }
22:58:46  [Pipeline] // withEnv
22:58:46  [Pipeline] }
22:58:46  [Pipeline] // node
22:58:46  [Pipeline] End of Pipeline
22:58:46  ERROR: script returned exit code 1
22:58:46  Finished: FAILURE

Not sure what I am doing wrong.

A: The hyperlink inside the message leads to a page that says:

Snapd does currently not support running snaps if the home directory of the user is outside of /home.

It says that for the docker command.  I suspect you're trying to run the docker command as the jenkins user.  The default home directory for the jenkins user is /var/lib/jenkins.  The default home directory of the jenkins user is outside /home.
If that's the case, there are several alternatives available:

*

*Create a user on that computer with a home directory in /home and run a Jenkins agent as that user

*Install docker on that computer using apt instead of using snapd (following the Docker directions rather than the Ubuntu directions)

*Create a user on another computer with a home directory in /home and install docker there with snapd, then configure an agent to use that computer

A: It's likely you are inheriting the HOME environment variable from Jenkins in some way.  You can use env config to override that.  If you want the HOME from the worker node executing the docker build you can mount env.HOME into /home/jenkins (or something like that) into the container.
Something like:
pipeline {
    agent {
        docker {
            image 'node:14-alpine'
            args '-v $HOME:/home/jenkins'
        }
    }
    ...
}


text:
Q: Overfull hbox on a tiny equation? My microscopic equation is 2.8 points too wide for some reason, which is quite a lot.  I am reluctant to ignore the warning because if I get more of them I'll start missing important things.
Code is:
Applying Snell's law (Equation \eqref{eq:snell}) twice gives us:
\begin{align}
    \theta_2 &= arcsin \left( \frac{n_{vacuum}}{n_{mylar}} sin(\theta_1) \right) \\
    \theta_1 &= arcsin \left( \frac{n_{mylar}}{n_{vacuum}} sin(\theta_0) \right)
\end{align}
which simplifies to
\begin{equation}
    \theta_2 = \theta_0
\end{equation}
We saw earlier that there was a critical angle [blah blah more text...]

And the warning is:
Overfull \hbox (2.80157pt too wide) (page 6)

on line 226, which is the line containing the tiny \theta_2 = \theta_0.
I'm probably missing something relatively obvious but I just can't see it.  Any idea ?

A: Local modification of the mu-lengths/skips (math-unit skips) could condense the equation enough to avoid the warning yet still produce a consistent enough look to your equation compared to others. Herbert Voß' mathmode document illustrates the different locations where mu-skips are used in an equation:

The default setting for these mu-skips are
\thinmuskip=3mu
\medmuskip=4mu plus 2mu minus 4mu
\thickmuskip=5mu plus 5mu

where 1mu=0.05556em. Perhaps merely adding some shrinkability to \thinmuskip=3mu minus 3mu would help.

A: To avoid warning for the case of small overfull (less than 3pt) write the following
\hfuzz = 3pt


text:
Q: Automatically updating QDateTimeEdit so that it displays the current system date and time Using the Qt library, is there a way to automatically update a QDateTimeEdit using a signal such that the widget shows the current date and time in a similar fashion to a clock?
In the code sample below, dateTimeEditSystem is the QDateTimeEdit object.  However, the setDateTime() function only operates once. I would like the QDateTimeEdit object to dynamically update.  Is there a reliable way of doing this without using a timer (i.e. with signals and slots)?  Or is a timer the only way of doing this?
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // setup the UI
    ui->setupUi(this);
    // set the current date and time
    ui->dateTimeEditSystem->setDateTime( QDateTime::currentDateTime() );
}

I tried using a timer, but unfortunately the QDateTimeEdit did not update.  Here is the complete mainwindow.cpp code.  What am I doing wrong here?
#include <QTimer>

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->dateTimeEditSystem->setDateTime( QDateTime::currentDateTime() );

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT( updateTime() ));
    timer->start(1000);
}

void MainWindow::updateTime()
{
    ui->dateTimeEditSystem->setDateTime( QDateTime::currentDateTime() );
}

MainWindow::~MainWindow()
{
    delete ui;
}

UPDATE:
This is actually very easy to do.  The reason why the code was not updating was due to the lack of a slot declaration in the mainwindow.h file.  Here is the complete contents of the mainwindow.h header.
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;

 private slots:
     void updateTime();

};

#endif // MAINWINDOW_H

A: Automatically updating a QDateTimeEdit or any other clock widget within Qt is easily accomplished with a QTimer.  Refer to the following examples for how to accomplish this:
http://qt-project.org/doc/qt-4.8/widgets-digitalclock.html
OR
http://qt-project.org/doc/qt-4.8/widgets-shapedclock.html
Note that the resolution of a QTimer varies on different operating systems, but for updates that need to occur ~1 second at a time, a QTimer should be fine on virtually all platforms.  Refer to the following for more information on the resolution of QTimer:
http://qt-project.org/doc/qt-4.8/QTimer.html#accuracy-and-timer-resolution


text:
Q: Mysql multiple join syntax error I'm new to mysql and I've been having problems with this query.
Consider this query:
SELECT a.group_message_id, a.scheduled_date, b.message, c.phone_number, d.group_name
    FROM schedule AS a
    JOIN group_message AS b ON a.group_message_id = b.id,
    JOIN phonenumber AS c ON c.id = a.phonenumber_id,
    JOIN group_table AS d ON d.group_id = a.group_id
    WHERE a.status = 'unsent'

And this error message:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'JOIN phonenumber AS c ON c.id = a.phonenumber_id, JOIN
  group_table AS d ' at line 4

I need help with what's actually wrong with the statement. Also I would really appreciate it if you can show me other and "proper" ways of doing such.
Lastly, provided that there's not enough time, is there an effective resource that I can learn from at least the basics of mysql. Please share.

A: remove the comma on join statements,
JOIN group_message AS b ON a.group_message_id = b.id, -- <<== HERE
JOIN phonenumber AS c ON c.id = a.phonenumber_id,     -- <<== HERE
JOIN group_table AS d ON d.group_id = a.group_id

final query,
SELECT  a.group_message_id,
        a.scheduled_date,
        b.message,
        c.phone_number,
        d.group_name
FROM    schedule AS a
        JOIN group_message AS b
            ON a.group_message_id = b.id
        JOIN phonenumber AS c
            ON c.id = a.phonenumber_id
        JOIN group_table AS d
            ON d.group_id = a.group_id
WHERE   a.status = 'unsent'

A: you should not put commas
just check the syntax here
sample syntax
SELECT  column_list FROM  table1 JOIN table2 ON condition JOIN table3 ON condition WHERE condition


text:
Q: Syncing Outlook calendar with SharePoint I am able to sync my share point calendar with the my outlook. I am also able to drag and drop meetings to share point calendar from my personal calendar.
However, i am facing issues when i edit the data in my personal calendar. If the meeting has been moved then the SharePoint does not move the meeting in the share point calendar automatically. I have to manually delete the meeting in SharePoint calendar and again drag and drop form my personal calendar.
Is there a better way? Please advise.
Thanks

A: It's because items(appointments) in Sharepoint Calendar and your personal calendar are different objects. After the item dragNdrop'd to sharepoint calendar a new item is created.
But you can update copied meetings with outlook vb script thato would be fired each time and appointment changes in your personal calendar.
Private Sub curCal_ItemChange(ByVal Item As Object)
Dim newCalFolder As Outlook.Folder
Dim cAppt As AppointmentItem
Dim objAppointment As AppointmentItem
Dim strStart, strSubject As String

 On Error Resume Next
Set newCalFolder = GetFolderPath("display name in folder list\Calendar\Test")

strSubject = "Copied: " & Item.Subject
strStart = Item.Start

For Each objAppointment In newCalFolder.Items
 If objAppointment.Subject = strSubject And objAppointment.Start = strStart Then
         Set cAppt = objAppointment
   End If
 Next

With cAppt
    .Subject = "Copied: " & Item.Subject
    .Start = Item.Start
    .Duration = Item.Duration
    .Location = Item.Location
    .Body = Item.Body
    .Save
End With

End Sub

full vb script example and additional functions are available here


text:
Q: Airmon-ng not working on Crostini When I try running airmon-ng I get no output and this error:
ls: cannot access '/sys/class/ieee80211/': No such file or directory
This is on a linux terminal on my Pixelbook, I installed aircrack-ng using Katoolin.
I had a look at this question but the answer doesn't apply to ChromeOS.
running iwconfig gives me:
lo         no wireless extensions.

eth0       no wireless extensions.


text:
Q: How does Linux schedule vCPUs equitably without any real insight into the workloads executing on them? Considering that to the kernel VMs are mostly opaque pieces of code running on vCPUs,how is Linux able to schedule the workloads equitably?
Does it blindly round robin them? That seems like it could degrade overall system throughput pretty badly. I mean, Linux may end up giving same priority (time) to idle threads in some VMs as threads actually doing useful work in other VMs.
What kind of scheduling algorithm works well for this? Or maybe the VM framework provides inputs that help with scheduling somehow.


text:
Q: i can not see the sysout log on a kubernetes pod I use logback to save the log to a file.
However, if i log on to the pod and see the log file, the log with logback is written well, but i can not find the log with sysout.
kubectl exec -it pod-name bash

Also, if i check the kubernetes pod log, i can not see the log written in logback, but i can check only the log written in sysout.
kubectl logs -f pod-name

In addition, when use logback and sysout  together at function, can not be found  any log using logback.
Do you know how to fix it?

A: kubectl logs -f <pod_name> will show only actions which are affecting POD, not what is actually happening inside the container (any calculations, entered data to the file).
Without function is hard to say what is going to happen, however keeping logs inside the POD is not the best idea. If something happen to the POD, it will crashed or any error occurs, Kubernetes will restart it and all data will be lost.
The proper way is to have your application log to stdout and then use an external tool to capture that and write to a file. Fluentd is frequently used for that purpose, with aggregation i.e. ElasticSearch.
I would suggest you to look at K8s logging architecture and Elasticsearch


text:
Q: Visual Studio on Mac (v7.1) - Cannot deploy/publish to Azure I cannot publish anymore my app with publish profile to Azure after updating my Visual Studio on Mac to version 7.1. I'm getting the following error:

/usr/local/share/dotnet/sdk/1.0.3/Sdks/Microsoft.NET.Sdk.Publish/build/netstandard1.0/PublishTargets/Microsoft.NET.Sdk.Publish.MSDeploy.targets(136,5): error : Package/Publish task Microsoft.NET.Sdk.Publish.Tasks.MsDeploy.VSMSDeploy failed to load Web Deploy assemblies. Microsoft Web Deploy is not correctly installed on this machine. Microsoft Web Deploy v3 or higher is recommended.
      0 Warning(s)
      1 Error(s)

A: As your error suggest to have Web deploy v3 or higher, please download it: https://www.microsoft.com/en-in/download/details.aspx?id=30436

A: I found the solution. I installed .Net Core v2.0 on my mac, changed the target framework in my app to .netcore2.0 and now I'm able to publish my app to Azure again.
I don't have a clue why it is.


text:
Q: Changing width of element using javascript using 2 Identifiers I was reviewing an example side navigation bar on W3Schools and had trouble understanding how the Javascript was implemented. The js is meant to open the side navigation menu via clicking a button. In the code below, why do you need to add the id mySidenav to the menu div? I thought it would make sense to target the div via its class sidenav with getElementsByClassName, but that did nothing. Can someone explain why the id is needed? I would appreciate any help as I learn js.
This is the basic html for the menu:

  ×
  About
  Services
  Clients
  Contact

Here is the CSS for the menu:
.sidenav {
   height: 100%;
   width: 0;
   position: fixed;
   z-index: 1;
   top: 0;
   left: 0;
   background-color: #111;
   overflow-x: hidden;
   transition: 0.5s;
   padding-top: 60px;
 }

And the JS:
function openNav() {
   document.getElementById("mySidenav").style.width = "250px";
}

A: I tried to change it in the Tryit Editor and changed the line to
document.getElementsByClassName("sidenav")[0].style.width = "250px";

and it worked. Did you forget to use the index as you get an array in this case.

A: When you've got something like a menu that there will only be one of on each page you should stick to ID. ID is ensured to only match one occurrence. Matching by class should be done if you've got multiple elements that should behave in the same way.
If you however want to match by class, I assume you tried using getElementsByClassName("sidenav"). In thus case you must specify which match to get, since it will return an array. The correct syntax would then be getElementsByClassName("sidenav")[0]

A: Both selectors will work, but selecting an element by id is faster.
See this question for more info:In jQuery, is selecting by class or id faster than selecting by some other attribute?
Even though this question is about jquery, jquery uses native browser selectors (getElementById or getElementsByClassName) if available


text:
Q: Multiple NSTimers issue I have sub-classed a component (it looks like circle and there is a picture inside it (NSView subclass)).
I want to change the picture every X time (to make it look like an animation).
When in my main view controller I drawing 1 sub-class like this everything works Fine, but when I adding more the picture changes much faster with each.
(I am firing the picture change using an NSTimer)
I am assuming that the issue happens because I have multiple NSTimers on the same queue
However I tried to use
NSTimer *uiTimer = [NSTimer timerWithTimeInterval:(1.0 / 5.0) target:self selector:@selector(changePicture) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:uiTimer forMode:NSRunLoopCommonModes];

It didn't solve the issue (I assume because it is still on the main thread)
So I came up with NSThread Solution
[NSThread detachNewThreadSelector:@selector(updateModel) toTarget:self withObject:nil];

- (void) updateModel
  {

  [NSTimer scheduledTimerWithTimeInterval:secondsBetweenUpdates
                                    target:self
                                    selector:@selector(changePicture)
                                    userInfo:nil
                                    repeats:YES];
    [[NSRunLoop currentRunLoop] run];
    }

It has a bit different behaviour (but still no luck as more sub-classes I have as faster picture changes).
My last shoot was this solution:
// Update the UI 5 times per second on the main queue
// Keep a strong reference to _timer in ARC
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,     dispatch_get_main_queue());
dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, (1.0 / 5.0) * NSEC_PER_SEC, 0.25 * NSEC_PER_SEC);

dispatch_source_set_event_handler(_timer, ^{
[self changePicture];
});

// Start the timer
dispatch_resume(_timer);

I am not usually giving up , but I am trying to resolve it for 3 days already... And I think I need and advice of how to do this so it will work as intended.

A: If you are using GCD I would recommend you use dispatch_after, for example:
float delayTime = 0.2f;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
                             (int64_t)(delayTime * NSEC_PER_SEC)),
               dispatch_get_main_queue(), ^{
    [self changePicture];
});


text:
Q: How can I bind a C/C++ structure to Ruby? I need some advice how can I bind a C/C++ structure to Ruby. I've read some manuals and I found out how to bind class methods to a class, but I still don't understand how to bind structure fields and make them accessible in Ruby.
Here is the code I'm using:
myclass = rb_define_class("Myclass", 0);
...
typedef struct nya
{
    char const* name;
    int age;
} Nya;
Nya* p;
VALUE vnya;
p = (Nya*)(ALLOC(Nya));
p->name = "Masha";
p->age = 24;
vnya = Data_Wrap_Struct(myclass, 0, free, p);
rb_eval_string("def foo( a ) p a end"); // This function should print structure object
rb_funcall(0, rb_intern("foo"), 1, vnya); //  Here I call the function and pass the object into it

The Ruby function seems to assume that a is a pointer. It prints the numeric value of the pointer instead of it's real content (i.e., ["Masha", 24]). Obviously the Ruby function can't recognize this object —I didn't set the object's property names and types.
How can I do this?  Unfortunately I can't figure it out.

A: You have already wrapped your pointer in a Ruby object. Now all you have to do is define how it can be accessed from the Ruby world:
/* Feel free to convert this function to a macro */
static Nya * get_nya_from(VALUE value) {
    Nya * pointer = 0;
    Data_Get_Struct(value, Nya, pointer);
    return pointer;
}

VALUE nya_get_name(VALUE self) {
    return rb_str_new_cstr(get_nya_from(self)->name);
}

VALUE nya_set_name(VALUE self, VALUE name) {
    /* StringValueCStr returns a null-terminated string. I'm not sure if
       it will be freed when the name gets swept by the GC, so maybe you
       should create a copy of the string and store that instead. */
    get_nya_from(self)->name = StringValueCStr(name);
    return name;
}

VALUE nya_get_age(VALUE self) {
    return INT2FIX(get_nya_from(self)->age);
}

VALUE nya_set_age(VALUE self, VALUE age) {
    get_nya_from(self)->age = FIX2INT(age);
    return age;
}

void init_Myclass() {
    /* Associate these functions with Ruby methods. */
    rb_define_method(myclass, "name",  nya_get_name, 0);
    rb_define_method(myclass, "name=", nya_set_name, 1);
    rb_define_method(myclass, "age",   nya_get_age,  0);
    rb_define_method(myclass, "age=",  nya_set_age,  1);
}

Now that you can access the data your structure holds, you can simply define the high level methods in Ruby:
class Myclass
  def to_a
    [name, age]
  end

  alias to_ary to_a

  def to_s
    to_a.join ', '
  end

  def inspect
    to_a.inspect
  end
end

For reference: README.EXT

A: This is not a direct answer to your question about structures, but it is a general solution to the problem of porting C++ classes to Ruby.
You could use SWIG to wrap C/C++ classes, structs and functions. In the case of a structure, it's burning a house to fry an egg.  However, if you need a tool to rapidly convert C++ classes to Ruby (and 20 other languages), SWIG might be useful to you.
In your case involving a structure, you just need to create a .i file which includes (in the simplest case) the line #include <your C++ library.h>.
P.S. Once more, it's not a direct answer to your question involving this one struct, but maybe you could make use of a more general solution, in which case this may help you.

A: Another option is to use RubyInline - it has limited support for converting C and Ruby types (such as int, char * and float) and it also has support for accessing C structurs - see accessor method in the API.


text:
Q: .class:first-child CSS not working Hi there I've got 4 divs each with a class called .section and the first div, I want to use less padding.
If you check out this codepen, I've got a really basic example where it actually works.
However if you look at my current project, I can't actually add the :last-child psuedo element. Please take a look here This code pen has the identical code in the CSS section. However it's not taking effect.
HTML

...

...

...

...

CSS
.section:first-child{
  padding-top:15px !important; //Not applying
}

Please put my mind to rest! Thanks!

A: There's a syntax error in your project's codepen.
Wrong
.section :first-child{
  padding-top:15px !important;
}

Correct (:first-child without space before)
.section:first-child{
  padding-top:15px !important;
}

You will notice the
 tag will move according to the padding-top being applied.
-
Alternative solution
You can add a new class to that specific section you need to apply the padding-top rule.
HTML

CSS
.section.new-class { padding-top: 15px }

A: it works in first code pen cause it have a well written CSS
in second codepen - unworkable cause... awful html, awful css (imho - too many random classes and id's). U must clean your code before test for 1st element, see that css
.section{color: red;}/*to mark red all section classes*/

.section:first-child{
  padding-top:0px !important;
color: blue;/*to mark first child, what not exist*/
}

#sermon-details/*don't use other, unnecessary rules*/

to see what you have in your html!
p.s. RTFM


text:
Q: Angular show and hide with ngClass for multiple divs I have multiple divs with the same class which I want to hide and show on click, also give class. when I click on EDIT, it affects all divs but I want to affect it on certain div which you click on it.
here is my stackblitz
.ts
  isShown: boolean = true ;
  editMode: boolean = false ;

  onEdit() {
    this.editMode = true;
    this.isShown = false;
  }
  done() {
    this.editMode = false;
    this.isShown = true;
  }

.html

        ....
          <form action="">

        ......
          </form>

A: You could create a map and assign an index for the divs:

      <button class="ml-m@s g-b--w0 g g--alignCenter g--nowrap cur-p edit ml-auto d-flex" (click)="onEdit(1)">

EDIT

      </button>

  editModeMap = {};

  onEdit(index: number) {
    this.editModeMap[index] = true;
  }

  done(index: number) {
    this.editModeMap[index] = false;
  }

Stackblitz


text:
Q: How to move selected Structures, Templates and articles from one liferay instance to another instance? I have 2 separate Liferay Instances, say Instance A which I was running from past 1 year, it has lot of articles, templates and structures, there are 3 different portals running on this same instance.
Now I have a new instance B, I want to move some of the selected articles, structures and templates from Instace A to Instance B. I am not able to find any method to do selected migration.
I can export the articles, structures and templates as a LAR file and import it in Instance B. But the problem is it by default imports all the articles, structures and templates. Is there any way to do selected Import???

A: The answer is no. Atleast there is no OOTB way to import selected articles. One option can be, to export the webcontent as lar from the the page itself. For example consider your Page PA on Server SA has a webcontent in webcontent display portlet called WA. Just export the webcontent as lar from the webcontent display portlet itself and then got to the page PB on server SB to import the lar in a webcontent display portlet called WB.


text:
Q: PHP - nested Arrays From this global variable:
echo '<pre>';
print_r($wp_registered_sidebars);
echo '</pre>';

I'm getting output like this:
Array
(
    [sidebar-1] => Array
        (
            [name] => Main Sidebar
            [id] => sidebar-1
            [description] => text
            [before_widget] =>
            [after_widget] =>
            [before_title] =>
            [after_title] =>
        )

    [sidebar-2] => Array
        (
            [name] => Footer Sidebar 1
            [id] => sidebar-2
            [description] => text
            [before_widget] =>
            [after_widget] =>
            [before_title] =>
            [after_title] =>
        )

    [sidebar-3] => Array
        (
            [name] => Footer Sidebar 2
            [id] => sidebar-3
            [description] => text
            [before_widget] =>
            [after_widget] =>
            [before_title] =>
            [after_title] =>
        )
)

I never know how many sidebars there are and how they are named.
Is there a way of:

*

*listing all sidebrs IDs only - sidebar-1, sidebar-2, sidebar-3,

*listing all sidebar names only - Main Sidebar, Footer Sidebar 1, Footer Sidebar 2,

Thank you!

A: $resultSlideBars = array();
foreach($wp_registered_sidebars as $slidebars)
{
   $resultSlideBars[$slidebars['id']] = $slidebars['name'];    // will store array as array(id => name

}

// ids
echo implode(' ', array_keys($resultSlideBars));
echo implode(' ', $resultSlideBars);   // echo names

or
foreach($wp_registered_sidebars as $slidebars)
{
   echo $slidebars['id'];      // echo id
   echo $slidebars['name'];    // echo name
}

A: foreach(array_keys($wp_registered_sidebars) as $sidebarID) {
    echo $sidebarID;
}

foreach($wp_registered_sidebars as $sidebar) {
    echo $sidebar['name'];
}

A: $sidebarIds = array_keys($wp_registered_sidebars);

$sideBarNames = array();
foreach($wp_registered_sidebars as $row)
{
  $sideBarNames[] = $row['name'];
}

A:
foreach ($wp_registered_sidebars as $key => $sidebars) {
    echo "sidebar id" . $key;
    echo "sidebar name " . $sidebar['name'];
}


text:
Q: How to remove border/shadow from lollipop buttons The buttons looks fine for api < 21. However, the +21 versions creates this border or shadow that is shown on the image below. How do I get rid of it without changeing the hole theme, but setting a style variable?

It might be more clear on this colored image. There is some kind of border around the buttons.

My buttonssstyle is defined like this:
<style name="buttonTransparent" parent="Base.TextAppearance.AppCompat.Button">
        <item name="android:background">#00000000</item>
        <item name="android:textColor">@drawable/button_text_blue</item>
        <item name="android:textSize">18dp</item>
        <item name="android:textAllCaps">false</item>
        <item name="android:minHeight">45dp</item>
    </style>

<style name="buttonLargeWhite" parent="buttonTransparent">
        <item name="android:background">#FFF</item>
        <item name="android:layout_marginTop">10dp</item>
    </style>

A: I fixed this globally by setting android:stateListAnimator="@null" in Resources\values\styles.xml:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
    </style>
    <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:buttonStyle">@style/NoShadowButton</item>
    </style>
    <style name="NoShadowButton" parent="android:style/Widget.Button">
        <item name="android:stateListAnimator">@null</item>
    </style>
</resources>

And voila the shadows are gone for good :)

A: "shadow" effect is added on Lollipop Appcompat theme
add the following line in res/values-v21/styles.xml to remove default shadow
Theme level:
<item name="android:buttonStyle">@style/Widget.AppCompat.Button.Borderless</item>

xml layout:
android:stateListAnimator="@null"

Java:
setStateListAnimator(null);

Kotlin:
stateListAnimator = null

A: Buttons in android have statelistAnimator property so by declaring it null we can remove the border of button
android:stateListAnimator="@null"

A: Best and easiest way i am using is setting style attribute to Button
<Button
...
style="?android:attr/borderlessButtonStyle"
....
/>

may be someone need in future.

A: in xml we can use
android:stateListAnimator="@null"

A: Lollipop has a nasty little feature called stateListAnimator which handles the elevations on Buttons, which leads to shadows.
Remove the stateListAnimator to get rid of the shadows.
You have got multiple options to do that:
Java:
button.setStateListAnimator(null);

Kotlin:
button.stateListAnimator = null

or in your layout xml's:
<Button
...
android:stateListAnimator="@null"
....
/>

A: I would suggest you just remove the shadow entirely, by setting the elevation to nothing.  Since you already have a XML style (add this to use this universally), or you could add this attribute to your XML view definition
android:elevation="0dp"

A: Issue

*

*From Android v21, Border has been added by default for all the button.
<!-- Bordered ink button -->
<style name="Widget.Material.Button">
     <item name="background">@drawable/btn_default_material</item>
     <item name="textAppearance">?attr/textAppearanceButton</item>
     <item name="minHeight">48dip</item>
     <item name="minWidth">88dip</item>
     <item name="stateListAnimator">@anim/button_state_list_anim_material</item>
     <item name="focusable">true</item>
     <item name="clickable">true</item>
     <item name="gravity">center_vertical|center_horizontal</item>
</style>

*

*The property "stateListAnimator" is the one which is causing the problem.

Solution

*

*In our application theme, set button style to remove the default border (Android support library itself provides style for it).
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
     <!-- From Android-v21 - Border has been added by default, hence we are removing it. -->
     <item name="android:buttonStyle">@style/Widget.AppCompat.Button.Borderless</item>
</style>

A: There is already a style you can leverage not to have the borders.
apply
style="@style/Base.Widget.AppCompat.Button.Borderless"

to your item to remove the borders

A: If you want to do this programmatically in Kotlin, you can do
button.stateListAnimator = null


text:
Q: How is accuracy calculated in Battlefield 3? Since there is no official source for this kind of information and I haven't found any data on the internet, I'm asking this here. The details:

*

*In which cases shots are affecting the specific gun's/general accuracy? Will my accuracy go down, if I just stand at one place and put 1000 rounds in the ground?

*How is calculated rocket launcher's accuracy? Is the indirect damage a miss or a hit?

*What math is used? Shots hit / shots fired? Or something more complicated?

*Off-topic: Why is my general accuracy around 13, if 26 guns out of 30 in my top weapons have 18+ accuracy (sniper rifles 30+, pistols 20+, rocket launchers 55+).

Any info will do - personal observations, tests, videos, maybe game-file tear-downs or unpopular developer blog entries, or closed forum posts, any.

A: It is simply hits/shots fired.
A hit is considered as anything that does damage to an opposing enemy/vehicle. Verifying my L96 accuracy, I have 1463 hits, with 4,119 shots fired. The site says my accuracy is 35.52% and doing the simple math, that's what that ratio is.
Edit: Answering your bullet points

*

*Yes, your accuracy would go down if no damage is done to an enemy player.

*Rocket accuracy is the same as all other weapons. Damage done = hit. It is how you can have over 100% accuracy with weapons since 1 shot could hit multiple players.

*I answered originally

*Your general accuracy is the total sum of your hits/shots fired for all your weapons. So while your top weapons have high accuracy ratings and make your general accuracy higher, your bottom weapons drop your general accuracy.

A: It would have to be shots fired vs. shots hit. On the Battlefeed site, you can see that they show for each weapon.


text:
Q: Can I use Zebble for only UI and use Xamarin for everything else I would like to use Zebble only for producing UI and all other things I would like to use Xamarin apis/custom http apis/local db or whatever it may be. Basically a UI project with zebble and other things will be in PCLs.
Will it be compatible? Could you please advice?

A: Yes you can. There is nothing in Zebble that prevents you from using the native APIs directly.
For custom http calls, I recommend using the HttpClient class which is by default available in all 3 platforms of a newly created Zebble project.
For Device APIs, you can of course use the standard API classes of each platform, but to save time and achieve 100% code reuse I strongly recommend using the  http://zebble.net/docs/device-api. For example if you want o use the lamp (aka flash, led or torch) you can very easily implement that on all platforms with very little code code:
// Determines if a lamp feature is available on the device.
if (await Device.Torch.IsAvailable()) { ... }

// This will switch the lamp on.
await Device.Torch.TurnOn();

// This will switch the lamp off.
await Device.Torch.TurnOff();


text:
Q: KeyPressed / KeyReleased events in Monodroid? I'm trying to send something continuously while holding a button down. It's Monodroid, so I could use the event OnTouchEvent, but that's not what I am looking for. What I want is just an event like the KeyPressed(), so it will run continuously the code.
There is also no KeyReleased() event in Monodroid which means that I need to use something else instead, maybe MotionEvent? I already tried something with MotionEvent, but that didn't work well.
Is there someone who could help me out?

A: You can make use of LongClick event :
var button = new Button(this);
button.LongClick += (object sender, Android.Views.View.LongClickEventArgs e) => {
};

KeyPress Event :
button.KeyPress += (object sender, Android.Views.View.KeyEventArgs e) => {
};

Refer :

*

*https://developer.xamarin.com/api/type/Android.Views.KeyEvent/

*http://developer.android.com/reference/android/view/KeyEvent.html

*http://code.tutsplus.com/tutorials/android-sdk-intercepting-physical-key-events--mobile-10379

Edit
Make use of OnTouch Event identify the motionEvent.
Eg :
public class MyTouchListener
    : Java.Lang.Object
    , View.IOnTouchListener
{
    public bool OnTouch(View v, MotionEvent e)
    {
        if (e.Action == MotionEventActions.Down)
        {
            // do stuff
            return true;
        }
        if (e.Action == MotionEventActions.Up)
        {
            // do other stuff
            return true;
        }

        return false;
    }
}

OR
    Button button = FindViewById<Button> (Resource.Id.myButton);
    var count = 0;
    var handled = false;
    button.Touch += (s, e) => {
        if(e.Event.Action == Android.Views.MotionEventActions.Down)
        {
            // Do stuff.
            System.Console.WriteLine("Counting ... " + count.ToString());
            count++;
            handled = true;
        }
        else if (e.Event.Action == Android.Views.MotionEventActions.Up)
        {
            // Do stuff.
            System.Console.WriteLine("Counting ... " + count.ToString());
            count++;
            handled = true;
        }
        e.Handled = handled;
    };

Refer :

*

*https://stackoverflow.com/a/10511800/3891036

*https://stackoverflow.com/a/25223860/3891036


text:
Q: unable to execute hadoop fs -put command from Java I am trying to execute hadoop fs -put <source> <destination> from Java code. When I execute this command directly from the terminal, it works fine but when I try to execute this command from within the Java code using
String[] str = {"/usr/bin/hadoop","fs -put", source, dest};
Runtime.getRuntime().exec(str);

I get error as Error: Could not find or load main class fs. I tried to execute some non-hadoop commands like ls,mkdir commands from Java and they worked fine but the hadoop commands are not getting executed even though they work fine from the terminal.
What could be the possible reason for this and how can I solve it?
JAVA API TRY: I tried to use java api to perform the copy operation but I get error. The Java code is :
        String source = "/home/tmpe/file1.csv";
        String dest = "/user/tmpe/file1.csv";
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://node1:8020");
        FileSystem fs = FileSystem.get(conf);
        Path targetPath = new Path(dest);
        Path sourcePath = new Path(source);
        fs.copyFromLocalFile(false,true,sourcePath,targetPath);

The error which I get is:
Exception in thread "main" java.io.IOException: Mkdirs failed to create /user/tmpe
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:378)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:364)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:564)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:545)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:452)
    at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:229)
    at org.apache.hadoop.fs.FileSystem.copyFromLocalFile(FileSystem.java:1230)

I have already created /user/tmpe folder  and it has full read-write permissions but still this error comes. I am unable to get the issue resolved

A: I guess you probably do not have a HADOOP_HOME environment variable set.
But since you're in Java, why on earth would you want to do a haddop fs -put in an external process when the Java API is even more friendly than the shell ?

A: Came across old post but if you haven't tried already, execute it with hadoop jar app_name.jar instead of java -jar. This way if classpath of your jar does not have all hadoop jars it will fetch the jars predefined in $HADOOP_CLASSPATH.


text:
Q: how to send details to mail in javascript code I want to send all input data which filled in the contact form.
contact form in javascript

function sendMail() {
    $.ajax({
      type: 'POST',
      url: 'https://mandrillapp.com/api/1.0/messages/send.json',
      data: {
        'key': 'YOUR API KEY HERE',
        'message': {
          'from_email': 'YOUR@EMAIL.HERE',
          'to': [
              {
                'email': 'RECIPIENT@EMAIL.HERE',
                'name': 'RECIPIENT NAME (OPTIONAL)',
                'type': 'to'
              }
            ],
          'autotext': 'true',
          'subject': 'YOUR SUBJECT HERE!',
          'html': 'YOUR EMAIL CONTENT HERE! YOU CAN USE HTML!'
        }
      }
     }).done(function(response) {
       console.log(response); // if you're into that sorta thing
     });
}

A: Replace your key/value pairs with values from textboxes like below
{
  ...
  'subject': $('#txtSubject').val(),
  ...
}

Here, txtSubject is id of subject's textbox. Like this you can replace all the fields you want to send to API.

A: After reading your query, I persume a solution
$.ajax({
    url: 'https://mandrillapp.com/api/1.0/messages/send.json',
    type: 'POST',
    data: {
    'key': <your_key>,
    'form-data': form.serialize()
    }
 })

Your will get all the keyword of input name with value inside the form-data dictionary.


text:
Q: Nagios custom plugin issue - https authetication I am writing a plugin to check authentication to a https site and then search for a text in the response html,body to confirm successful login.  I have created the following plugin
#!/bin/bash
add_uri='--no-check-certificate https://'
end_uri='/'
result=$(wget -O- $add_uri$1$end_uri --post-data=$2)
flag=`echo $result|awk '{print match($0,"QC Domain")}'`;
echo $flag
echo "Nagios refreshes properly1"

if [[ $flag -gt 0 ]] ; then
echo 'ALL SEEMS FINE!!'
exit 0
   else
echo 'Some Problem'
exit 2
fi;

When I execute this plugin directly from command line
./check_nhttps <url here>  '<very long post data with credential information>'

The plugin works as expected(For both + & - test cases) and there seems to be no issues.
But when the plugin runs from Nagios,
check_command                   check_nhttps! <url here>  '<very long post data with    credential information>'

It always shows critical error(Prints else condition text "Some Problem" too).
P.S : Tried sending the post data with double quotes also.doesnt work!!
Please help!!!


text:
Q: How can I search street or postal address on simplekml without using coordinates I have a list of street addresses, weekly my database grows. For example 10 Hage Geingob Walvis Bay.  I  need to plot their positions on Google Mymaps (or alternatively Google Earth) using the kml file. I'm doing it via Python. I'll eventually have control over the labels, colors, titles, descriptions offering me some value.
However the code seems to only respond to coordinate (lat/long) input, using the "coords" command. When using "address" command it simply targets the 0,0 lat/long position in the ocean.
I would appreciate any help on how to use the a street address as the input directly into simplekml...as if I typed the street address directly into google maps or google earth.
As a workaround I have used geocode functions such as geopy and Nominatim ...to establish GPS coordinates and then feed that to simplekml ...but accuracy is terrible. Some addresses are accurate, some are miles off.
I'm not interested in setting up keys and API's in GoogleV3.
Code used as workaround
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="redacted")
location = geolocator.geocode(address)
print(location.address)
print((location.latitude, location.longitude))
import simplekml
kml = simplekml.Kml() # Create an instance of Kml
single_point = kml.newpoint(name=address, coords=[(location.longitude,location.latitude)])
kml.save("10 Hage Geingob.kml")```

When in my view it should be possible to do the following according to the simplkml documentation...

```street_address = '10 Hage Geingob Walvis Bay'
import simplekml
kml = simplekml.Kml()
kml.newpoint(name=street_address, address=street_address)
kml.save("10 Hage Geingob.kml")```

...but it doesn't work. Any help is much appreciated thank you. I am indeed a complete noob.

Thank you


text:
Q: Scrollable flutter popup menu I'm trying to use flutter popup menu button, but I can't seem to make it smaller with a scroll.
Is it doable? Or am I using the wrong widget to do it?
Image below as reference, would like to show only the first 4 / 5 items, and scroll to show the rest!
Thanks in advance!

A: You can create your own PopUp Widget instead.
A Card wrapped into a AnimatedContainer with specific dimensions and a ListView inside.
Place this widget on your screen using Stack and Positioned widgets so it will be above other elements on the top | right.
class CustomPopup extends StatefulWidget {
  CustomPopup({
    @required this.show,
    @required this.items,
    @required this.builderFunction,
  });

  final bool show;
  final List<dynamic> items;
  final Function(BuildContext context, dynamic item) builderFunction;

  @override
  _CustomPopupState createState() => _CustomPopupState();
}

class _CustomPopupState extends State<CustomPopup> {
  @override
  Widget build(BuildContext context) {
    return Offstage(
      offstage: !widget.show,
      child: AnimatedContainer(
        duration: Duration(milliseconds: 300),
        height: widget.show ? MediaQuery.of(context).size.height / 3 : 0,
        width: MediaQuery.of(context).size.width / 3,
        child: Card(
          elevation: 3,
          child: MediaQuery.removePadding(
            context: context,
            removeTop: true,
            child: ListView.builder(
              scrollDirection: Axis.vertical,
              itemCount: widget.items.length,
              itemBuilder: (context, index) {
                Widget item = widget.builderFunction(
                  context,
                  widget.items[index],
                );
                return item;
              },
            ),
          ),
        ),
      ),
    );
  }
}

return Stack(
      children: <Widget>[
        Container(
          color: Colors.blueAccent,
        ),
        Positioned(
          right: 0,
          top: 60,
          child: CustomPopup(
                  show: shouldShow,
                  items: [1, 2, 3, 4, 5, 6, 7, 8],
                  builderFunction: (context, item) {
                    return ListTile(
                       title: Text(item.toString()),
                       onTap: () {}
                    );
                  },
              ),
          ),
      ],
    );

A: You can create this in two ways: the first one is PopupMenuButton widget and the second one is PopupRoute.

class HomePage extends StatefulWidget {

@override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State {
Listitems = [1,2,3,4,5,6,7,8,9,10,11,12,13];
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(
  child: PopupMenuButton(
      child: Icon(Icons.add_shopping_cart),
      offset: Offset(-1.0, -220.0),
      elevation: 0,
      color: Colors.transparent,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
      itemBuilder: (context) {
        return <PopupMenuEntry<Widget>>[
          PopupMenuItem<Widget>(
            child: Container(
              decoration: ShapeDecoration(
                  color: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10))),
              child: Scrollbar(
                child: ListView.builder(
                  padding: EdgeInsets.only(top: 20),

                  itemCount: items.length,
                  itemBuilder: (context, index) {
                    final trans = items[index];
                    return ListTile(

                      title: Text(
                        trans.toString(),
                        style: TextStyle(
                          fontSize: 16,

                        ),
                      ),

                      onTap: () {
                        //what would you like to do?
                      },
                    );
                  },
                ),
              ),
              height: 250,
              width: 500,
            ),
          )
        ];
      }),
)

You can also adjust the number of items you want to show by reducing or increasing height of the container. I also added a scrollbar just in case.

A: You can use maxHeight for constrains property.
...
PopupMenuButton(
              constraints:
                  BoxConstraints(minWidth: context.maxWidth, maxHeight: 300),
...


text:
Q: how to get "xyz" text from span, I tried css but protractor did not identify it

xyz

how to get "xyz" text from span, I tried css but protractor did not identify it

A: First of all your selector should look like:
div > span
You don't have [...] > td > span.
And then .getText() on that element.


text:
Q: How does Google redirect its search results? I input the query java into the search text box on https://www.google.com. One result is https://en.wikipedia.org/wiki/Java_(programming_language). I get the following text by right clicking the link and selecting Copy Link Address.
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=10&cad=rja&uact=8&ved=0ahUKEwiijvLpqvnSAhVFqY8KHU5UDyYQFghDMAk&url=%68%74%74%70%73%3a%2f%2f%65%6e%2e%77%69%6b%69%70%65%64%69%61%2e%6f%72%67%2f%77%69%6b%69%2f%4a%61%76%61%5f%28%70%72%6f%67%72%61%6d%6d%69%6e%67%5f%6c%61%6e%67%75%61%67%65%29&usg=AFQjCNEaMDPWkK-lszS-jjSYrWuKEdrmKA&bvm=bv.150729734,d.dGc
And I paste the above link to Chrome address bar. And I use Developer Tools to monitor the HTTP network traffic.

The first HTTP request is for the original link. And its status code is 200. How does Chrome make the following request for https://en.wikipedia.org/wiki/Java_(programming_language)?I know that a HTTP response with status code 302 can make brsowers following the link in Location header. But how is the redirect done in this case with status code 200?

A: The redirect is done because in the response of the first HTTP request (https://www.google.com/url?sa=t&rct=j...):

*

*If javascript is enabled, then the window location is navigated to https://en.wikipedia.org/... using script.

*If javascript is disabled, or client does not support javascript, then <meta http-equiv="refresh"> is used to redirect to https://en.wikipedia.org/...
Here is the response body of the first HTTP request:
<script>window.googleJavaScriptRedirect=1</script>
<META name="referrer" content="origin">
<script>var n={navigateTo:function(b,a,d){if(b!=a&&b.google){if(b.google.r){b.google.r=0;b.location.href=d;a.location.replace("about:blank");}}else{a.location.replace(d);}}};n.navigateTo(window.parent,window,"https://en.wikipedia.org/wiki/Java_(programming_language)");
</script>
<noscript>
<META http-equiv="refresh" content="0;URL='https://en.wikipedia.org/wiki/Java_(programming_language)'">
</noscript>


text:
Q: Vertical alignment is not working -Windows Phone 8.1 Below is my XAML part of windows Phone 8.1.
<Grid Background="#FAE8C9">
        <ListView x:Name="articleListing">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid Margin="5,5,5,5">
                        <StackPanel  Background="#FFFEDC" RequestedTheme="Light" Tapped="RedirectToArticle" Tag="{Binding URL}" >
                            <StackPanel Orientation="Horizontal" >

                                <StackPanel Margin="10 0 0 0" Width="{Binding Width}">
                                    <StackPanel  VerticalAlignment="Top">
                                    <TextBlock TextWrapping="Wrap"  Text="{Binding HeadLine}" FontSize="22"/>
                                    </StackPanel>

                                    <StackPanel Orientation="Horizontal" VerticalAlignment="Bottom">
                                        <Image Source="/Images/cal.png" Width="20" />
                                        <TextBlock Text="{Binding UpdatedAtDate}" FontSize="18" Foreground="#CEBFA5" />
                                        <Image Source="/Images/clock.png" Width="20"/>
                                        <TextBlock Text="{Binding UpdatedAtTime}" FontSize="18" Foreground="#CEBFA5" />
                                    </StackPanel>
                                </StackPanel>

                                <StackPanel Background="Transparent" Width="{Binding Width}" >
                                    <Image Source="{Binding ImageURL}" />
                                </StackPanel>

                            </StackPanel>
                        </StackPanel>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>

In this, I have tried to make the below part as vertical alignment to the bottom. But it doesn't work.
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom">
                                        <Image Source="/Images/cal.png" Width="20" />
                                        <TextBlock Text="{Binding UpdatedAtDate}" FontSize="18" Foreground="#CEBFA5" />
                                        <Image Source="/Images/clock.png" Width="20"/>
                                        <TextBlock Text="{Binding UpdatedAtTime}" FontSize="18" Foreground="#CEBFA5" />
                                    </StackPanel>
                                </StackPanel>

Please help me to solve this issue. Thank you

A: Most XAML containers like list views and stack panels fill from top to bottom and their height is equal to the sum of the heights of their contents.
If you've got something you want to appear at the bottom of the container you have the following choices:

*

*Use a canvas of the desired dimensions and explicitly place each element on the canvas. This loses you a big benefit of XAML - namely that it reacts to changes in the available space and repositions elements for you.

*Insert some padding into your layout to force elements to be in the place you want them to be. Again you might lose the ability to change view size etc.

You might find using a Grid rather than a StackPanel gives you a bit more control over placement - but again usually the row heights and column widths are governed by the sizes of the elements contained therein.

A: Use This code.
<Grid Background="#FAE8C9">
            <ListView x:Name="articleListing">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid Margin="5,5,5,5">
                            <StackPanel  Background="#FFFEDC" RequestedTheme="Light" Tapped="RedirectToArticle" Tag="{Binding URL}" >
                                <StackPanel Orientation="Horizontal" >
                                    <Grid Margin="10 0 0 0" Width="{Binding Width}">
                                        <StackPanel  VerticalAlignment="Top">
                                            <TextBlock TextWrapping="Wrap"  Text="{Binding HeadLine}" FontSize="22"/>
                                        </StackPanel>
                                        <StackPanel Orientation="Horizontal" VerticalAlignment="Bottom">
                                            <Image Source="/Images/cal.png" Width="20" />
                                            <TextBlock Text="{Binding UpdatedAtDate}" FontSize="18" Foreground="#CEBFA5" />
                                            <Image Source="/Images/clock.png" Width="20"/>
                                            <TextBlock Text="{Binding UpdatedAtTime}" FontSize="18" Foreground="#CEBFA5" />
                                        </StackPanel>
                                    </Grid>

                                    <StackPanel Background="Transparent" Width="{Binding Width}" >
                                        <Image Source="{Binding ImageURL}" />
                                    </StackPanel>

                                </StackPanel>
                            </StackPanel>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>

This might be work for you.


text:
Q: Make a Wine installed Video Player Default Player I have installed DivX Player (version 6.6) using Wine in my ubuntu 11.10. Is there any way to make it a default player to play certain video formats ?
Thanks in advance.

A: It is possible, though it is potentially a bit more complicated.
If DivX shows up as an option in the "Open With" list for your files, then you can easily set it as default.

If it does not, then I would suggest not bothering to go through the trouble.

A: A long post, but the first and last bits, may be enough for you.
You can put a launching command into a script (eg divx-player) and assign that script to launch a particular type via Nautilus - Properties - Open with...
But what is the command? The following explanation is long, but the idea is very simple, once you've "got" it ..(it took me quite a while to "get" it :)
Because you can have multiple wine environments installed (eg, to suit specific settings for a particular program), the system must be told which wine you want to run..  For this, wine relies on an environment variable named $WINEPREFIX.
If you are using wine from its default location, $WINEPREFIX will have a value of  $HOME/.wine...  Let's assume that your DivX player is installed to this WINEPREFIX  (to this environment)...
To be robust, your wine command should explicitly specify the WINEPREFIX, so wine knows which wine environment to run in.
If you don't explicitly specify the WINEPREFIX, wine will use the default value you specified when you installed wine.
Here is the command to specify the WINEPREFIX you want to use.
env WINEPREFIX="$HOME/.wine"  wine

To cleanly launch an app via a Windows command-line, it is a good idea to use the Windows start.exe command, so the command nees to include this (note the use of thw Windows C:\style\path-name here)..
 env WINEPREFIX="$HOME/.wine"  wine  'C:\windows\command\start.exe'

Files that reside within the $WINEPREFIX/dosdevices/c:/ directory can be addressed in this Windows style, but files elsewhere on your sysem, need a different approach.
Windows C:\ is mapped to the unix directory `$WINEPREFIX/dosdevices/c:/, and likewise other files on your system can be accessed from within wine via another virtual Windows disk-drive Z:\... but wine provides a simpler method to access your data files (eg, a movie, somewhere/anywhere on your file-system).
These files are, of course, known in the Unix/Linux world by their Unix-style path-names.  wine facilitates the translation from unix-style path-names to windows-style path-names via a wine-specific command-line option /Unix
Your DivX player command now needs to be followed by the /path/to/the/DivX-player -options /path/to/the/movie.  But because the DivX player is a Windows app, it expects all paths to be in Windows format (ie: C:\Program Files\etc\etc).
As the DivX player.exe is within the WINEPREFX environment you can launch it either via its C:\Windows\path or via /Unix /Unix/path.  Using the /Unix option is typically easier and less error-prone, because you don't have to manually flip all the slashes to back-slashes.  All four of the following command will run the player, but the first one (/Unix /unix-path/player.exe) is typically the best choice.
# Using Unix-style: Run the .exe directly
/Unix "$WINEPREFIX/dosdevices/c:/Program Files/DivX/DivX.exe"

# Using Unix-style: Run the .exe via its Windows menu shortcut.lnk
/Unix "$WINEPREFIX/dosdevices/c:/users/Public/Start Menu/Programs/DivX/DivX.lnk"

# Using Windows-style: Run the .exe directly
'C:\Program Files\DivX\DivX.exe'

# Using Windows-style: Run the .exe via its Windows menu shortcut.lnk
'C:\users\Public\Start Menu\Programs\DivX\DivX.lnk'

Then you can just tack on the final arg, the movie-path, (in unix-style)... so the full command becomes...
env WINEPREFIX="$HOME/.wine" \
    wine 'C:\windows\command\start.exe' \
    /Unix "$WINEPREFIX/dosdevices/c:/Program Files/DivX/DivX.exe" \
    /Unix "/media/dat_ext4/video/Galaxy Quest.avi"

Nautilus will automatically provide the movie path, so your command for your divx-player bash script needs to cater of an argument, as follows
#!/bin/bash
env WINEPREFIX="$HOME/.wine" \
    wine 'C:\windows\command\start.exe' \
    /Unix "$WINEPREFIX/dosdevices/c:/Program Files/DivX/DivX.exe" \
    /Unix "$1"


text:
Q: Can I use Visual Studio 2015 for creating Windows Phone 8 applications? I have Visual Studio 2015 Community edition installed with Windows Desktop development tools (languag - C++). Can I use it for creating Windows Phone 8 application with C++ language (especially with C++11/14 standard)? Which SDK\tools I have to install for this task or may be all required instruments are in Visual Studio 2015 Community package alredy?
Thank you for help.
P.S.: The "Visual Studio 2015 Platform Targeting and Compatibility" article, in the section "Visual Studio 2015 Support for Windows Universal, Windows Store, and Windows Phone App Development", says that Windows Phone 8 apps are supported by the Visual Studio 2015 but with footnotes "Supports migration of Windows Phone 8 projects to Windows Phone Silverlight 8.1.". So, I can't understand, does Visual Studio 2015 support the whole development cycle for Windows Phone 8 app or only migration to the Windows Phone 8.1?
UPDATE: I mean the Windows Runtime applications for Windows Phone 8 platform.

A: sure, you need to download windows phone 8/8.1 sdk from microsoft website
https://www.microsoft.com/en-in/download/details.aspx?id=35471 or from somewhere which provide standalone installer for this.
after this, just open up visual studio go to c++ the expand windows > windows phone


text:
Q: Android - How to get the mobile nunber when not stored in the SIM card I want to get the mobile number related with a SIM card. But I know that some celular operators doesn't store the number into the SIM card.
So use the code below will not return anything,
TelephonyManager tm = (TelephonyManager)this.getApplicationContext()
                                            .getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber =  tm.getLine1Number();

Anyone knows any other way to get the mobile number?
Maybe some API that retrieves the number using the IMSI of the SIM Card, or maybe the mobile number is stored somewhere on the memory of the device.
One desperate way could be make some kind of request to the operator or carrier to ask for the mobile number for that IMSI, I don't know :)
any help will be appreciated :)
thanks

A: In that event I would just have the user input their phone number and cache it.
EDIT AFTER COMMENT
I am not 100% sure, but is there a way to grab the phone number stored in the "About Phone" settings menu? Though that probably grabs the phone number from the SIM as well, and if the OS itself can't figure it out, you might have to just settle for not grabbing the phone number on all devices. My phone number is not stored on my SIM, and my About Phone menu can not see my phone number.

A: I hope that no such API exists, or otherwise I foresee being called all day long by some call centers trying to sell useless stuff.