text:
Q: Journey Builder contact update within Journey In Journey Builder I'm testing whether updating a contact's Data Extension record that is already in a Journey will update the contact in the Journey.
Here is my test:
Part 1
Create a Data Extension (Customer) with a few records of Status = 1
Part 2
Create Journey in Journey Builder with Email Audience entry (no filter) with Entry Audience as "Customer" Data Extension

*

*Step 1: Wait 15 minutes

*Step 2: Decision Split (If
Customer.Status = 999) go to Branch A else go to Branch B

*Branch A: Exit after 1 day

*Branch B: Exit after 1 day

Part 3
Running the test:

*

*Activate Journey

*Wait until subscribers of Customer Data Extension are in the "Wait 15 minutes step"

*While records are still in the "Wait 15 minutes step", update some records of the Customer Data Extension and change the "Status" value from 1 to 999 using Contact Builder (Edit records of Data Extensions functionality)

*Wait until the journey completes

Expected Result:

*

*Updated records (Customer.Status = 999) go to Branch A of Journey

Actual Result

*

*All records go to Branch B of Journey

Is this the expected functionality of Journey Builder?
It seems to me that the record's value should be evaluated at the Decision Split Activity step, but instead I'm seeing only the original values of the Data Extension being evaluated at that step.
This has major implications on how Journeys are built.

A: I've discovered the problem.
Updating a Data Extension record with Contact Builder's "edit record in Data Extension" functionality doesn't seem to let Journey Builder know that there has been an update to the record.
When I performed the same steps as above, but instead of manually updating the record, I use a query activity,  the contacts continued down the correct Journey Branch A.


text:
Q: Typo3 inherit data when if is true I generate an lib.content with the current content but i want to add it only if the following if statement will be true, otherwise not/empty:
lib.content = COA
lib.content{
    10 < styles.content.get
    10.stdWrap.cObject.if{
        value.data = DB:pages:{page:uid}:nav_hide
        value.data.insertData = 1
        equals = 1
    }
}

is this possible or where's the error in the syntax?
Version of Typo3 is 10.4

A: You need to use "insertData" twice, because it replaces {page:uid} with the UID (e.g. 5), but it keeps the rest DB:pages:5:nav_hide.
The rest DB:pages:5:nav_hide needs to be "data inserted" again, so the trick is to use wrap3.
Solution:
lib.content = COA
lib.content {
    10 < styles.content.get
    10.stdWrap.cObject.if {
        // Replaces page:uid
        value.dataWrap = DB:pages:{page:uid}:nav_hide
        // Wraps curly brackets around DB:pages:5:nav_hide
        value.wrap3 = {|}
        // Replaces DB:pages:5:nav_hide with the nav_hide value
        value.insertData = 1
        equals = 1
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: getter method of asynctask that run from other file I have two files XMLParser that parse XML from URL and the Activity. Seems the getter methods don't work. I can output the values of the arrayList in XMLParser files. but not in Activity file.
public class XMLParser extends AsyncTask<Void, Void, ArrayList<Object>> {

    ArrayList<String> groupItem = new ArrayList<String>();
    ArrayList<Object> childItem = new ArrayList<Object>();
    ArrayList<String> child = new ArrayList<String>();

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            System.out.println("authType is " + authType);
            System.out.println("cert issuers");
            for (int i = 0; i < certs.length; i++) {
                System.out.println("\t"
                        + certs[i].getIssuerX500Principal().getName());
                System.out.println("\t" + certs[i].getIssuerDN().getName());
            }
        }
    } };

    @Override
    protected ArrayList<Object> doInBackground(Void... params) {

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        try {
            URL url = new URL();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getElementsByTagName("Device");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element deviceElement = (Element) nodeList.item(i);
                groupItem.add(deviceElement.getAttribute("serial"));
                child = new ArrayList<String>();
                child.add(deviceElement.getAttribute("model"));
                child.add(deviceElement.getAttribute("asset"));
                child.add(deviceElement.getAttribute("location"));
                child.add(deviceElement.getAttribute("lastConnected"));
                childItem.add(child);
            }
;
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }
        return childItem;
    }

    protected void onPostExecute() {
        // here you will get the result
    }

    public ArrayList<String> getGroupItem() {

        return groupItem;
    }

    public ArrayList<Object> getChildItem() {
        return childItem;
    }

Here is Activity file:
public class DevicesActivity extends ExpandableListActivity implements
OnChildClickListener  {
    ArrayList<String> groupItem = new ArrayList<String>();
    ArrayList<Object> childItem = new ArrayList<Object>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /** Create a new layout to display the view */
         //setContentView(R.layout.activity_devices);

        //ExpandableListView expandbleLis = getExpandableListView();
        //expandbleLis.setDividerHeight(2);
        //expandbleLis.setGroupIndicator(null);
        //expandbleLis.setClickable(true);
        startXMLParser();

        System.out.println("size in Device "+groupItem.size());
        System.out.println("size in Device "+childItem.size());

    }
    private void startXMLParser() {
        XMLParser XMLTask = new XMLParser();
        XMLTask.execute(null,null,null);
        groupItem=XMLTask.getGroupItem();
        childItem=XMLTask.getChildItem();
}

Get ArrayList:
public void getArrayList(ArrayList<DataInterface> lst) {
        finalList=lst;

    }

A: Since AyncTask is asynchronous there is no guarantee that the results will be there when you call your methods to retrieve the data, in fact, it probably won't be. You need to make sure that the task has completed before trying to access those variables.
One solution would be to pass that data on to the Activity in onPostExecute(). If this class is an inner class of the Activity then you can have member variables and assign them in onPostExecute() or another AsyncTask method.
Also, you should have the parameter type in your onPostExecute() declaration or it won't receive the results. And you should add the @Override annotation
@Override
protected void onPostExecute(ArrayList<Object> result) {
    // here you will get the result
}

In AsyncTask create a constructor to receive Context
Activity mAct;
public calss MyTask extends AsyncTask<...>  // you know what to add here
{
    public MyTask(Activity act)
    {
         mAct = act;
    }

then use mContext in onPostExecute() to call your Activity function
When you create the task
MyTask task = new MyTask(this);  // pass context to constructor
taske.execute(// add params);

public void onPostExecute(ArrayList<Object> result){
    mAct.yourMethod(result);

A: Following Example Give You Idea
@Override
    protected void onPostExecute(ArrayList<Object> result) {
        // here you will get the result               ||    This Must Be Same
    }                                                 \/
    protected                          ArrayList<Object> doInBackground(String... params)

Return type of doInBackground and Parameter of PostExecute must be Same


text:
Q: How to create separate lists for each set of matching characters are found in a multi-line string What is the best way to create separate lists for each set of matching characters found in a multi-line string ?
str="""Name: abc1
Age: defg1
Place: xyz1

Name: abc2
Age: defg2
Place: xyz2

Name: abc3
Age: defg3
Place: xyz3
"""

Using the below code I am able to create one big list but interested in creating three separate lists.
my_list = []
for each_module in str.split("\n"):
        if "Name: " in each_module:
                my_list.append(each_module.strip("Name: "))
        elif "Age: " in each_module:
                my_list.append(each_module.strip("Age: "))
        elif "Place: " in each_module:
                my_list.append(each_module.strip("Place: "))
print my_list

Output:
['abc1', 'defg1', 'xyz1', 'abc2', 'defg2', 'xyz2', 'abc3', 'defg3', 'xyz3']

Preferred Output:
['abc1', 'defg1', 'xyz1']
['abc2', 'defg2', 'xyz2']
['abc3', 'defg3', 'xyz3']

A: You are well started, just create a new list that you reset when you fill out the place, and add it to your main list as below:
my_str="""Name: abc1
Age: defg1
Place: xyz1

Name: abc2
Age: defg2
Place: xyz2

Name: abc3
Age: defg3
Place: xyz3
"""
my_list = []
new_list = []
for each_module in my_str.split("\n"):
    if "Name: " in each_module:
        new_list.append(each_module.strip("Name: "))
    elif "Age: " in each_module:
        new_list.append(each_module.strip("Age: "))
    elif "Place: " in each_module:
        new_list.append(each_module.strip("Place: "))
        my_list.append(new_list)
        new_list = []
print(my_list)

Output:
[['bc1', 'defg1', 'xyz1'], ['bc2', 'defg2', 'xyz2'], ['bc3', 'defg3', 'xyz3']]


text:
Q: Machine state in a CoreOS cluster Is there an easy way to figure out who is the current leader in an etcd cluster (except for searching through the logs)?

A: curl -L http://127.0.0.1:4001/v2/stats/self

yields
{
"leaderInfo": {
    "leader": "10.132.90.172",
    "startTime": "2015-04-16T11:57:49.568452941Z",
    "uptime": "1h18m25.433506066s"
},
"name": "10.132.90.172",
"recvAppendRequestCnt": 0,
"sendAppendRequestCnt": 0,
"startTime": "2015-04-16T11:57:49.56843843Z",
"state": ""
}


text:
Q: Jquery - Server can't read data sent from Ajax I am currently sent data using ajax to api server from my web application.
but it's like the server can't read my data because the typeData of my data isn't same with typeData sent by postman.
i'am testing sending data from postman and works perfectly.
here's the capture sending data via postman.

and here's my ajax code
data = {
    nama_lengkap: "user name",
    nama_panggilan: "user",
    ttl: "new york, 10 april 1999",
    jenis_kelamin: "male",
    agama: "-",
    email: "username@mailinator.com",
    no_telp: "1234567",
    nama_ayah: "Johnson",
    nama_ibu: "Kadita",
    pendidikan_terakhir: "S1",
    organisasi: "-",
    kejuaraan: "-",
};

obj = JSON.stringify(data);
t = Cookies.get("user");

$.ajaxSetup({
    headers: {
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        accept: "application/json",
    },
});
$.ajax({
    type: "POST",
    timeout: 0,
    headers: {
        Accept: "application/json",
    },
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + t);
    },
    url: "http://localhost:8000/api/anggota/store",
    contentType: "application/json",
    data: obj,
    dataType: "json",
    processData: false,
    contentType: false,
    success: function (response) {
        console.log(response);
    },
    error: function (xhr, status, err) {
        console.error(JSON.parse(xhr.responseText));
    },
});

but I got error responseText like this
{
    "success": false,
    "code": 500,
    "message": "Gagal",
    "errors": [
        {
            "nama_lengkap": [
                "The nama lengkap field is required."
            ],
            "nama_panggilan": [
                "The nama panggilan field is required."
            ],
            "ttl": [
                "The ttl field is required."
            ],
            "jenis_kelamin": [
                "The jenis kelamin field is required."
            ],
            "agama": [
                "The agama field is required."
            ],
            "email": [
                "The email field is required."
            ],
            "no_telp": [
                "The no telp field is required."
            ],
            "nama_ayah": [
                "The nama ayah field is required."
            ],
            "nama_ibu": [
                "The nama ibu field is required."
            ],
            "pendidikan_terakhir": [
                "The pendidikan terakhir field is required."
            ]
        }
    ]
}

um, what's wrong with my code? any clues are helps.
Thankyou

A: You should not use Json.Stringify() !
Just use data Object directly.
Try this:
data = {
    nama_lengkap: "user name",
    nama_panggilan: "user",
    ttl: "new york, 10 april 1999",
    jenis_kelamin: "male",
    agama: "-",
    email: "username@mailinator.com",
    no_telp: "1234567",
    nama_ayah: "Johnson",
    nama_ibu: "Kadita",
    pendidikan_terakhir: "S1",
    organisasi: "-",
    kejuaraan: "-",
};

t = Cookies.get("user");

$.ajaxSetup({
    headers: {
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        accept: "application/json",
    },
});
$.ajax({
    type: "POST",
    timeout: 0,
    headers: {
        Accept: "application/json",
    },
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + t);
    },
    url: "http://localhost:8000/api/anggota/store",
    contentType: "application/json",
    data,
    dataType: "json",
    processData: false,
    contentType: false,
    success: function (response) {
        console.log(response);
    },
    error: function (xhr, status, err) {
        console.error(JSON.parse(xhr.responseText));
    },
});

A: see stringify:
its result is JSON string.
Extract from the official docs:

The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}.

So I suggest you use the object format when sending to the server.

A: there is no wrong about the typeData in my code. the main problem is because i  declare  ContentType: false in the end of my code.
it should like this
$.ajax({
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + t);
            },
            url: "http://localhost:8000/api/anggota/store",
            method: "POST",
            timeout: 0,
            data: form_anggota,
            contentType: "application/json",
            dataType: "json",
            success: function (response) {
                console.log(response);
            },
            error: function(xhr){
                console.log(JSON.parse(xhr.responseText))
            }
        });


text:
Q: JIRA Integration with external systems I'm working on a POC to automate downstream processes in external systems based on JIRA processes and have hit a wall with the API.  It appears to have great integration for pulling data about tickets out of JIRA and for the ability to externally generate tickets into JIRA.
However I don't see how to trigger external calls as a part of my workflows.  For example if a ticket should be prevented from being routed to the next stage of a workflow without accessing a database to ensure availability of inventory first how could I do that in JIRA?
Based on attributes in the JIRA ticket upon final completion of the workflow we'd like to send a JMS or REST message or possibly update an external database.  Is this possible?
Thanks all in advance for the help!

A: If you want to do a "before" check, use a Validator on the Workflow Transition.
I strongly suggest deploying the (free) Script Runner add-on. There you can implement a ton of things. For example, you'll get a new validator option "Script Validator", where you can specify a Groovy script that decides if it lets through the transition or aborts it.


text:
Q: Application crash on showing Decoded image on imageView In my application when i try to show image in image view without using compression techniques, my application crashes. Following is the complete code and logcat
10-30 21:19:53.779: E/Trace(1817): error opening trace file: No such file or directory (2)
10-30 21:20:12.789: E/AndroidRuntime(1817): FATAL EXCEPTION: main
10-30 21:20:12.789: E/AndroidRuntime(1817): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { act=inline-data dat=content (has extras) }} to activity {com.example.checkactivities/com.example.checkactivities.Activity2}: java.nio.BufferUnderflowException
10-30 21:20:12.789: E/AndroidRuntime(1817):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3622)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3672)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at android.app.ActivityThread.access$1100(ActivityThread.java:151)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at android.os.Looper.loop(Looper.java:155)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at android.app.ActivityThread.main(ActivityThread.java:5454)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at java.lang.reflect.Method.invokeNative(Native Method)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at java.lang.reflect.Method.invoke(Method.java:511)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at dalvik.system.NativeStart.main(Native Method)
10-30 21:20:12.789: E/AndroidRuntime(1817): Caused by: java.nio.BufferUnderflowException
10-30 21:20:12.789: E/AndroidRuntime(1817):     at java.nio.Buffer.checkGetBounds(Buffer.java:177)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at java.nio.HeapByteBuffer.get(HeapByteBuffer.java:63)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at com.example.checkactivities.Activity2.onActivityResult(Activity2.java:476)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at android.app.Activity.dispatchActivityResult(Activity.java:5275)
10-30 21:20:12.789: E/AndroidRuntime(1817):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3618)
10-30 21:20:12.789: E/AndroidRuntime(1817):     ... 11 more

        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        int bytes =  thumbnail.getWidth()*thumbnail.getHeight()*4;
        ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
            thumbnail.copyPixelsToBuffer(buffer);
        byte[] bytes1 = new byte[bytes];
        buffer.get(bytes1, 0, bytes1.length);
        byte[] b = buffer.array();
        String ImageString = Base64.encodeToString(b, Base64.DEFAULT);
        byte[] bytarray = Base64.decode(ImageString, Base64.DEFAULT);
         Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,bytarray.length);
         imageView11.setImageBitmap(bmimage);

A: You can directly use Bitmap like
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView11.setImageBitmap(thumbnail);

Or
you can first decode the Image then use it like
Uri mImageCaptureUri = intent.getData();
                try {
                    thumbnail = decodeBitmap(mImageCaptureUri, this);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                imageView11.setImageBitmap(thumbnail);

Image Decode
public Bitmap decodeBitmap(Uri selectedImage, Context context)
            throws FileNotFoundException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(context.getContentResolver()
                .openInputStream(selectedImage), null, o);

        final int REQUIRED_SIZE = 100;

        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        System.out.println("width_tmp" + width_tmp + "height_tmp" + height_tmp);
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
                break;
            }
            width_tmp = 50;
            height_tmp = 50;
            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(context.getContentResolver()
                .openInputStream(selectedImage), null, o2);
    }


text:
Q: Joining tables using variable columns - dplyr, r, join Problem:  I have 2 tables I'd like to join.  However, the column upon which I wish to join the second to the first will vary dependent upon a successful parsing of the 2nd data frame to identify which column and row to join.
Request:  I have found a solution to the problem (see below) but it does not seem to me to very computationally efficient.  Not a problem for the reproducible example below but potentially less ideal when stepped out to a larger scale problem i.e. ~200,000+ rows / observations.
Wondering if anyone might be able to help identify something better - ideally utilising functionality from dplyr.
Reproducible Example:
# Equipment alias table
alias1    <- c('a1a1', 'a2a2', 'a3a3', 'a4a4', 'a5a5', 'a6a6')
alias2   <- c('bc001', 'bc002', 'bc003', 'bc004', 'bc005', 'bc006')
alias3   <- c('e1o1', 'e202', 'e303', 'e404', 'e505', 'e606')

df_alias <- data.frame(alias1, alias2, alias3)

# Attribute table
equip    <- c('a1a1','bc006', 'e404')
att1     <- c('a', 'b', 'c')
att2     <- c('1', '2', '3')

df_att   <- data.frame(equip, att1, att2)

Desired Outcome:
I'm looking to achieve the following....
# DESRIED OUTPUT - combining equipment alias table into attribute table based on string match between attibute_equip and any one of columns in equipment alias
equip    <- c('a1a1','bc006', 'e404')
att1     <- c('a', 'b', 'c')
att2     <- c('1', '2', '3')
alias1   <- c('a1a1','a6a6', 'a4a4')
alias2   <- c('bc001','bc006', 'bc004')
alias3   <- c('e1o1','e606', 'e404')

df_att   <- data.frame(equip, att1, att2, alias1, alias2, alias3)

Current Solution:
library(dplyr)
left_join(df_att, df_alias, by = character()) %>%
filter(equip == alias1 | equip == alias2 | equip == alias3)

Effective but not exactly elegant as there's a great deal of duplication for ultimately a filter to then be applied to undo that duplication.

A: An option is to filter with if_any and then bind the subset rows with the df_att
library(dplyr)
df_att2 <- df_alias %>%
    filter(if_any(everything(), ~ .x %in% df_att$equip)) %>%
    arrange(na.omit(unlist(across(everything(), ~ match(df_att$equip, .x))))) %>%
    bind_cols(df_att, .)

-checking with OP's expected (changed the object name 'df_att' to 'out' to avoid any confusion)
> all.equal(df_att2, out)
[1] TRUE

A: I don't know how it compares efficiency-wise, but one idea is to pivot a copy of each alias so that you can left_join against a single column instead of multiple ones.
library(tidyr)
library(dplyr)

df_alias %>%
  mutate(across(everything(), ~., .names = "_{.col}")) %>%
  pivot_longer(starts_with('_'), names_to = NULL, values_to = 'equip') %>%
  left_join(df_att, .)

#> Joining, by = "equip"
#>   equip att1 att2 alias1 alias2 alias3
#> 1  a1a1    a    1   a1a1  bc001   e1o1
#> 2 bc006    b    2   a6a6  bc006   e606
#> 3  e404    c    3   a4a4  bc004   e404


text:
Q: Is order of a Ruby hash literal guaranteed? Ruby, since v1.9, supports a deterministic order when looping through a hash; entries added first will be returned first.
Does this apply to literals, i.e. will { a: 1, b: 2 } always yield a before b?
I did a quick experiment with Ruby 2.1 (MRI) and it was in fact consistent, but to what extent is this guaranteed by the language to work on all Ruby implementations?

A: There are couple of locations where this could be specified, i.e. a couple of things that are considered "The Ruby Language Specification":

*

*the ISO Ruby Language Specification

*the RubySpec project

*the YARV testsuite

*The Ruby Programming Language book by matz and David Flanagan
The ISO spec doesn't say anything about Hash ordering: it was written in such a way that all existing Ruby implementations are automatically compliant with it, without having to change, i.e. it was written to be descriptive of current Ruby implementations, not prescriptive. At the time the spec was written, those implementations included MRI, YARV, Rubinius, JRuby, IronRuby, MagLev, MacRuby, XRuby, Ruby.NET, Cardinal, tinyrb, RubyGoLightly, SmallRuby, BlueRuby, and others. Of particular interest are MRI (which only implements 1.8) and YARV (which only implements 1.9 (at the time)), which means that the spec can only specify behavior which is common to 1.8 and 1.9, which Hash ordering is not.
The RubySpec project was abandoned by its developers out of frustration that the ruby-core developers and YARV developers never recognized it. It does, however, (implicitly) specify that Hash literals are ordered left-to-right:

new_hash(1 => 2, 4 => 8, 2 => 4).keys.should == [1, 4, 2]

That's the spec for Hash#keys, however, the other specs test that Hash#values has the same order as Hash#keys, Hash#each_value and Hash#each_key has the same order as those, and Hash#each_pair and Hash#each have the same order as well.
I couldn't find anything in the YARV testsuite that specifies that ordering is preserved. In fact, I couldn't find anything at all about ordering in that testsuite, quite the opposite: the tests go to great length to avoid depending on ordering!
The Flanagan/matz book kinda-sorta implicitly specifies Hash literal ordering in section 9.5.3.6 Hash iterators. First, it uses much the same formulation as the docs:

In Ruby 1.9, however, hash elements are iterated in their insertion order, […]

But then it goes on:

[…], and that is the order shown in the following examples:

And in those examples, it actually uses a literal:

h = { :a=>1, :b=>2, :c=>3 }

# The each() iterator iterates [key,value] pairs
h.each {|pair| print pair }    # Prints "[:a, 1][:b, 2][:c, 3]"

# It also works with two block arguments
h.each do |key, value|
  print "#{key}:#{value} "     # Prints "a:1 b:2 c:3"
end

# Iterate over keys or values or both
h.each_key {|k| print k }      # Prints "abc"
h.each_value {|v| print v }    # Prints "123"
h.each_pair {|k,v| print k,v } # Prints "a1b2c3". Like each

In his comment, @mu is too short mentioned that

h = { a: 1, b: 2 } is the same as h = { }; h[:a] = 1; h[:b] = 2

and in another comment that

nothing else would make any sense

Unfortunately, that is not true:
module HashASETWithLogging
  def []=(key, value)
    puts "[]= was called with [#{key.inspect}] = #{value.inspect}"
    super
  end
end

class Hash
  prepend HashASETWithLogging
end

h = { a: 1, b: 2 }
# prints nothing

h = { }; h[:a] = 1; h[:b] = 2
# []= was called with [:a] = 1
# []= was called with [:b] = 2

So, depending on how you interpret that line from the book and depending on how "specification-ish" you judge that book, yes, ordering of literals is guaranteed.

A: From the documentation:

Hashes enumerate their values in the order that the corresponding keys
  were inserted.


text:
Q: Proper way to catch imagemagick convert errors in php exec Hi guys whats the proper way to catch imagemagick convert errors in php exec()?
exec('convert img.jpg -resize 100x100 img.jpg',$output);
var_dump($output);

$output always return a blank array.

A: For exec, evaluate the return status; which is the third parameter.
exec('convert img.jpg -resize 100x100 img.jpg',$output,$exit_status);
if( $exit_status !== 0 ) {
  // Error handle here
}

However, anything written to stderr may not be present in the $output array. A better, more flexible, approach would be to use proc_open & pipes.
$pipe_handle = array();
$pipe_spec = array(
  array('pipe','r'), // stdin
  array('pipe','w'), // stdout
  array('pipe','w')  // stderr
);

$pid = proc_open('convert img.jpg -resize 100x100 img.jpg',$pipe_spec,$pipe_handle);
// Close stdin
fclose($pipe_handle[0]);
// Read what's in stdout buffer & close
$pipe_stdout = stream_get_contents($pipe_handle[1]);
fclose($pipe_handle[1);
// Read what's in stderr buffer & close
$pipe_stderr = stream_get_contents($pipe_handle[2]);
fclose($pipe_handle[2]);

// Get exist status
$exit_status = proc_close($pid);

if( $exit_status === -1 ) {
  // Handle error and evaluate stderr
} else {
  // Handle success and evaluate stdout
}

A bit more work, but can cleanly seperate errors from normal messages (if any)


text:
Q: Two lists in python. Check when the elements are of the same sign I have two lists in python
list1=[1,3,5,-3,-3]
list2=[2,-3,3,-3,5]

I want to produce a list that is true when the elements are of the same sign
result=[True,False,True,True,False]

which is the fastest and more pythonic way to do this?
EDIT:
Solution
I solve it by transforming both list to numpy arrays
np.array(list1)*np.array(list1)>0

A: The product of two numbers of the same sign should be positive, so you can do:
result = [a * b > 0 for a, b in zip(list1, list2)]


text:
Q: Spring boot jar on azure websites performance issues I have an application built as a spring boot fat jar.
I host it in azure websites according to "official" documentation with a web.config similar too:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
        </handlers>
        <httpPlatform processPath="%JAVA_HOME%\bin\java.exe" arguments="-Djava.net.preferIPv4Stack=true -Dserver.port=%HTTP_PLATFORM_PORT% -jar "%HOME%\site\wwwroot\my-web-project.jar"">
        </httpPlatform>
    </system.webServer>
</configuration>

The application is monolithic in structure, not too large but does some mapping and has some layers to initialize so startup time is about 12 seconds locally.
It runs an H2 in memory database just for testing purposes.
Actual deployment and getting it running on azure websites were never really a problem, but there's some real performance issues, at least with the settings I have.
Some settings of interest:

*

*Standard S1 instance (at the time of writing costing about ~$40USD/month).

*Webapp configured with:

*

*Tomcat8 (shouldn't really matter as the fat jar runs embedded tomcat)

*JDK 8

*Always on enabled

To be able to compare the numbers to something I ran the application on an Azure VM I have with similar (but not the same) specs and price range and ran the application on that one.
Here are some of the results:
Startup time of the application:

*

*Azure websites: ~2 minutes

*VM: 30 sek

Cold call:
Deployed/started the application and left it to make a call the day after.

*

*Azure websites: 31119 ms

*VM: 219 ms

Consequent call:
A call directly after the cold call, but to another endpoint.

*

*Azure websites: 2685 ms

*VM: 223 ms

My question here is:
Do any one know if it is viable to run spring boot fat jars hosted on azure websites?
As there is official documentation from Microsoft one would think that it is, and of course technically it is, but is it viable in production?
I'm not really after any debating about AWS vs Azure vs Google App Engine .....,
or to write wars/jars or how to host it.
I have reasons to want it this way. If it's not possible I have other options but would like to explore the idea first and see if any one else has better experiences?
Edit: Just to add to the information. The database was empty for all calls. So that shouldn't add any overhead to speak off. No data was actually fetched only empty lists.

A: Although it is an old question and my answer is rather not valuable since I have no knowledge on Azure, but I would like to share results of my research. I have couple of Spring Boot microservices and one relatively big service (170 MB fat jar that on my local machine starts in about 70 seconds). Azure starts small microservices in tens (if not in hundreds) of seconds... and I mean like really small microservices (an example of config server from Spring Cloud etc... there is nothing fancy going on there). If it comes to the big one - Azure starts it and after 2 minutes... starts it again... and again... and again. As a result it never gets started.
and it was all on B3 app service plan. So quite big plan.
Wrapping up, in my (strongly subjective) opinion - Azure is not a viable option for Java apps.

A: It's viable for your question about running spring boot fat jars hosted on Azure websites, please refer to my answer for the SO thread Deploying Springboot to Azure App Service and focus on the offical document for the part of spring boot.
Hope it helps. Any concern, please feel free to let me know.


text:
Q: How can I setup video streaming via http on windows? I'm looking for a  module to one of these web servers (apache, nginx, lighthttpd) to create video streaming in webm format. My operating system is Windows.

A: Why don't you try to use VLC? It's capable of webm http streaming. Try this in your command line:
C:\Program Files\VideoLAN\VLC>vlc.exe --sout "#transcode{vcodec=VP80,vb=300,scale=1,acodec=vorb,ab=128,channels=2,samplerate=44100}:http{mux=webm,dst=:8080/mountpoint.webm}" yourmovie.foo

You don't need to use a http server in the middle, except if you want to do some rewrite rules to keep vlc sending webm video to another port (like 8080) and then do some rewrite to make it look like it's coming from port 80.
I hope it helps.


text:
Q: Clear a region so that views behind show through Okay, so I have a base view that looks like this:

And I have a view on top of it, with some subviews, that looks like this:

Let's say those colourful squiggles represent my subviews in that overlay view.
But there are parts of my base layer I want to show through. If I had a rect like this one:

I would want it to look like this:

I'm honestly at a bit of a loose end when it comes to implementing this. My first thought was to use CGContextSetBlendMode(.Clear), but drawing is done behind subviews, not over them. I also can't just straight up render the contents of the subviews without adding them to my view, because when they're not clipped out, they still need to be interactive.
To throw a spanner in these works; that base layer is a WKWebView, and it still needs to be interactive, too.
I'm seriously stumped here. Any help?

A: I'm having a little difficulty understand what the difficulty is... You seem to be describing a mask. Maybe I'm wrong; I could be missing some further requirement. But with a mask I was easily able to attain this result:

That's a background with some words in it; in front of that, a clear view to host everything else; and the squiggles are subviews of the clear view. The clear view has a mask layer that cuts out the rectangular hole in the squiggles. Touch is unaffected by the clear view, since touches "fall through" a clear view; it's there just to host the mask (and the squiggles).


text:
Q: Swap function for user-defined class never instantiated? The following is a reduced example of something I'm stumbling across with a larger class I'm creating and attempting to make Swappable by providing my own non-member friend swap function.
#include <iostream>
#include <utility>

template<typename T>
class Wrapper {
  friend void swap(Wrapper& a, Wrapper& b);

public:
  Wrapper(T t) : value_(t) {}
  const T& operator*() const { return value_; }

private:
  T value_;
};

template<typename T>
void swap(Wrapper<T>& a, Wrapper<T>& b) {
  using std::swap;
  swap(a.value_, b.value_);
}

int main() {
  Wrapper<int> w1{5}, w2{10};
  std::cout << *w1 << " " << *w2 << std::endl;
  swap(w1, w2);
  std::cout << *w1 << " " << *w2 << std::endl;
}

Attempting to compile this small test program results in the following linker error from clang (Apple LLVM version 7.0.2, clang-700.1.81 on OS X El Capitan 10.11.3):
[~/Development/c++_test][16:30:57]$ clang++ --std=c++11 -o SwapTest SwapTest.cc
Undefined symbols for architecture x86_64:
  "swap(Wrapper<int>&, Wrapper<int>&)", referenced from:
      _main in SwapTest-a978ea.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Why is the template swap function for my Wrapper class that I've defined not instantiated appropriately despite my use of it in main()?

A: friend void swap(Wrapper& a, Wrapper& b);

declares a non-template function swap that happens to take Wrapper<T>& arguments.  This doesn't match with your template function swap<T>.
One simple fix is to declare the friend as the template function.
template <typename U>
friend void swap(Wrapper<U>&a, Wrapper<U>& b);

The drawback there is you've friended a little more than you wanted: every swap instantiation is a friend of every Wrapper<T>, not just the correct Wrapper<T> class.
A more correct way involves declaring the template function before the class:
template <class T> class Wrapper;
template <class T>
void swap(Wrapper<T>&, Wrapper<T>&);

template <class T>
class Wrapper
{
    friend void swap<>(Wrapper&, Wrapper&);
    // ...

A: Simply change your friend declaration to be a template:
template<typename T>
class Wrapper {
  template<typename U>
  friend void swap(Wrapper<U>& a, Wrapper<U>& b);
  ...

gcc outputs a warning about this when trying to compile your code


text:
Q: Reading from two excel and creating difference file Reading from two excel files and writing the differences into another excel file. It is showing the differences but not at the right index. It is not writing "Correct" at the appropriate position. Please tell me how it can be fixed
This is my code
import pandas as pd
import numpy as np

   def report_diff(x):
    if x[0] == x[1]:
         return 'Correct'
    else:
         return '{} ---> {}'.format(*x)

def has_change(row):
if "--->" in row.to_string():
    return "Y"
else:
    return "N"

df1 = pd.read_excel(r'File1.xlsx', 'Sheet1', na_values=['NA']) df2 =
pd.read_excel(r'File2.xlsx', 'Sheet1', na_values=['NA'])

df = pd.read_excel(r'File1.xlsx') writer =
pd.ExcelWriter('Differences.xlsx')
df.to_excel(writer,'Highlighting-Error',index=False)

diff_panel = pd.Panel(dict(df1=df1,df2=df2))

diff_output = diff_panel.apply(report_diff, axis=0)

diff_output['has_change'] = diff_output.apply(has_change, axis=1)

diff_output[(diff_output.has_change ==
'Y')].to_excel(writer,sheet_name='Difference-Sheet',index=False,
                                                columns["dbsymbol","alias"])

writer.save()

data:
dbSymbol    Alias
UQ_121      mike
UQ142       Sam
UQ143       john
UQ144       deep
UQ145      shubh
UQ_121      joe
UQ_121      name

dbSymbol    Alias
UQ_121      mike
UQ142       sammy
UQ143       johnny
UQ144           deep
UQ145           shubh
UQ_121        Ann

Output:
dbSymbol    Alias
UQ_121      mike
UQ142       Sam---> Sammy
UQ143       john--->Johnny
UQ144       deep
UQ145      shubh
UQ_121        Ann--->mike
UQ_121     shubh-->mike
UQ_121     name-->mike

A: I think your solution should be simplify DataFrame.where and for Falses values of boolean mask join both DataFrames with --->:
mask = df1 == df2
diff_output = df1.where(mask, df1.astype(str) + ' ---> ' + df2.astype(str))
print (diff_output)
  dbSymbol             Alias
0   UQ_121              mike
1    UQ142    Sam ---> sammy
2    UQ143  john ---> johnny
3    UQ144              deep
4    UQ145             shubh

Detail:
print (mask)
   dbSymbol  Alias
0      True   True
1      True  False
2      True  False
3      True   True
4      True   True

EDIT: If different length of DataFrames with duplicates is possible use:
print (df1)
  dbSymbol  Alias
0   UQ_121   mike
1    UQ142    Sam
2    UQ143   john
3    UQ144   deep
4    UQ145  shubh
5   UQ_121    joe
6   UQ_121   name

print (df2)
  dbSymbol   Alias
0   UQ_121    mike
1    UQ142   sammy
2    UQ143  johnny
3    UQ144    deep
4    UQ145   shubh
5   UQ_121     Ann

df1['count'] = df1.groupby('dbSymbol').cumcount()
df2['count'] = df2.groupby('dbSymbol').cumcount()
df1 = df1.set_index(['count','dbSymbol'])
df2 = df2.set_index(['count','dbSymbol'])
df1, df2 = df1.align(df2)
df1 = df1.fillna('').reset_index()
df2 = df2.fillna('').reset_index()

print (df1)
   count dbSymbol  Alias
0      0    UQ142    Sam
1      0    UQ143   john
2      0    UQ144   deep
3      0    UQ145  shubh
4      0   UQ_121   mike
5      1   UQ_121    joe
6      2   UQ_121   name

print (df2)
   count dbSymbol   Alias
0      0    UQ142   sammy
1      0    UQ143  johnny
2      0    UQ144    deep
3      0    UQ145   shubh
4      0   UQ_121    mike
5      1   UQ_121     Ann
6      2   UQ_121

mask = df1 == df2
diff_output = df1.where(mask, df1.astype(str) + ' ---> ' + df2.astype(str))
print (diff_output)
   count dbSymbol             Alias
0      0    UQ142    Sam ---> sammy
1      0    UQ143  john ---> johnny
2      0    UQ144              deep
3      0    UQ145             shubh
4      0   UQ_121              mike
5      1   UQ_121      joe ---> Ann
6      2   UQ_121        name --->


text:
Q: Unable to use self-signed certificate that imported to ACM I have created and imported self-signed certificate to amazon certificate manager. On acm console, it looks successfully imported. I want to use this sertificate to aws client VPN endpoint.
At "Server certificate ARN" section of "Create Client VPN Endpoint" page in the VPC console, My certification dose not show up in the list.
"aws acm describe-certificate --certificate-arn " command returns my certificate information. But "aws acm list-certificates" command returns "CertificateSummaryList" with null.
I also tried to create VPN endpoint using aws cli "aws ec2 create-client-vpn-endpoint" specifying my certificate arn with "--authentication-options" but it end up to error as well.
Can someone tell me how to fix this?

A: Can you please check if your certificate has been created in the same region where you want to create the client vpn endpoint?The certificate arn will list something like
arn:aws:acm:::certificate/xxxxxxxxxxxxxx
If your certificate is created in a different region in might not show up in the drop down menu.

A: Might be a bit late, but I just had the same issue.
One reason for the certificate not showing up is if it has been created without specifying a domain.
You can specify the domain using the -subj switch in openssl.
E.g.
openssl req -new -x509 -nodes -sha1 -days 3650 -subj '/CN=yourdomain.com' -extensions v3_ca -key my-aws-private.key > my-aws-public.crt

See https://www.digicert.com/kb/ssl-support/openssl-quick-reference-guide.htm#Usingthe-subjSwitch


text:
Q: JavaScript shake image using getelementbyid I found a tutorial on how to make an image shake when a event happens. It works, However I would like to avoid using the div tag and use the getElementById (since it has a id). I did some googled around and couldn't find anything on the subject. So it may not be at all possible?
Whenever I do this is doesn't work.
I changed this
 $('#mySubmit input').shake();

to this
 getElementByid("mySubmit").shake();

And the entire script
JsFiddle
I'm pretty new to JavaScript, So if this is completely dumb and doesn't make sense please explain why.
Thanks for your help.

A: Since you have an id you can use jQuery id selector, but you in your case 2 elements have the same id that is not valid as ID has to be unique. So assign different ID's to the div and input button and use the id-selector like

jQuery.fn.shake = function () {
    this.each(function (i) {
        $(this).css({
            "position": "relative"
        });
        for (var x = 1; x <= 9; x++) {
            $(this).animate({
                left: -25
            }, 10).animate({
                left: 0
            }, 50).animate({
                left: 25
            }, 10).animate({
                left: 0
            }, 50);
        }
    });

}

function start() {
    $('#mySubmit').shake();

};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mySubmitCt" align="center">
    <input type="image" id="mySubmit" src="http://ezelrn.com/session/image/ButtonBlkForward.png">
</div>
<button onclick="start();">test</button>

A: Above seems to answer the question, but I also have an alternative approach you might consider using CSS.

Visit the website: http://elrumordelaluz.github.io/csshake/ for more
  information :)

Happy Coding!


text:
Q: Why is the building system not available/not installed? OK, so basically, after I downloaded Sublime Text and Python 3 (I cannot deselect the "Install launcher for all users" thing) according to Crash Course Python, I followed the instructions of how to change the build system, by entering "cmd": ["python3", "-u", "$file"], then saved this file under the name "Python3.sublime-build." When I have changed the building system under Tools to Python3. When I finished, I entered the code print("Hello Python World!"), but in the console where we would usually see the things pop up, I only got "Python was not found but can be installed from the Microsoft Store: https://go.microsoft.com/fwlink?linkID=2082640[Finished in 0.2s]"
Why is this?


text:
Q: Pow and VMware Fusion I am using Pow to serve a Rack application on Mac OS X. http://myapp.dev correctly displays the application. On the same machine I am using VMware Fusion to run Windows 7 while sharing the Mac's network connection. I would like to test the Rack application using Internet Explorer within the VM. http://vmnet8.adapter.ip.address correctly displays the "Pow is installed screen". However, htttp://myapp.dev no longer works.
I understand that Pow creates a DNS resolver and uses it's own DNS server to intercept domains ending in ".dev" and redirect them to localhost. Is it possible to get this to work within the VM also?

A: In my case I uses virtualbox, but it looks like it is kind the same concern I had to deal with, so:

*

*Get the IP used by your Mac with ifconfig or any other way you prefer. In this case lets assume the IP address is 10.249.158.68

*This link explains how to execute POW server from other computer; in our case it will be the virtualized Windows image: http://pow.cx/manual.html#section_2.1.5
So open IE[7|8|9] on your Windows virtual machine and type:
http://myapp.10.249.158.68.xip.io/ ---> replaces "myapp" to the name used in your Mac to refer your project

A: Create a symlink in your ~/.pow directory called default, and point it to the app you would like to test in VMWare.  http://vmnet8.adapter.ip.address will now use that app instead of presenting the default pow screen, as will http://<myhostname>.local.


text:
Q: Using htmltopdf want pdf in greek language I am having hard time trying to generate PDF files containing Greek letters using htmltopdf.
English letters appear in results but not the Greek ones. Searching for the problem, I think it might be related to the font used. I do not know what ttf file to use if this is the problem.I have set encoding as 'Cp1253'
Thanks in advance

A: I would suggest you switch to mPDF! It is a little bit slower than HTML2PDF, but it handles almost all Unicode languages, and has many more features bundled with it.

mPDF is a PHP class which generates
  PDF files from UTF-8 encoded HTML. It
  is based on FPDF and
  HTML2FPDF, with a number of
  enhancements.


text:
Q: Pandas: Assign column from single-indexed df to multi-indexed df Consider three dataframes:
df1 = pd.DataFrame({'x1': [1,2,3], 'a': [1,1,2], 'b': [10,20,10], 'c':[100, 200, 300]}).set_index(['a', 'b', 'c'])
df2 = pd.DataFrame({'x2': [1,3,4], 'a': [1,2,2], 'b': [10,10,20]}).set_index(['a', 'b'])
df3 = pd.DataFrame({'x3': [1,4], 'a': [1,2]}).set_index('a')

If I do
df1['x2'] = df2['x2']

pandas will match the multiindex properly and df1 will contain:
                x1  x2
a   b   c
1   10  100     1   1.0
    20  200     2   NaN
2   10  300     3   3.0

However, if I do:
df1['x3'] = df3['x3']

Result would be:
                x1  x3
a   b   c
1   10  100     1   NaN
    20  200     2   NaN
2   10  300     3   NaN

I am, of course, expecting to get x3 = [1, 1, 4] instead of all NaNs. I guess this is because df3 doesn't have a Multiindex? Is there some nice way to do this, without merging on index or reindexing?


text:
Q: click data on/off in legend python scatterplot So I've found this code: https://matplotlib.org/examples/event_handling/legend_picking.html. And I'm trying to make it work for data points instead of lines. So I thought I just change the marker in 'o', but that doesn't seem to work.
Also I want to use this in an animation, so that I can decide if I want to follow a datapoint or not. In the end I want to have 10 clickable legend entries.
What I'm trying to do is to just put a marker in the line1, and line2, code:
import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 0.2, 0.1)
y1 = 2*np.sin(2*np.pi*t)
y2 = 4*np.sin(2*np.pi*2*t)

fig, ax = plt.subplots()
ax.set_title('Click on legend line to toggle line on/off')
line1, = ax.plot(t, y1, ls='None', marker='o', color='red', label='1 HZ')
line2, = ax.plot(t, y2, ls='None', marker='o', color='blue', label='2 HZ')
leg = ax.legend(loc='upper left', fancybox=True, shadow=True)
leg.get_frame().set_alpha(0.4)

# we will set up a dict mapping legend line to orig line, and enable
# picking on the legend line
lines = [line1, line2]
lined = dict()
print(lined)

for legline, origline in zip(leg.get_lines(), lines):
    legline.set_picker(5)  # 5 pts tolerance
    lined[legline] = origline

def onpick(event):
    # on the pick event, find the orig line corresponding to the
    # legend proxy line, and toggle the visibility
    legline = event.artist
    origline = lined[legline]
    vis = not origline.get_visible()
    origline.set_visible(vis)
    # Change the alpha on the line in the legend so we can see what lines
    # have been toggled
    if vis:
        legline.set_alpha(1.0)
    else:
        legline.set_alpha(0.2)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

Thanks for looking at my problem!

A: not sure if you're still looking for an answer to this, but I wanted the same thing and this is how I tweaked the code you linked to:
"""
Enable picking on the legend to toggle the original line on and off
"""
import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 0.2, 0.02)
y1 = 2*np.sin(2*np.pi*t)
y2 = 4*np.sin(2*np.pi*2*t)

fig, ax = plt.subplots()
ax.set_title('Click on legend line to toggle line on/off')
line1leg, = ax.plot(0, 0, lw=2, c='r', label='1 HZ')
line2leg, = ax.plot(0, 0, lw=2, c='b', label='2 HZ')
line1, = ax.plot(t, y1, 'ro', lw=0, label='_nolegend_')
line2, = ax.plot(t, y2, 'bo', lw=0, label='_nolegend_')
leg = ax.legend(fancybox=True, shadow=True)
leg.get_frame().set_alpha(0.4)

# we will set up a dict mapping legend line to orig line, and enable
# picking on the legend line
lines = [line1, line2]
lined = dict()
for legline, origline in zip(leg.get_lines(), lines):
    legline.set_picker(5)  # 5 pts tolerance
    lined[legline] = origline

def onpick(event):
    # on the pick event, find the orig line corresponding to the
    # legend proxy line, and toggle the visibility
    legline = event.artist
    origline = lined[legline]
    vis = not origline.get_visible()
    origline.set_visible(vis)
    # Change the alpha on the line in the legend so we can see what lines
    # have been toggled
    #if not vis:
    #    legline.set_alpha(2)
    #    legline.set_marker('^')
    #else:
    #    legline.set_linewidth(3)
    #    legline.set_marker('<')
    if vis:
        legline.set_alpha(1.0)
    else:
        legline.set_alpha(0.2)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

It's essentially a cheat, but I found that if I added markers to the plot I couldn't make changes to the marker that appeared in the legend. So we plot the data once as a line, giving it only the point (0,0), then plot the data again as with markers and no line. Then we can continue on and set the legend line transparency to coincide with toggling the plot markers on/off.


text:
Q: Why can't I crawl the page? I am trying to scrape a table on a website and then convert it into a CSV form. The thing is nothing shows up despite my code. Could you tell me what went wrong?
URL: http://www.multiclick.co.kr/sub/gamepatch/gamerank.html
Don't worry about the language. Please just set the date anytime that is a day or two earlier than today on the calendar and click on the magnifying glass. Then you'll be able to see a table.
# Load the required modules
import urllib
from bs4 import BeautifulSoup
import pandas as pd

# Open up the page
url = "http://www.multiclick.co.kr/sub/gamepatch/gamerank.html"
web_page = urllib.request.Request(
        url,
        data = None,
        headers={'User-Agent': ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) "
                                "AppleWebKit/537.36 (KHTML, like Gecko) "
                                "Chrome/35.0.1916.47 Safari/537.36")})
type(web_page)
web_page = urllib.request.urlopen(web_page)

# Parse the page
soup = BeautifulSoup(web_page, "html.parser")
print(soup)

# Get the table
    # Get the columns
    # Get the rows
    # Stack them altogether

# Save it as a csv form

A: Ais @mx0 said, instead of fetching the mian page, fetch the ajax call, for example:
import csv
import requests

link = "http://ws.api.thelog.co.kr/service/info/rank/2018-10-18"

req = requests.get(link)
content = req.json()
with open('ranks.csv', 'w', newline='') as csvfile:
    csv_writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    # write column titles
    csv_writer.writerow(['gameRank', 'gameName', 'gameTypeName', 'gameShares', 'publisher', 'gameRankUpDown'])
    # write values
    for row in content["list"]:
        csv_writer.writerow(list(row.values()))


text:
Q: Is it OK to use the instance variables created for auto-synthesized properties? Currently I can write a class like this:
@interface Foo
@property(assign) float bar;
@end

@implementation Foo

- (void) someMethod
{
    _bar = 4;
}

@end

It's convenient that I can leave out the @synthesize boilerplate list, and if I can get used to the underscore notation, I get the nice readable rule that everything named _foo is an instance variable. Is it OK to use the auto-generated instance variables like this? I mean, maybe they're supposed to be invisible even to the class author?

A: Yes, it is absolutely OK to use these variables.
Dropping the @synthesize requirement altogether was a convenience: the @synthesize xyz is now inserted implicitly - that is the only difference. Designers of the compiler reasoned that since they can unambiguously identify situations when you want to synthesize accessors vs. situations when you provide custom implementations, it is reasonable to stop asking you for an explicit @synthesize.

A:
Is it OK to use the instance variables created for auto-synthesized properties?

Absolutely

It's convenient that I can leave out the @synthesize boilerplate list, and if I can get used to the underscore notation, I get the nice readable rule that everything named _foo is an instance variable.

Of course, you also have the ability to specify a name using @synthesize foo = f00;.

Is it OK to use the auto-generated instance variables like this? I mean, aren't they supposed to be invisible even to the class author?

Nope. It is necessary for them to be internally accessible. That's less frequent if you are using ARC, but the common case where you would access them directly is initialization and destruction (cases where the accessor methods should not be used).


text:
Q: Grab end of URL before GET $_parameters I'm having an issue with grabbing the last part of the URL before the query parameters.
The current solution I'm using is this:
$base_url = current_url();
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
$language = $uri_segments[1];
$end_url = array_pop($uri_segments);

I then pass the $end_url through a Switch statement to modify form fields, depending on the value.
Is there something I'm missing or is there a more efficient way to grab the last part of the URL?
Any suggestions would be helpful and greatly appreciated.
Thanks!

A: try this
<?php
$url = parse_url('http://example.com/project/controller/action/param1/param2');
$url['sections'] = explode('/', $url['path']);

$last = end($url['sections']);
echo $last;
?>

output

param2


text:
Q: Opening a file inside the terminal I want to open files inside the terminal, like with vim or whatever, but I have no idea how. For example, instead of opening a .js file with atom, now I open it inside the terminal with vim. Any ideas?
I think you could use the Appify script, but I don't know how to make it work with opening files. This would mean that you open the file by double clicking on it in finder, and opening it into terminal.

A: Just type vim file.js into the terminal, where file.js is the file you want to open.


text:
Q: SynchronizationContext is null in OnStart method of WindowsService I am trying to create a background Task for my windows service (it is already installed via InstallUtil.exe) and use SynchronizationContext to send some messages to the main Service thread.
Unfortunately SynchronizationContext.Current is always null on service start.
I've saw some questions around the topic and hints on why SynchronizationContext is null in various scenarios (e.g. in Winforms, WPF apps) but no clue about the Windows services.
How can I resolve this issue?
Below the code:
using Lextm.SharpSnmpLib.Messaging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SnmpTrapListenerService
{
    public partial class SnmpTrapListenerService : ServiceBase
    {
        public Listener Listener { get; set; }
        public CancellationTokenSource CancellationTokenSource { get; set; }
        public Task PulseTask { get; set; }
        public SynchronizationContext SyncContext { get; set; }

        public SnmpTrapListenerService()
        {
            //Debugging windows service.
            Debugger.Launch();
            InitializeComponent();
            Debug.WriteLine($"Main service threadId: {Thread.CurrentThread.ManagedThreadId}");
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                CancellationTokenSource = new CancellationTokenSource();
                SyncContext = SynchronizationContext.Current; //Here I'm getting always null.
                PulseTask = new Task(x =>
                {
                    Debug.WriteLine($"Pulse task threadId: {Thread.CurrentThread.ManagedThreadId}");
                    while (true)
                    {
                        var context = (SynchronizationContext)x;
                        context.Post(new SendOrPostCallback(y => DoSomethingOnServiceMainThread()), null);
                        Debug.WriteLine($"Alive at {DateTime.Now.ToLongTimeString()}");
                        Thread.Sleep(5000);
                    }
                }, SyncContext, CancellationTokenSource.Token);

                PulseTask.Start();

                Listener = new Listener();
                Listener.AddBinding(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 162)); //IP address of listener system
                Listener.MessageReceived += Listener_MessageReceived;
                Listener.StartAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            Debug.WriteLine("Service started");
        }
        private static void Listener_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            File.AppendAllText("servicelog.log", "Version :" + e.Message.Version + "\n");
            File.AppendAllText("servicelog.log", "Version :" + e.Message.Scope.Pdu.Variables[4].Data.ToString() + "\n");
        }

        protected override void OnStop()
        {
            CancellationTokenSource.Cancel();
            Listener.Stop();
            Debug.WriteLine("Service stopped");
        }

        private void DoSomethingOnServiceMainThread()
        {
            //Some work that needs to be done one Service main thread.
        }
    }
}

A: Console and Service applications do not have a default SynchronizationContext.  This is because there is no "UI" thread that is pumping messages constantly while the application runs.
The question is why do you need a synchronization context?


text:
Q: How to use request variables in  Using a constant string in a  statement works fine like this:
Request with browser or curl:
https://example.com/images/filename.jpeg

In httpd.conf:
<IfFile /var/www/example/images/filename.jpeg> ...do something ... </IfFile>

But of course one wants to use variables, like:
<IfFile %{REQUEST_FILENAME}> ... </IfFile>

I can seem to get that to work. I tried many different possible syntaxes and they were all approved by apachectl configtest. However, none produces the desired result. No file is ever matched. In place of %{REQUEST_FILENAME} I've also tried %{DOCUMENT_ROOT} . %{REQUEST_URI} and "expr=%{REQUEST_FILENAME}"
I have tried all variables (REQUEST_FILENAME, REQUEST_URI, DOCUMENT_ROOT) with the prefix ENV: ( i.e %{ENV:REQUEST_FILENAME} ) and/or with quotation marks ( "%{REQUEST_FILENAME}" ).
It seems like I can't address any header variables in an <IfFile> statement.


text:
Q: PySNMP : ImportError: No module named pyasn1.compat.octets I'm trying to use PySNMP on windows, but when I try to import cmdgen I see following Error:
from pysnmp.entity.rfc3413.oneliner import cmdgen
ImportError: No module named pyasn1.compat.octets

How can I solve this error, I also don't touched init.py
Thank you

A: Make sure you have the latest pyasn1 package also installed on your system for the same Python version as pysnmp is installed.

A: I met with the same mistake.
I copied the library from this link into the downloaded project dirctory and corrected the error
this link :
https://pypi.python.org/pypi/pyasn1/


text:
Q: TFS 2010 Cannot Change Accout Identity I have recently moved our TFS 2010 server to new server, when I'm trying to configure Reporting server and enter the server name and populate URLs and then press ok, the tfs tells me that user or group is not recognized

I tried to run this command
TFSConfig identities /change /fromdomain: OldComputerorDomainName /todomain: NewDomainName /account: OldTFSServiceAccount /toaccount:NewTFSServiceAccount
in order to change the account identity as i moved from a domain to another domain but it doesn't work.
Any ideas how i can solve that?

A: I have run this command
TFSConfig identities /change /fromdomain: OldComputerorDomainName /todomain: NewDomainName
before this command
TFSConfig Accounts /ResetOwner /SQLInstance:ServerName /DatabaseName:DatabaseName
and everything is working now

A: This is another interesting case. Can you try and connected to the Reporting Services server using SQL Server Management Studio and not Reporting Services administration website. In the root folder permissions, remove the reference to OldComputer\Administrators and added the one to NewComputer\Administrateurs.
HTH
Cheers, Tarun


text:
Q: copy all files with certain extension Hello I want to copy all files with and a specific extension. I've tried a few things but it isn't working. During my debug I get an exception "Illegal characters used in path" I'm guessing it doesn't like *.xls any suggestions?
First try
 My.Computer.FileSystem.CopyFile("C:\test\test\mxw\*.xls\", "C:\workorder1-23\workorder1-23\mxw\", True)

second try
For Each f In Directory.GetFiles("C:\test\test\mxw\*.xls\", CStr(SearchOption.AllDirectories))
     If My.Computer.FileSystem.FileExists(f.ToString) Then
          File.Copy("C:\test\test\mxw\*.xls\", "C:\workorder1-23\workorder1-23\mxw\", True)
     End If
Next

A: CopyFile copies just one file.
You cannot use it with wildcards to copy a group of files.  (The invalid character is probably the wildcard)
And you should not append a backslash at the end of the file.
So let me try to replace your code with this
For Each f In Directory.GetFiles("C:\test\test\mxw", "*.xls", SearchOption.AllDirectories)
     If File.Exists(f) Then
          File.Copy(f, Path.Combine("C:\workorder1-23\workorder1-23\mxw", Path.GetFileName(f)), True)
     End If
Next

Also Directory.GetFiles has three parameters, a path, a pattern and a flag to read subfolders

A: Since File.Copy does not create directories the provided answer will only work if the target directories exist. Add a Create.Directory(f) before the File.Copy if they don't.


text:
Q: Python's json dumps/loads make integer keys of my dict str when i serialize and deserialize python built-in structure I'm expect output same as input
arr2 = [1,2,'3']
arr2_json = json.dumps(arr2)
json.loads(arr2_json)

Out[16]: [1, 2, '3']
BUT when I'm tring do it with dict I got str keys instead of integer
dict1 = {0: 'object0', '1': 'object2'}
json1 = json.dumps(dict1)
json.loads(json1)

Out[6]: {'0': 'object0', '1': 'object2'}
Notice keys must be [0, '1'] but actually are ['0', '1']
What is it? My misunderstanding or ussue in python
Python 3


text:
Q: How to enable CredSSP I am trying to use the -Authentication CredSSP switch when entering with PowerShell (2.0) in order to remotely launch a Script that can write to files or set up new PSDrives.
I get an error when I invoke Enter-PSSession with CredSSP, saying that the target computer is not approved.
I Enabled CredSSP as server on the target computer and as a client on the computer that executes the New-PSSession, with delegate computer set to *.
We are in a domain, the DC runs Windows Server 2008 R2, clients run Windows 7.
In AD, both stations are approved when I look at Properties->Delegation.
I also opened gpedit and activated the delegation specifiying the target computer name.
Here is the error message (French):
La connexion au serveur distant a échoué avec le message d'erreur suivant : Le client WinRM ne peut pas traiter la demande. Une stratégie d'ordinateur ne permet pas la délégation des informations d'identification de l'utilisateur à l'ordinateur cible car ce dernier n'est pas approuvé. L'identité de l'ordinateur cible ne peut pas être vérifiée si vous configurez le service WSMAN pour utiliser un certificat valide à l'aide de la commande suivante : winrm set winrm/config/service '@{CertificateThumbprint="<thumbprint>"}'  Sinon, vous ouvez rechercher dans l'Observateur d'événements un événement qui spécifie que le SPN suivant n'a pas pu être créé : WSMAN/<computerFQDN>. Si vous trouvez cet événement, vous pouvez manuellement créer le SPN à l'aide de setspn.exe.  Si le SPN existe, mais que CredSSP ne peut pas utiliser Kerberos pour valider l'identité de l'ordinateur cible et si vous souhaitez toujours autoriser la délégation des informations d'identification de l'utilisateur à l'ordinateur cible, utilisez gpedit.msc et examinez la stratégie sui
vante : Configuration de l'ordinateur -> Modèles d'administration -> Système -> Délégation d'informations d'identification -> Autoriser les nouvelles informations d'identification avec l'authentification du serveur NTLM uniquement.  Vérifiez qu'elle est activée et configurée avec un SPN approprié pour l'ordinateur cible. Par exemple, pour le nom d'ordinateur cible « monserveur.domaine.com », le SPN peut être : WSMAN/monserveur.domaine.com ou WSMAN/*.domaine.com. Renouvelez la demande après ces modifications. Pour plus d'informations, voir la rubrique d'aide bout_Remote_Troubleshooting.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportExc
   eption
    + FullyQualifiedErrorId : PSSessionOpenFailed

What are the others parameters that can prevent CredSSP ?
Edit:
Ok so I have a temporary workaround for mounting a drive on a remote PSSession where CredSSP is not allowed. I use the
net use X: \\xxx.xxx.xxx.xxx /user:username password

syntax when I'm on the remote session (i.e. not the New-PSDrive cmdlet). This seems to work fine, even with the Invoke-Command on a remote Computer.
But still need to enable CredSSP, that would prevent me from hardcoding credentials...

A: There is a bug in PowerShell 2.0 (fixed in PS 3.0): FileSystem Provider should support credentials

It's not possible to supply alternate credentials when using any
  cmdlets with the FileSystem provider. Even New-PSDrive, which accepts
  a -Credentials parameter, won't accept it with the FileSystem
  provider.
The bottom line here is that the ancient NET USE command has more
  power than PowerShell's New-PSDrive ...

So if you're stuck with PS 2.0, there is no way (AFAIK) to force New-PSDrive cmdlet to use credentials. Workarounds exist, but they all use hardcoded crdentials:
Net use (as you already did):
net use X: \xxx.xxx.xxx.xxx /user:username password

or
Wscript:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("X:", "\\server\share", $false, "domain\user", "password")


text:
Q: How do i make an ultrasonic sensor trigger an LED to stay on until reset? So, I know it's probably SUPER simple, but I'm new to arduino and I'm just drawing a blank. I'm making a motion detector with an HC-SRO4 ultrasonic sensor. Right now I have it set so whenever it senses an object within 60 cm, it turns on an LED light, but when the object disappears, the LED turns off. What I would like to happen is that it would stay on until I press a button to reset it. Any help is really appreciated and i thank you in advance.
void setup() {
#define LED 8
#define trigPin 12
#define echoPin 13
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED, OUTPUT);

}

void loop() {
 int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1

;if (distance >= 60 || distance <= 0){
Serial.println("no object detected");
digitalWrite(LED, LOW);}

else {
Serial.println("object detected");
digitalWrite(LED, HIGH);
}}

A: for this you have make low pushbutton pin while pressing.once the oobject came near the flag will set once the set it will move to while loop and run until the button pressed
#define LED 8
#define trigPin 12
#define echoPin 13
#define push_button 5
int flag=0;
void setup() {

Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED, OUTPUT);
pinMode(push_button,INPUT);
}

void loop() {
 int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if(digitalRead()==0)
{
flag=0;
}

if (distance >= 60 || distance <= 0){
Serial.println("no object detected");

digitalWrite(LED, LOW);}

else {
Serial.println("object detected");
flag=1;
while(flag=1)
{
  digitalWrite(LED, HIGH);}
}}


text:
Q: iReport compile error (java.lang.String cannot be resolved) in maven NetBeans project Maybe somebody can help me to solve this issue.
I am trying to integrate iReport in my NetBeans project and can't solve the following issue.
When I create new report from "MyProject ---> New ---> Empty report" it won't compile and show me Preview from report Designer Tab it gives me the following error:
Compilation exceptions: com.jaspersoft.ireport.designer.compiler.ErrorsCollector@3d50d9ef  net.sf.jasperreports.engine.JRException: Errors were encountered when compiling report expressions class file: 1. The type java.lang.String cannot be resolved. It is indirectly referenced from required .class files /* ^ 1 errors      at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:204)     at com.jaspersoft.ireport.designer.compiler.IReportCompiler.run(IReportCompiler.java:512)     at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1418)     at org.netbeans.modules.openide.util.GlobalLookup.execute(GlobalLookup.java:45)     at org.openide.util.lookup.Lookups.executeWith(Lookups.java:278)     at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:2033)
At the same time everything looks fine if I create new report from iReport Welcome Screen in NetBeans.
This my Pom file.
<?xml version="1.0" encoding="UTF-8"?>

<repositories>
    <repository>
        <id>unknown-jars-temp-repo</id>
        <name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
        <url>file:${project.basedir}/lib</url>
    </repository>
    <repository>
        <id>Jasper Reports</id>
        <url>http://jaspersoft.artifactoryonline.com/jaspersoft/jr-ce-releases</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.19</version>
        <exclusions>
            <exclusion>
                <groupId>com.google.protobuf</groupId>
                <artifactId>protobuf-java</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>mchange-commons-java</artifactId>
        <version>0.2.20</version>
    </dependency>
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.5</version>
    </dependency>
    <dependency>
        <groupId>com.toedter</groupId>
        <artifactId>jcalendar</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>org.netbeans.external</groupId>
        <artifactId>AbsoluteLayout</artifactId>
        <version>RELEASE112</version>
    </dependency>
    <dependency> <!-- needed by jasperreports to build-->
        <groupId>com.lowagie</groupId>
        <artifactId>itext</artifactId>
        <version>2.1.7</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports -->
    <dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports</artifactId>
        <version>${jasperreports.version}</version>
    </dependency>
    <dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports-functions</artifactId>
        <version>${jasperreports.version}</version>
    </dependency>
    <dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports-fonts</artifactId>
        <version>6.11.0</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.30</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>xalan</groupId>
        <artifactId>xalan</artifactId>
        <version>2.7.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy</artifactId>
        <version>2.5.9</version>
    </dependency>
    <dependency>
        <groupId>org.mariadb.jdbc</groupId>
        <artifactId>mariadb-java-client-jre7</artifactId>
        <version>1.6.1</version>
    </dependency>
</dependencies>

<pluginRepositories>
    <pluginRepository>
        <id>Jasper Reports</id>
        <url>http://jaspersoft.artifactoryonline.com/jaspersoft/jr-ce-releases</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>

<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>13</maven.compiler.source>
    <maven.compiler.target>13</maven.compiler.target>
    <jasperreports.version>6.11.0</jasperreports.version>
</properties>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <configuration>
                <argLine>-Djava.awt.headless=true</argLine>
            </configuration>
        </plugin>
        </plugins>
    </pluginManagement>
    <plugins>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <id>copy-resources</id>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${basedir}/target/TechInfo</outputDirectory>
                        <resources>
                            <resource>
                                <directory>resources</directory>
                                <filtering>true</filtering>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.2.0</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>techinfo1.MainPage</mainClass>
                    </manifest>
                    <manifestEntries>
                        <Class-Path>.</Class-Path>
                    </manifestEntries>
                </archive>
                <finalName>TechInfo_1.0</finalName>
            </configuration>
        </plugin>
        <plugin>
            <groupId>com.alexnederlof</groupId>
            <artifactId>jasperreports-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <sourceDirectory>${project.build.sourceDirectory}/../resources</sourceDirectory>
                <outputDirectory>${project.build.outputDirectory}/jrxml</outputDirectory>
                <verbose>true</verbose>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>net.sf.jasperreports</groupId>
                    <artifactId>jasperreports-functions</artifactId>
                    <version>6.11.0</version>
                </dependency>
                <dependency>
                    <groupId>net.sf.jasperreports</groupId>
                    <artifactId>jasperreports</artifactId>
                    <version>6.11.0</version>
                </dependency>
            </dependencies>
            <executions>
                <execution>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>jasper</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>

I also downgraded JRE from 8 to JRE 7.
Added whole bunch of files in Libraries for iReport.
From Report query it gives me same error. It connects to database but can't read from it.

Any ideas what am I missing in my project?
Thank you in advance.

A: i dont know how to explain, but this work for me.
go to report properties then change the language to groovy. before i change my language to java then error like that.


text:
Q: Customer is not created on stripe account I am running this node.js code to create customer on stripe account function deploy successful but failed to create customer on stripe I am not getting what I am missing.
Fire base functions folder is also not showing the function there.
const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);
    const stripe = require('stripe')("secret key here");
    var customer;

    stripe.customers.create(
      {
        email: 'customer@example.com',
      },
      {
        maxNetworkRetries: 2,
      }
    );

A: When you use APIs to services (viz. stripe.com and firebase) outside your complete control, you must check for errors. If you're using a service incorrectly the error will explain, or at least hint, what you're doing wrong.
The stripe-node API documentation suggests you invoke stripe.customer.create() as an awaited function, like this:
const customer = await stripe.customers.create({
         email: 'customer@example.com',
});

This is easy if you call it from an async function. You should use this sort of code in your async function to check for errors back from stripe.com.
try {
   const customer = await stripe.customers.create({
         email: 'customer@example.com',
    });
    /* here's your customer object */
}
catch (error) {
    console.error ('stripe', error);
}

If you do not call it from an async function, you can wait for results using the Promises scheme.
    stripe.customers.create({
         email: 'customer@example.com',
       })
    .then ( function (customer) {
             /* here's your customer object */
       })
    .catch ( function (error) {
        console.error ('stripe', error);
       });

If you haven't yet figured out how async/await or Promises work, the time has come for you do to that.


text:
Q: CSS3: Floating first div between second and third Should be a simple solution to this:
I have the divs in the following order:

I HAVE to have them in this order. Using floats, how can I get the first div ("middle") to fall in between the second divs.
Each div has a set height and a set width (in px).
I've tried doing float:left; on the middle:

[[middle] right] [left]

and then float:right; on the top cluster:

[left [[middle] right]]]

but it shows up as

[middle][left][right]

Any help?
EDIT: this is the current source:
http://pastebin.com/sjiw9PLn
http://pastebin.com/NMsWk1nZ

A: you can write like this:
div{
display:inline-block;
}
#left{
 float:left;
}
#right{
 float:right;
}

Check this http://jsfiddle.net/8amez/

A: If you are, indeed, able to add a wrapper div element, then this works (insofar as your simple example) at JS Fiddle:
#left {
    float: left;
}

#wrap {
    width: 80%;
    float: right;
}

#wrap #middle {
    float: left;
}

#wrap #right {
    float: right;
}

Given the following HTML:

middle

right

left

Bear in mind, though, that this is likely to be fairly fragile; and would be better achieved by re-ordering your mark-up, or, if that can't be changed server-side, or in the HTML, using JavaScript to move things around, for example:
var middle = document.getElementById('middle'),
    left = document.getElementById('left');

middle.parentNode.insertBefore(middle,left.nextSibling);

JS Fiddle demo.

A: If widths and heights are set, use the css attribute:
position:absolute;

and play with:
left: 100px; /* width of the div on the left */

A: Long after for the pleasure :
pout all 3 divs in side another than will have a text-align-center property (just for the middle div) and let the left and right divs float as answered.

.group{
   text-align:center;
}

#left{
 display:inline-block;
   float:left;
}

#right{
   display:inline-block;
   float:right;
}

#middle{
 display:inline-block;

}

[left]

[middle]

[right]

A: Presuming it HAS to be in this order for some scraping tool grabbing the code relying on it being like this, why don't you just add some JavaScript to shuffle them about after the page has loaded.


text:
Q: Renaming files from CSV mapping using bash mangles files I'm trying to rename auto-generated PDF files so that each one contains the name of the user it will go to, using a CSV map of the current name to it's new name, using what I thought was a straight forward and simple script in a bash shell.
The original files in the directory are named in the format Cover_Letter_1.pdf, Cover_Letter_2.pdf, etc. and in the CSV, they are mapped in the format:
Cover_Letter_1.pdf,Cover_Letter_User1.pdf
Cover_Letter_2.pdf,Cover_Letter_User2.pdf
I CD into the directory (where both the files and the CSV are), and tried this script:
sed 's/"//g' rename_list.csv | while IFS=, read orig new; do echo mv "$orig" "$new"; done

which returns a preview, showing exactly what I'd expected:
mv Cover_Letter_1.pdf Cover_Letter_User1.pdf
mv Cover_Letter_2.pdf Cover_Letter_User2.pdf

(sed 's/"//g' files.csv was for if there are quotes in the file names in the CSV file, there just happen to not be for this first group of files)
So, I would remove echo to run it for real, but the result is that it mangles the files, transforming them into generic .file format, with gibberish names like P4L8I7~B.file
I ran a "previewed" command (e.g. mv Cover_Letter_2.pdf Cover_Letter_User2.pdf) just to make sure that part of the script was correct (it was).
EDIT: I just thought to try running sed 's/"//g' rename_list.csv | while echo IFS=, read orig new; do echo mv "$orig" "$new"; done which results in it running indefinitely in a while loop with no apparent end. I thought that it would terminate when there were no more commas in the file, but, if I'm understanding correctly, it's just trying to continue reading lines forever.

A: The problem was in the CSV file itself. The CSV was created in Windows and had CR LF EOL markers. Once I converted it to LF, it worked properly.

A: You can just change your command in the following way and it should work, if it displays properly the move commands.
(sed 's/"//g' rename_list.csv | while IFS=, read orig new; do echo mv "$orig" "$new"; done) | bash
This will read:
mv Cover_Letter_1.pdf Cover_Letter_User1.pdf
mv Cover_Letter_2.pdf Cover_Letter_User2.pdf

as commands and run it.
Take backup of your files before running this command.


text:
Q: YouTube - Download/Play Private Videos My iOS app is going to have private and public videos, and users can purchase private ones. Right now I'm using YouTube and the youtube-ios-player-helper library for video hosting. Loading a public video is extremely easy:
playerView.loadWithVideoId("M7lc1UVf-VE")

but how do you do it in the most simplistic way for private videos? Is there something as simple as:
let playerVars = [
    "username": username,
    "password": password,
]
playerView.loadWithVideoId("M7lc1UVf-VE", playerVars: playerVars)

or something equally as simple?

A: If you look at the YouTube Embedded Players and Player Parameters API Documentation, you will see that there is no way to pass in a user's credentials.
The only way to play private videos in a web view like the YTPlayerView helper class is to take control of the web view and have the user log into their YouTube account, and then play back the Private video in that specific web view session only. YouTube suggests marking videos as Unlisted rather than Private for playback on mobile devices.
Related discussion can be found in this similar question about the Android player and this Google Groups post.


text:
Q: How to install C# client library, particularly Google Cloud Text to Speech? I'm trying to use Google Cloud services such as Text-To-Speech in a Unity app.  On the quickstart page I've done the Before You Begin stuff. However, I can't "Install the Client Library". The provided line is:
Install-Package Google.Cloud.TextToSpeech.V1 -Pre
However, when I put this into my terminal it says "'Install-Package' is not recognized as an internal or external command, operable program or batch file."
I tried with Powershell too but got "Install-Package : A parameter cannot be found that matches parameter name 'Pre'.
At line:1 char:46

*

*Install-Package Google.Cloud.TextToSpeech.V1 -Pre

*~~~~

*CategoryInfo : InvalidArgument: (:) [Install-Package], ParameterBindingException

*FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage"
I've tried searching online but it seems like I'm just missing a crucial step or something. Is there supposed to be anything I do before trying to install the client library? Am I doing it in the wrong place? Help appreciated, thanks!
Edit:
Visual Studio displayed:
"Install failed. Rolling back...
Package 'Google.Cloud.TextToSpeech.V1.1.0.0-beta02' does not exist in project 'Assembly-CSharp'
Package 'Google.Cloud.TextToSpeech.V1.1.0.0-beta02' does not exist in folder 'C:\Users\bwubr\Documents\EventHorizonVR\packages'
Executing nuget actions took 1.03 sec
Install-Package : Could not install package 'Google.Cloud.TextToSpeech.V1 1.0.0-beta02'. You are trying to install this package into a project that targets '.NETFramework,Version=v3.5',
but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
At line:1 char:1
+ Install-Package Google.Cloud.TextToSpeech.V1 -Pre
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
 "

A: Install-Package is a feature of the Nuget package manager console. You can open this from Visual Studio by following these steps:

*

*Select the Tools menu

*Select NuGet Package Manager

*Package Manager Console

You can now run that command in the resultant window.
Alternatively, you can install it directly from the UI by selecting "Manage NuGet packages for the solution..." instead of "Package Manager Console".


text:
Q: Find file and directory size while ignoring symlink in sub-directories I have a directory structure where there are multiple symlinks at random depths.
For illustration purpose:
/fs
/fs/afile
/fs/blink -> /usr/local/lib
/fs/cdir/cfile
/fs/cdir/cdir/cdir/clink -> /var/log
/fs/edir/edir/efile
/fs/edir/elink -> /usr/local/bin

I want to find which file or folder utilizes the most space to do some cleanup. I am hoping an output similar to:
3.0G     /fs
4.0G     /fs/afile
3.3G     /fs/cdir
15.0G    /fs/edir

I tried running cd /fs && find -maxdepth 1 -type d | sudo xargs du -hs but this expands the symlinks underneath, which means the size of /fs/edir would include the content and size of /usr/local/bin in this case.
TLDR: For a given path, how do I find the size of all files or directories at depth=1, without expanding any underneath symlinks?
Note: I read du skip symbolic links but this case is different as the symlink in this case could be of any depth.


text:
Q: How to load pdf in webview from assets folder I have problem to load pdf from asset folder this code not working for me please help. when i open this location in chrome showing the pdf in app does not showing error="ERR_UNKNOWN_URL_SCHEME"
val web=findViewById<WebView>(R.id.weber)
    val settings = web.getSettings()
    settings.setJavaScriptEnabled(true)
    settings.builtInZoomControls = true
    web.setWebChromeClient(WebChromeClient())
    web.loadUrl("F:\\Studyfy\\app\\src\\main\\assets\\p.pdf")

A: 1) Enable the below permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2) Put this code block inside OnCreate method
            InputStream in = null;
            OutputStream out = null;
            File file = new File(getFilesDir(), "sample.pdf");
            try
            {
                in = assetManager.open("sample.pdf");
                out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

                copyFile(in, out);
                in.close();
                in = null;
                out.flush();
                out.close();
                out = null;
            } catch (Exception e)
            {
                Log.e("tag", e.getMessage());
            }

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://"+getFilesDir()+"/sample.pdf"),"application/pdf");
            startActivity(intent);

3) Put this method inside your class (Outside of OnCreate)
 private void copyFile(InputStream in, OutputStream out) throws IOException
        {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, read);
            }
        }


text:
Q: Truecrypt hidden volume space I am using truecrypt to encrypt thumb drives and laptop harddrive etc, and have a question regarding the hidden volume option. As i understand it, an encrypted volume is created inside another, and the outer volume can be filled with "dummy" data. What i am wondering is, owdoes Truecrypt handle t hidden volume? would not the outer volume, if mounted, show up as almost full, even thou there is only a few files in the outer volume?

A: I think the official doc is pretty clear about that :

If you mount a TrueCrypt volume within which there is a hidden volume, you may read data stored on the (outer) volume without any risk. However, if you (or the operating system) need to save data to the outer volume, there is a risk that the hidden volume will get damaged (overwritten). To prevent this, you should protect the hidden volume in a way described in this section.

When you activate the Hidden Volume Protection:

As soon as a write operation to the hidden volume area is denied/prevented (to protect the hidden volume), the entire host volume (both the outer and the hidden volume) becomes write-protected until dismounted (the TrueCrypt driver reports the 'invalid parameter' error to the system upon each attempt to write data to the volume).

The outer volume is not aware of the hidden volume, and that's why the hidden part risk to be corrupted (overwritten). So, you won't see the usage of the hidden volume in the outer's usage.


text:
Q: Making a list from range in Excel In original column I have years in range(s). Like
1865–1868

How do I transform it to comma separated list? Like:
1865, 1866, 1867, 1868

The current data format is TEXT. And I plan to change it to DATE.
NOTE: The original cell often consists mixed form. Like "1865–1868, 1870"

A: How about:
Public Function CSVList(rng As Range) As String
    Dim r As Range, ary1, ary2
    For Each r In rng
        v = r.Text
        If InStr(1, v, "-") = 0 Then
            CSVList = CSVList & "," & v
        Else
            ary = Split(v, "-")
                For i = CLng(ary(0)) To CLng(ary(1))
                    CSVList = CSVList & "," & CStr(i)
                Next i
        End If
    Next r
    CSVList = Mid(CSVList, 2)
End Function

or:

EDIT#1:
This UDF treats any non-numeral as a separator:
Public Function CSVList2(rng As Range) As String
    Dim r As Range, ary1, ary2, L As Long, i As Long, C As String
    For Each r In rng
        v = r.Text
        L = Len(v)
        C = ""
        For i = 1 To L
            If Not Mid(v, i, 1) Like "[0-9]" Then C = Mid(v, i, 1)
        Next i

        If C = "" Then
            CSVList2 = CSVList2 & "," & v
        Else
            ary = Split(v, C)
                For i = CLng(ary(0)) To CLng(ary(1))
                    CSVList2 = CSVList2 & "," & CStr(i)
                Next i
        End If
    Next r
    CSVList2 = Mid(CSVList2, 2)
End Function