text:
Q: override metadata in static constructor? I have a class that inherits the TextBox Class, call it MyTextBox
I'd like to redefine the default Background value for this class.
So I looked for a way to do so and found a good option: call BackgroundProperty.OverrideMetadata()
trouble is: where can I put this?
in the App.OnStartup()? Ugly and not practical, I'd like that to be in my Class's code file.
in the Class's contructor? I get an exception:

PropertyMetadata is already registered
  for the type 'MyTextBox'.

(seems fine to me, I understand why I get this perfectly)
So I looked again a found about the static constructor in C# (did not no about that earlier, what a pity)
so here's my code:
public class MyTextBox : TextBox
{
    static MyTextBox()
    {
        MyTextBox.BackgroundProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(App.Current.Resources["CustomBackgroundBrush"]));
    }
}

now, I'm pretty happy whith this, but Microsoft isn't. Namely, when I use the code analysis feature, I get this:
CA1810: Initialize reference type static fields inline
Hence my question: what can I do about it?

*

*ignore the warning? >> I don't like to ignore warnings

*move the call to the overrideMetadata method? >> I'd like to, but where?

any hints welcome, thanks
Edit: I'll add that I don't fully understand why I get this warning, since I am not initializing anything per say in my static constructor, or am I?

A: Here is the link from MSDN for overridding metadata for overridding metadata for a dependency property:
It states:
"Overriding metadata on a dependency property must be done prior to that property being placed in use by the property system (this equates to the time that specific instances of objects that register the property are instantiated). Calls to OverrideMetadata must be performed within the static constructors of the type that provides itself as the forType parameter of OverrideMetadata."
And the wording from the link you posted to CA1810 about when to suppress warnings:
When to Suppress Warnings
CA1810
It is safe to suppress a warning from this rule if performance is not a concern; or if global state changes that are caused by static initialization are expensive or must be guaranteed to occur before a static method of the type is called or an instance of the type is created.
So, your current implementation and suppression of the warning is probably the correct route.


text:
Q: SimpleXML works on emulator, not on Android device I'm using Simple 2.6.1 on an Android project for serialize some complex xml files. I use Eclipse and followed the procedure described on the project site (Simple XML in Android 1.5 and Up):
1) created the "libs" folder on the project root
2) put simple-xml-2.6.1.jar in the "libs" folder
3) added the jar to the build path
4) selected for export on the build path
All works fine when I run the application on the android emulator. But when I install the application on the device I get a crash at the time of serialization.
What's wrong?
P.S. I'm developing with android api level 8 (android 2.2)
Here's logcat:
I/WindowManager( 3002):   CREATE SURFACE Surface(name=Please wait..., identity=2186, mNativeSurface=0) IN SESSION android.view.SurfaceSession@40966108: pid=13036 format=-2 flags=0x0 / Window{40b8a978 Please wait... paused=false}

I/WindowManager( 3002):   CREATE SURFACE Surface(name=data5.android/data5.android.activity.CompileForm, identity=2187, mNativeSurface=0) IN SESSION android.view.SurfaceSession@40966108: pid=13036 format=-1 flags=0x0 / Window{40ce66e8 data5.android/data5.android.activity.CompileForm paused=false}

I/dalvikvm(13036): Could not find method javax.xml.stream.XMLInputFactory.newInstance, referenced from method org.simpleframework.xml.stream.StreamProvider.<init>

W/dalvikvm(13036): VFY: unable to resolve static method 1532: Ljavax/xml/stream/XMLInputFactory;.newInstance ()Ljavax/xml/stream/XMLInputFactory;

D/dalvikvm(13036): VFY: replacing opcode 0x71 at 0x0003

D/dalvikvm(13036): VFY: dead code 0x0006-0009 in Lorg/simpleframework/xml/stream/StreamProvider;.<init> ()V

D/dalvikvm(13036): GC_CONCURRENT freed 120K, 50% free 2855K/5639K, external 857K/1168K, paused 4ms+4ms

W/dalvikvm(13036): VFY: unable to find class referenced in signature (Ljavax/xml/stream/XMLEventReader;)

W/dalvikvm(13036): VFY: unable to find class referenced in signature (Ljavax/xml/stream/XMLEventReader;)

I/dalvikvm(13036): Could not find method javax.xml.stream.XMLInputFactory.createXMLEventReader, referenced from method org.simpleframework.xml.stream.StreamProvider.provide

W/dalvikvm(13036): VFY: unable to resolve virtual method 1530: Ljavax/xml/stream/XMLInputFactory;.createXMLEventReader (Ljava/io/InputStream;)Ljavax/xml/stream/XMLEventReader;

D/dalvikvm(13036): VFY: replacing opcode 0x6e at 0x0002

D/dalvikvm(13036): VFY: dead code 0x0005-000a in Lorg/simpleframework/xml/stream/StreamProvider;.provide (Ljava/io/InputStream;)Lorg/simpleframework/xml/stream/EventReader;

I/dalvikvm(13036): Could not find method javax.xml.stream.XMLInputFactory.createXMLEventReader, referenced from method org.simpleframework.xml.stream.StreamProvider.provide

W/dalvikvm(13036): VFY: unable to resolve virtual method 1531: Ljavax/xml/stream/XMLInputFactory;.createXMLEventReader (Ljava/io/Reader;)Ljavax/xml/stream/XMLEventReader;

D/dalvikvm(13036): VFY: replacing opcode 0x6e at 0x0002

D/dalvikvm(13036): VFY: dead code 0x0005-000a in Lorg/simpleframework/xml/stream/StreamProvider;.provide (Ljava/io/Reader;)Lorg/simpleframework/xml/stream/EventReader;

D/dalvikvm(13036): GC_CONCURRENT freed 453K, 52% free 2890K/5959K, external 834K/1168K, paused 1ms+2ms

I/ActivityManager( 3002): Displayed data5.android/.activity.CompileForm: +409ms

W/WindowManager( 3002): Window Window{40ada338 data5.android/data5.android.activity.StartForm paused=false} destroyed surface Surface(name=data5.android/data5.android.activity.StartForm, identity=-1, mNativeSurface=0), session Session{40cbdc28 uid 10226}

W/SurfaceFlinger( 3002): data5.android/data5.android.activity.StartForm[2184] is not removed from mLayerMap

D/dalvikvm(13036): GC_CONCURRENT freed 512K, 52% free 2907K/6023K, external 834K/1168K, paused 1ms+3ms

D/dalvikvm(13036): GC_CONCURRENT freed 509K, 52% free 2909K/6023K, external 834K/1168K, paused 2ms+2ms

D/PowerManagerService( 3002): onSensorChanged: light value: 1000

D/dalvikvm(13036): GC_CONCURRENT freed 553K, 53% free 2917K/6087K, external 834K/1168K, paused 1ms+2ms

D/dalvikvm(13036): GC_CONCURRENT freed 461K, 52% free 2954K/6087K, external 834K/1168K, paused 2ms+2ms

D/dalvikvm(13036): GC_CONCURRENT freed 449K, 52% free 2968K/6087K, external 834K/1168K, paused 2ms+2ms

D/dalvikvm(13036): GC_CONCURRENT freed 514K, 52% free 2957K/6087K, external 834K/1168K, paused 1ms+2ms

D/dalvikvm(13036): GC_CONCURRENT freed 502K, 52% free 2967K/6087K, external 834K/1168K, paused 2ms+2ms

D/dalvikvm(13036): GC_CONCURRENT freed 506K, 52% free 2972K/6087K, external 834K/1168K, paused 1ms+2ms

D/dalvikvm(13036): GC_CONCURRENT freed 574K, 52% free 2972K/6151K, external 834K/1168K, paused 2ms+2ms

E/lights  ( 3002): write_int: path /sys/devices/virtual/misc/melfas_touchkey/brightness, value 2

W/PowerManagerService( 3002): Timer 0x7->0x3|0x0

I/PowerManagerService( 3002): Ulight 7->3|0

D/PowerManagerService( 3002): setLightBrightness : mButtonLight : 0

D/dalvikvm(13036): GC_CONCURRENT freed 489K, 52% free 2995K/6151K, external 834K/1168K, paused 1ms+2ms

D/dalvikvm(13036): GC_CONCURRENT freed 520K, 52% free 2986K/6151K, external 834K/1168K, paused 2ms+2ms

D/dalvikvm(13036): GC_CONCURRENT freed 508K, 52% free 2990K/6151K, external 834K/1168K, paused 2ms+2ms

D/dalvikvm(13036): GC_CONCURRENT freed 512K, 52% free 2990K/6151K, external 834K/1168K, paused 2ms+2ms

D/dalvikvm(13036): GC_CONCURRENT freed 510K, 52% free 2992K/6151K, external 834K/1168K, paused 1ms+2ms

W/dalvikvm(13036): threadid=12: thread exiting with uncaught exception (group=0x4001e578)

A: Change java compiler version into higher

redpajama_set_name: RedPajamaStackExchange


text:
Q: can't connect to DB codeIgniter I'm trying to learn CodeIgniter by myself. but when I followed the specific instruction from this tutorial
http://www.codeigniter.com/user_guide/tutorial/news_section.html
this is my DB config
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'test',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => TRUE,
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

I get the following error:
A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_Loader::$db

Filename: pages/about.php

Line Number: 9

Backtrace:

File: /Applications/MAMP/htdocs/CodeIgniter/application/views/pages/about.php
Line: 9
Function: _error_handler

File: /Applications/MAMP/htdocs/CodeIgniter/application/controllers/Pages.php
Line: 18
Function: view

File: /Applications/MAMP/htdocs/CodeIgniter/index.php
Line: 292
Function: require_once

Fatal error: Call to a member function query() on null in /Applications/MAMP/htdocs/CodeIgniter/application/views/pages/about.php on line 9
A PHP Error was encountered

Severity: Error

Message: Call to a member function query() on null

Filename: pages/about.php

Line Number: 9

Backtrace:

A: I am thinking it is because you did not autoload the database library.
Path: application/config/autoload.php
$autoload['libraries'] = array('database');

As why Message: Undefined property: CI_Loader::$db shown.

A: you can try loading your model in controller or view using, recommendation is to load in controller...
$this->load->model('News_model','News',true);
and then try to insert, update or delete using:
$this->News->insert_function($param1,$param2);
class News_model extends CI_Model {

    public function insert_function($param1,$param2)
    {
            $this->db->query("insert into table ('col1','col2') values ('$param1','$param2')");
            //other codes here....
    }
}

hope this help..


text:
Q: Prove that the space P is a Hilbert Space. Prove that the space P of all entire functions of the form
$$f(z)=\frac{1}{2\pi}\int_{-\pi}^{\pi}\varphi(t) e^{-izt} dt,$$
is a Hilbert Space, where $\varphi\in L^2[-\pi,\pi]$. The inner product of two functions f and g in P is defined to
$$(f,g)=\int_{-\infty}^{\infty}f(t) g^*(t) dt$$
Any suggestions please?
Thanks.

A: Note that at first your definition is only suitable for $\phi\in L^1(\mathbb T) \cap L^2(\mathbb T)$, but can be continuously extended to $\phi\in L^2(\mathbb T)$.
The Operator taking $\phi$ to $f$ is precisely the fourier transform $\mathcal F$. It is a fundamental result of complex analysis that $\mathcal F: L^2(\mathbb T) \to L^2(\mathbb T)$ is an isometric isomorphism. All you need though is that it is an isomorphism, since this guarantees that $P = L^2(\mathbb T)$, wich is a hilbert space.


text:
Q: Linux Mint panel management Is there a primer on Linux Mint panel management? Problems: The panel does not resize dynamically (like in Windows) - If I add too many apps the panel just overflows off the end and some apps are not visible. Is there a way to expand the panel to 2 rows? I have 2 panels - how do I choose the panel I want to add the app to?

A: Manual on the administration of the linux mint panel I have not found.
In case of having many applications in the panel it is recommended to have more than one panel. You can create a second panel, right click, properties, and set orientation to bottom, the new panel will be placed below the main panel, and you will have much more space to organize your applications. To place an application in the new panel, simply left click on the application you want to add, add to panel, the application will be added to the main panel, then left click on the application icon in the panel, move, and move it with the mouse to the bottom panel, then you can drop it where you want on the panel.
I also recommend that in case of opening many applications, use the work areas so as not to overcrowd the panel.


text:
Q: Custom translation of Month names How do I customize the translation of the Month name strings in WordPress?
example
"January" be "Jan11" in all of website

A: Add the following to your existing functions.php file:
function ra_change_translate_text( $translated_text ) {
    if ( $translated_text == 'January' ) {
        $translated_text = 'Jan11';
    }
    return $translated_text;
}
add_filter( 'gettext', 'ra_change_translate_text', 20 );

If you want to change multiple strings, use this function instead:
function ra_change_translate_text_multiple( $translated ) {
    $text = array(
        'January' => 'Jan11',
        'February' => 'Feb22',
        'March' => 'Mar33',
    );
    $translated = str_ireplace(  array_keys($text),  $text,  $translated );
    return $translated;
}
add_filter( 'gettext', 'ra_change_translate_text_multiple', 20 );

You can add as many strings as you want, for example:
'April' => 'Apr44',

And the new translation can also be in a foreign language. Here's an example with Arabic:
'May' => 'مايو',

Last notes: If you use this function, keep in mind this will change the string translation everywhere in your WordPress site: front and back end. January will become Jan11 everywhere. Try it and see.
If that is acceptable to you then you're good to go. Otherwise, if you were looking to change the strings only on the front end (for your visitors to see), then consider making the changes to your theme or WordPress website language settings (which can be different from the admin language) - as suggested in some of the comments above.
Also, for reference, I learned about this function here: https://ronangelo.com/change-or-translate-text-on-a-wordpress-theme/. It is a very good post and if you want further information on translating text or themes in WordPress I recommend reading it.
Update to the original answer:
This function can only be used with words that are translatable - meaning, those wrapped in these functions ( __(), _e() )...
However, your comment and the website you linked to have given me a clearer idea of what you are trying to achieve. Simply change the locale of the PHP used to show that date to ar-LB.UTF-8. Lebanon is one of the Arabic locales that uses أذار for March, whereas other locales use مارس. The php locale will then render the date as you want it with no need for digging into translations and strings.
So, in your WordPress theme, use this code where you want to display the date instead of the code you are already using:
<?php
   setlocale(LC_ALL, 'ar_LB.UTF-8');
   echo strftime("%e %B %Y");
?>

In the source code of the page you linked to, the date is displayed within these lines of code:

Depending on how you organized your theme, that bit could be in header.php or maybe even a template part. Find it and you will see that the old PHP code to echo the date will be there between the  tags. Paste the snippet I gave you in its place.
Do keep in mind that if this theme is not your own unique one and you're not using a child theme you might lose that modification if the parent theme is updated.
I hope this helps. Please let me know if you need further assistance.

A: The right approach is as suggested by @Jos in a comment to your question , or you can write a function where you can replace the date string extracted from WordPress functions like get_the_date() for desired output.
Here is an example function that may help.
function my_custom_date($date){
    $new_date = getdate(strtotime($date));

    // Array that holds customized month's name
    $my_months=[
            'January'   => '1st Month',
            'February'  => '2nd Month',
            'March'     => '3rd Month',
            'April'     => '4th Month',
            'May'       => '5th Month',
            'June'      => '6th Month',
            'July'      => '7th Month',
            'August'    => '8th Month',
            'September' => '9th Month',
            'October'   => '10th Month',
            'November'  => '11th Month',
            'December'  => '12th Month',
        ];

        $new_date['month']= $my_months[$new_date['month']];

        return $new_date['month'].' '.$new_date['mday']. ', '. $new_date['year'];

    }

Then you can use this function to display dates in your site. For example,
echo my_custom_date( get_the_date() ); // Post publish date, within a loop

echo my_custom_date( "May 10, 2017" ); // Outputs: 5th Month 10, 2017

A: global $wp_locale;
echo $wp_locale->get_month('01'); // string between '01' and '12'

Doc:
https://developer.wordpress.org/reference/classes/wp_locale/get_month/


text:
Q: Error after updating from 0.8.3 to 0.9.2 I've updated from 0.8.3 to the latest version (0.9.2) and I've received this error. I have gone so far as to create a new meteor (0.9.2) project, and transfer all of my code from the old project, then freshly install all packages required.
/Users/nathaniel/Desktop/ESOS/.meteor/local/build/programs/server/packages/meteorhacks_kadira.js:2682
throw err;
      ^
ReferenceError: Router is not defined
    at app/common/router.js:1:36
    at app/common/router.js:177:3
    at /Users/nathaniel/Desktop/ESOS/.meteor/local/build/programs/server/boot.js:161:10
    at Array.forEach (native)
    at Function._.each._.forEach (/Users/nathaniel/.meteor/packages/meteor-tool/.1.0.31.sw6o3m++os.osx.x86_64+web.browser+web.cordova/meteor-tool-os.osx.x86_64/dev_bundle/lib/node_modules/underscore/underscore.js:79:11)
at /Users/nathaniel/Desktop/ESOS/.meteor/local/build/programs/server/boot.js:82:5
=> Exited with code: 7


text:
Q: Unpack nested tar files in s3 in streaming fashion I've got a large tar file in s3 (10s of GBs). It contains a number of tar.gz files.
I can loop through the contents of the large file with something like

    s3_client = boto3.client('s3')
    input = s3_client.get_object(Bucket=bucket, Key=key)

    with tarfile.open(fileobj=input['Body'],mode='r|') as tar:
        print(tar) -- tarinfo

However I can't seem to open the file contents from the inner tar.gz file.
I want to be able to do this in a streaming manner rather than load the whole file into memory.
I've tried doing things like
tar.extract_file(tar.next)

But I'm not sure how this file like object is then readable.
--- EDIT
I've got slightly further with the help of @larsks.

 with tarfile.open(fileobj=input_tar_file['Body'],mode='r|') as tar:
        for item in tar:
            m = tar.extractfile(item)
            if m is not None:
                with tarfile.open(fileobj=m, mode='r|gz') as gz:
                    for data in gz:
                        d = gz.extractfile(data)

However if I call .read() on d. It is empty. If I traverse through d.raw.fileobj.read() there is data. But when I write that out it's the data from all the text files in the nested tar.gz rather than one by one.

A: The return value of tar.extractfile is a "file-like object", just like input['Body']. That means you can simply pass that to tarfile.open. Here's a simple example that prints the contents of a nested archive:
import tarfile

with open('outside.tar', 'rb') as fd:
    with tarfile.open(fileobj=fd, mode='r') as outside:
        for item in outside:
            with outside.extractfile(item) as inside:
                with tarfile.open(fileobj=inside, mode='r') as inside_tar:
                    for item in inside_tar:
                        data = inside_tar.extractfile(item)
                        print('content:', data.read())

Here the "outside" file is an actual file, rather than something
coming from an S3 bucket; but I'm opening it first so that we're still
passing in fileobj when opening the outside archive.
The code iterates through the contents of the outside archive (for item in outside), and for each of these items:

*

*Open the file using outside.extractfile()

*Pass that as the argument to the fileobj parameter of
tarfile.open

*Extract each item inside the nested tarfile


text:
Q: Mysql NOT not working in this query using GROUP BY - why? Strange wording "Not not working!" I know, but strangely enough results are being returned where user_id does exist, though the query directs NOT (user_id = 1).
SELECT post_id, last_update
       FROM the_table
       WHERE last_update
       BETWEEN NOW( ) - INTERVAL 7 DAY
       AND NOW( ) AND NOT (user_id =1)
       GROUP BY post_id
       ORDER BY last_update DESC

Simply stated, we're trying to retrieve the latest results the user hasn't voted on - but results are turning up where the user has indeed voted despite the NOT (user_id = 1).
How is this possible? Is one one part of the query over-riding another? Perhaps the grouping?
Oddly enough, things work as predicted on Localhost, but not on the server! Its as though there is a tear in the sql-continuum and reality changes depending on environment. (And yes, user_id is 1 on both server and localhost)

A: SELECT x.*
  FROM the_table x
  JOIN
     ( SELECT post_id
            , user_id
            , MAX(last_update) max_last_update
         FROM the_table
        WHERE last_update BETWEEN NOW( ) - INTERVAL 7 DAY AND NOW( )
          AND user_id <> 1
        GROUP
           BY post_id
            , user_id
     ) y
    ON y.post_id = x.post_id
   AND y.user_id = x.user_id
   AND y.max_last_update = x.last_update
 ORDER
    BY x.last_update DESC;


text:
Q: HttpUrlConnection sometimes gives EOF exception I am using HttpUrlConnection and using POST method to get some data from web server. Sometimes, I get the response and at times I get EOFexception
These are the solutions are I have already tried :
1)  System.setProperty("http.keepAlive", "false");
2) if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
                    connection.setRequestProperty("Connection", "close");
                }

Below is my code from AsyncTask class;
CODE :
@Override
    protected JSONObject doInBackground(KeyValuePair... keyValuePairs) {

        JSONObject jsonResponse = new JSONObject();
        HttpURLConnection connection = null;
        // check if is Internet is available before making a network call
        if (isInternetAvailable()) {
            try {
                jsonResponse = new JSONObject();
                URL url = new URL(urlStr);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setUseCaches(false);
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("charset", "UTF-8");
                if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
                    connection.setRequestProperty("Connection", "close");
                }
                // setting post params
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < keyValuePairs.length; i++) {
                    builder.append(URLEncoder.encode(keyValuePairs[i].getKey(), "UTF-8") + "=" + URLEncoder.encode(keyValuePairs[i].getValue(), "UTF-8") + "&");
                    GeneralUtils.print("key : " + keyValuePairs[i].getKey() + ", value : " + keyValuePairs[i].getValue());
                }
                String postData = builder.toString();
                postData = postData.substring(0, postData.length() - 1);
                GeneralUtils.print("postData " + postData);
                byte[] postDataByteArr = postData.getBytes();
                connection.setFixedLengthStreamingMode(postDataByteArr.length);
                connection.setConnectTimeout(20000);
                DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
                dataOutputStream.writeBytes(postData);
                dataOutputStream.flush();
                dataOutputStream.close();
                GeneralUtils.print("respCode " + connection.getResponseCode());
                // if connection was not successful
                if (connection.getResponseCode() != 200) {
                    jsonResponse.put("status", "Failure");
                    jsonResponse.put("message", "Something went wrong. Please Try Again");

                } else {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line = null;
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    reader.close();
                    String response = sb.toString();
                    GeneralUtils.print("NetworkCall Server response " + response);
                    jsonResponse = new JSONObject(response);

                }
            } catch (JSONException e) {
                GeneralUtils.print("NetworkCall.JSONEx 162 " + e);
            } catch (MalformedURLException e) {
                GeneralUtils.print("NetworkCall.MalformedURLEx " + e);
            }  catch (IOException e) {
                try {
                    jsonResponse.put("status", "No Internet Connection");
                    jsonResponse.put("message", "Please check your Internet connection and try again");
                } catch (JSONException e1) {
                    GeneralUtils.print("NetworkCall.JSONEx " + e);
                }
            } finally {
                connection.disconnect();
            }
        } else {
            // if Internet is not available
            try {
                jsonResponse.put("status", "No Internet Connection");
                jsonResponse.put("message", "Please check your Internet connection and try again");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsonResponse;
    }

Many many thanks in advance!

A: As of now I am following a workaround posted here
 which essentially dictates trying to connect N number of times to bypass the EOF exception issue.
In my case, when I catch EOFException, I call the doInBackground again depending upon the reconnectCount;
 CODE :

catch (IOException e) {
                try {
                    if (reConnectCount <= 10) {
                        reConnectCount++;
                        jsonResponse = doInBackground(keyValuePairs);
                    } else {
                        jsonResponse.put("status", "No Internet Connection");
                        jsonResponse.put("message", "Please check your Internet connection and try again");
                    }
                } catch (JSONException e1) {
                    GeneralUtils.print("NetworkCall.JSONEx " + e);
                }
            }

Where jsonResponse essentially holds server response in JSON form. So, whenever doInBackground is successfully executed (i.e. does not get Caught and returns jsonResponse), we overwrite the calling doInBackground's jsonResponse object.


text:
Q: Como remover elementos repetidos de um array de objetos preservando o objeto que possuir propriedade id diferente de null Preciso remover os elementos que possuir o mesmo valor na propriedade screen_id mantendo o que tiver a propriedade id diferente de null.
Meu objeto de exemplo:
let userPermissions  = [
    {
        id: 1,
        description: Cadastro de usuários,
        screen_id: 1,
        allow_read: true,
        allow_create: true,
        allow_update: false,
        allow_delete: true
    },
    {
        id: null,
        description: "Cadastro de usuários",
        screen_id: 1,
        allow_read: false,
        allow_create: false,
        allow_update: false,
        allow_delete: false
    },
    {
        id: null,
        description: "Tela teste 3",
        screen_id: 5,
        allow_read: false,
        allow_create: false,
        allow_update: false,
        allow_delete: false
    },
]

Eu preciso do seguinte resultado:
[
    {
        "id": 1,
        "description": "Cadastro de usuários",
        "screen_id": 1,
        "allow_read": true,
        "allow_create": true,
        "allow_update": false,
        "allow_delete": true
    },
    {
        "id": null,
        "description": "Tela teste 3",
        "screen_id": 5,
        "allow_read": false,
        "allow_create": false,
        "allow_update": false,
        "allow_delete": false
    },
]

O que eu tentei:
userPermissions = userPermissions.reduce((arr, item) => {
  const removed = arr.filter(i => i['screen_id'] === item['screen_id'] && item['id'] !== null)
  return [...removed, item]
}, [])

Porém não está retornando o resultado conforme esperado.

A: Se você quiser uma solução um pouco mais performática, pode utilizar um laço for convencional:

const userPermissions = [
  { id: null, description: 'Tela teste 4', screen_id: 6 },
  { id: null, description: 'Cadastro de usuários', screen_id: 1 },
  { id: null, description: 'Tela teste 3', screen_id: 5 },
  { id: 8, description: 'Tela teste 4', screen_id: 6 },
  { id: 1, description: 'Cadastro de usuários', screen_id: 1 }
];

function removeDuplicates(list) {
  const listed = {};

  for (const item of list) {
    const { id, screen_id: screenId } = item;

    // Caso um item já esteja sido listado e seu ID não seja nulo, não será
    // adicionado à lista.
    if (screenId in listed && listed[screenId].id !== null) {
      continue;
    }

    // Caso ainda não esteja listado, ou já esteja listado, porém com um ID
    // nulo, será adicionado à lista.
    if (
      !(screenId in listed) ||
      (listed[screenId].id === null && id !== null) // Irá garantir que itens com ID não nulo sejam reinseridos.
    ) {
      listed[screenId] = item;
    }
  }

  return Object.values(listed);
}

console.log(removeDuplicates(userPermissions));

É um pouco verboso, mas como só tem um laço de iterações, creio que seja a melhor alternativa se você precisar de performance... Até dá para fazer com reduce, mas penso que ficaria meio nojento...

A: Apesar de "legal", nem sempre é mais fácil pensar de maneira "funcional", então antes de tentar fazer com reduce, por que não usar um loop simples?

let userPermissions  = [
    {
        id: 1,
        description: "Cadastro de usuários",
        screen_id: 1,
        allow_read: true,
        allow_create: true,
        allow_update: false,
        allow_delete: true
    },
    {
        id: null,
        description: "Cadastro de usuários",
        screen_id: 1,
        allow_read: false,
        allow_create: false,
        allow_update: false,
        allow_delete: false
    },
    {
        id: null,
        description: "Tela teste 3",
        screen_id: 5,
        allow_read: false,
        allow_create: false,
        allow_update: false,
        allow_delete: false
    }
];

let result = [];
let screenIdsJaVistos = {};
for (const u of userPermissions) {
    // se o screen_id ainda não foi verificado
    if (!screenIdsJaVistos[u.screen_id]) {
        // buscar todos que tem o mesmo screen_id
        let mesmoScreenId = userPermissions.filter(user => user.screen_id == u.screen_id);
        if (mesmoScreenId.length > 1) { // se tem mais de um, pega o que tem id não nulo
            result.push(mesmoScreenId.find(user => user.id !== null));
        } else { // senão, pega o próprio elemento
            result.push(u);
        }
        // esse screen_id já foi verificado, posso pular nas próximas iterações
        screenIdsJaVistos[u.screen_id] = true;
    }
}
console.log(result);

Claro que se tiver vários elementos com o mesmo screen_id, ele vai pegar o primeiro que não tem id nulo. Mas se precisar de outro critério de desempate, basta adicionar acima, dentro do if (mesmoScreenId.length > 1).
Na minha opinião fica um código bem mais claro do que usando reduce mas claro que há quem discorde, por isso é "opinião" - além disso, fica mais fácil adicionar novas condições, caso necessário.
O código pode até ficar maior do que se usasse reduce, mas o tamanho do código não deve ser um fim por si só. Um código mais claro e fácil de entender e manter é muito melhor que um código curto porém complicado (a menos que você e sua equipe se sintam confortáveis com reduce, claro).


text:
Q: How to convert column of text to CSV I have the following output from a command in Unix:
"10"
"30"
"u"
"hello"

And I want it in the following CSV format without the trailing comma:

"10","30","u","hello"

I tried tr '\n' ',' but that leaves a trailing comma.
Being new to Unix, I am not sure how to go about achieving what I'm trying. Any help?

A: You could just simply remove the trailing comma with sed.
# echo '"10"
"30"
"u"
"hello"' | tr '\n' ',' | sed s/',$'/\\n/g

"10","30","u","hello"


text:
Q: send data to JS file without using global variables I need to send data in a HTML page to a script file that is loaded in that page. The simplest way i can think of is to use a global variable which is defined in the page and accessed in the script file.
We all know global state is bad, so i started thinking about the options available for passing data from HTML page to script file without using global state. I cant find (or think of) any.
I am curious whether this is possible. Any ideas?

A: It really depends what you're doing. In general, I wouldn't advise this methodology, but it's something to consider depending on your circumstances. For the sake of this example, I'll assume you're using jQuery (if not, replace the document.ready with whatever you want to use for onDOMReadyStateChange monitoring).
In the HTML:
<script type='text/json-data' id='some_data_set'>
  { 'foo': 'bar', 'baz': 1 }
</script>

In the JavaScript:
$(function() {
  var myData = JSON.parse($('script#some_data_set').html());
  // YOUR CODE GOES HERE
});

A: Nope. All the javascript scope starts from a global level, therefore you must have at least one global reference to your data.
Let's say you wanted to store a list of products and events:
var myGlobalData = { "products":<products>, "events":<events> };

Where <products> and <events> are two different data blocks.

If you're paranoid on global objects, you can simply delete the reference point (thus it's contents) after you finished using it, as follows:
delete window.myGlobalData;

A: One option is to scope your data.  For example, in JS file you can define an object like:
   var processor = {
     function setData(o) { // do stuff
     }
   };

Then in your HTML you know that the data is scoped to the processor.  So you can do something like:
processor.setData({someData});


text:
Q: How to export SVG from a typescript custom package to React Native Project I have a custom package called "app-packages", and i want all of my .png and .svg stored in this package. I manage to export the .png files but i have problems exporting and using the .svg file.
I already installed
https://github.com/kristerkari/react-native-svg-transformer & https://github.com/react-native-svg/react-native-svg in my app-packages and react native app.
What i have tried:
I have src/Arrow.svg in the package, and i export it like this in src/index.tsx.
export { default as SvgPicture} from './Arrow.svg'

i already create a declaration.d.ts in src/
declare module "*.svg" {
    import React from 'react';
    import {
        SvgProps
    } from "react-native-svg";
    const content: React.FC<SvgProps> ;
    export default content;
}

here is my tsconfig.json
{
"compilerOptions": {
  "target": "ESNext",
  "module": "ESNext",
  "strict": true,
  "outDir": "build",
  "declaration": true,
  "jsx": "react",
  "importHelpers": true,
  "moduleResolution": "node",
  "experimentalDecorators": true,
  "esModuleInterop": true,
  "allowSyntheticDefaultImports": true,
  "noImplicitAny": false,
  "allowJs": false,
  "sourceMap": true,
  "lib": ["es6", "dom", "dom.iterable", "es2016", "es2017"],
  "forceConsistentCasingInFileNames": true,
  "resolveJsonModule": true,
  "isolatedModules": true,
  "noImplicitReturns": true,
  "noImplicitThis": true,
  "strictNullChecks": true,
  "suppressImplicitAnyIndexErrors": true,
  "noUnusedLocals": true,
  "noUnusedParameters": true,
  "noEmit": true
},
"include": ["src", "src/declaration.d.ts"],
"exclude": ["node_modules", "build"]

}
after all that done, i build the package and tried it in my app.
like this
import {SvgPicture} from 'app-packages';

and call it like this in render because i already installed react-native-svg-transformer
 <SvgPicture />

but the result is this
Invariant Violation: View config getter callback for component `../../../Arrow.svg` must be a function (received `undefined`).

if the SVG file is in my react native app, the step above will show the .svg. But it will fail if i move it to app-packages. Anybody have a solution?


text:
Q: How to implement lazy loading for multiple modules I need to implement lazy loading for my project which uses AngularJs, RequireJs, Grunt.This is a very large project and it is divided into multiple modules containing their separate controller, service and routing.js files. I tried my hands on OcLazyLoad but it works only if I maintain a single routing file for entire project.
But my manager says no for having a single routing file.
Is there any other lazy loader available I can try or any grunt plugin to merge all routing files to one on build time.
We follow this kind of structure in the project:
App

|--js
    |-
-app.js
    |--bootstrap.js
    |--main.js

|--modules
    |--login
        |--controller.js
        |--routing.js
        |--service.js
    |--agent
        |--orders
            |--controller.js
            |--routing.js
            |--service.js
        |--controller.js
        |--routing.js
        |--service.js
    |--admin
        |--controller.js
        |--routing.js
        |--service.js


text:
Q: Why component from Xpages Extension lib doesn't support converter My xpage is using xe:djDateTextBox (bellow):
<xe:djDateTextBox id="djDateCreatedFrom"
                    value="#{compositeData.archiveDocument.entryDateFrom.time}"
                    title="#{javascript:languageGetLabelName('_arch_from_date')}"
                    style="width:49%;" showReadonlyAsDisabled="true"
                    readOnly="#{javascript:!compositeData.editMode}">
                    <xe:this.converter>
                        <xp:convertDateTime>
                            <xp:this.pattern><![CDATA[${javascript:"dd.MM.yyyy"}]]></xp:this.pattern>
                        </xp:convertDateTime>
                    </xe:this.converter>

public class ArchiveDocument extends Param{

/**
 *
 */
private Calendar entryDateFrom;

public ArchiveDocument() {
    super();
    entryDateFrom = Calendar.getInstance();}
public Calendar getEntryDateFrom() {
    return entryDate;
}

public void setEntryDateFrom(Calendar entryDate) {
    this.entryDate = entryDate;
}

.....
}
If I set standard date time picker instead of  xe:djDateTextBox everything works fine: (bellow)
<xp:inputText id="txtDateCreatedFrom"
                    style="width:75.0%"
                    value="#{compositeData.archiveDocument.entryDateFrom.time}"
                    readonly="#{javascript:!compositeData.visible}"
                    dojoType="dijit.form.DateTextBox">
                    <xp:this.converter>
                        <xp:convertDateTime>
                            <xp:this.pattern><![CDATA[${javascript:"dd.MM.yyyy"}]]></xp:this.pattern>
                        </xp:convertDateTime>
                    </xp:this.converter>
                    <xp:dateTimeHelper></xp:dateTimeHelper>
                </xp:inputText>

Settings for IE, Domino server, pattern in xpage:

My IE settings for languages: English (United STates) [en-US]

Pattern:"dd.MM.yyyy"

Domino server 9.0.1 FP2
Web User Preferences: Default regional locale:  Server locale

My page doesn't show date time like 27.11.2014 as it should.
It show date time like 11/27/2014.
If I'm using standard date time picker everything works fine.
Thanks in advance!

A: Is your page displaying a pre-saved value or is it just defaulting to the current date? If the former, you may be misunderstanding what the converter does.
The job of the converter is to convert the server-side date/time value to a text string and vice versa. The converter code all runs server-side, so if there's not a pre-existing value, it will just pass a blank string. So the converter is not the place to look to modify the format the browser offers, Dojo will be defining the value.
The Dojo locale settings will be what is being used for the date time format being used for a default value or entered on the browser. I'm not sure if this will help explain dates and localization http://xomino.com/2014/01/14/dealing-with-dates-and-localization-in-xpages/


text:
Q: Codeigniter 4 embedding CSS and JS file I am new to Codeigniter and I am trying to use Codeigniter 4. What do I have to do in order for me to load my CSS and JS file? I have been spending for the past 7 hours trying to figure out what's wrong but still can't find any solution.
This is my folder structure:
-app
-public
--css
---styles.css
--js
---mainjs.js
--img
-system
-writable

The file is there and I even tried to put the exact path instead of using base_url but I keep getting either file not found error or internal server error message. The tutorial or guide I see on the net, all I saw was pointing the path to the file location and it works for them. There are limited answers posted here too which is based on Codeigniter 4.
.env file
 app.baseURL = 'http://localhost/ci/'

app/Controllers/Pages.php

<?php namespace App\Controllers;

class Pages extends BaseController
{
    public function index()
    {
        return view('index');
    }

    public function view($page)
    {
        if ( ! is_file(APPPATH.'/Views/pages/'.$page.'.php'))
        {
            // Whoops, we don't have a page for that!
            throw new \CodeIgniter\Exceptions\PageNotFoundException($page);
        }

        $data['title'] = ucfirst($page); // Capitalize the first letter

        echo view('templates/header', $data);
        echo view('pages/'.$page, $data);
        echo view('templates/footer', $data);
    }

    //--------------------------------------------------------------------

}

app/Views/templates/header.php

<!DOCTYPE html>
<html lang="en-US" class="no-js">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="<?php echo base_url('public/css/style.css'); ?>" type="text/css" media="all" />
</head>

Hope there's someone here who can help me out on this issue. Thanks in advance.

A: because in your .env app.baseURL = 'http://localhost/ci' if u echo base_url() it will return http://localhost/ci as well so it assume that your public folder have CI folder inside that

*

*if you still want to use your current folder structure

    <link rel="stylesheet" href="http://localhost/css/style.css" type="text/css" media="all" />

*

*in your public folder structur there is no ci/assets folder so just put your style.css folder under ci/assets/css

<link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>" type="text/css" media="all" />


text:
Q: How to use embeddings in neural networks? Time2Vec suggests a learned embedding of time as a variable for machine learning, but the paper only seems to explore using time as a single input in benchmark tasks.
If I were to use a n-dimensional vector representation of time, generated by an encoder-decoder stack, along with 2 other scalar variables, for example, would these just be concatenated into a (n+2)-dimensional input layer to a neural network or other algorithm?
Is there any danger of the time variables "outweighing" the others by outnumbering them? How is this approached?


text:
Q: Send DropDown value to API Flutter I have some Data coming from my API and is displayed in a DropDownButton. My problem is I can't send back the selected value to the API when the submit button is pressed.

Here I do the register HTTP call

  Future<Map> register(String name, String email, String budget,
  String currency, String password, String confirmPassword) async {
  final url = "$api/register";

  var body = {
  'name': name,
  'email': email,
  'budget': budget,
  'currency': currency,
  'password': password,
  'confirmPassword': confirmPassword,
  };

  Map<String, dynamic> result = {
  "success": false,
  "message": 'Unknown error.'
  };

  final response = await dio.post(
  url,
  data: body,
  );

  if (response.statusCode == 201) {
  notifyListeners();
  result['success'] = true;

  return result;
 }
 Map apiResponse = response.data;
 _status = Status.Authenticated;

  _token = apiResponse['token'];
  print(_token);
  await storeUserData(apiResponse);

  if (response.statusCode == 422) {
  if (apiResponse['errors'].containsKey('email')) {
    result['message'] = apiResponse['errors']['email'][0];
    return result;
  }

  if (apiResponse['errors'].containsKey('password')) {
    result['message'] = apiResponse['errors']['password'][0];
    return result;
  }

  return result;
 }

 return result;
 }

This is the post function that I'm calling in the UI

    Future<void> submit() async {
  final form = _formKey.currentState;
  if (form.validate()) {
    response = await Provider.of<AuthProvider>(context, listen: false)
        .register(name, email, budget, currency, password, confirmPassword);
    if (response['success']) {
      print("Signed Up Successfuly");
      showAlertDialogWithActions(
          "Signed Up Successfuly, Please Sign in to continue", context);
    } else {
      setState(() {
        message = response['message'];
      });
    }
  }
  }

DropDown Button
     DropDownInput(
                      validator: (value) {
                        currency = selectedValue;
                        return Validate.requiredField(
                            value, 'Budget is required.');
                      },
                      width: 150,
                      hint: "Currency",
                      items: currencyItemList.map((item) {
                        return DropdownMenuItem(
                            child: Text(item['currencyName']),
                            value: item['_id'].toString());
                      }).toList(),
                      onChange: (newVal) {
                        setState(() {
                          selectedValue = newVal;
                        });
                      },
                      value: selectedValue,
                    )

I want to send the SelectedValue to API using the validator I'm using above


text:
Q: Getting volley response is null on first call This my class for network calls. Here executing a method networkCallByVolley then saving the information on shared preferences.
 public class NetworkCall extends Activity {
        Context context;
        String res = "something";

        SharedPreferences userDetails;

         ArrayList<String> type = new ArrayList<String>();
         ArrayList<String> value = new ArrayList<String>();

    public NetworkCall(Context context){
        this.context = context;

    }

        public void networkCallByVolley(final ArrayList<String> type, final ArrayList<String> value){

            this.type = type;
            this.value = value;
            Log.i("type", type.toString());
            Log.i("value", value.toString());

            RequestQueue queue = Volley.newRequestQueue(context);
            StringRequest myReq = new StringRequest(Method.POST,
                    "http://My URL",
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {

                            Log.i("rrrrr", response);

                            res = response;

                             userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
                            Editor edit = userDetails.edit();
                            edit.clear();
                            edit.putString("response", response);

                            edit.commit();

                            //Log.i("rrrrr", response);

                        }
                    },
                    new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    }) {
                protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                  //for(int i = 0; i<= params1.size(); i++)

                    for(int i =0 ; i< type.size(); i++){
                    params.put(type.get(i), value.get(i));
                    //params.put("password", "aaaaaa");
                   Log.i("typpppp", type.get(i));
                    }

                    return params;
                };
            };

            queue.add(myReq);

           }
         public String getCharlie(){
             userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
             return userDetails.getString("response", "no value found");
         }
        public void clearCharlie(){
            SharedPreferences.Editor edit = userDetails.edit();
            edit.clear();
            edit.commit();
        }

        }

when i am trying to use this class from login activity i am getting  message for the below log  "pref response" is "no value found". if run it again i am getting proper response which i am expecting. I don't know how to fix this bug. any help is appreciated.
this is my main activity
public class Login extends Activity {
    Button signup,submit;
    EditText email,password;
protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    setContentView(R.layout.login);

final  NetworkCall net = new NetworkCall(getApplicationContext());

    final ArrayList<String> type = new ArrayList<String>();

    final ArrayList<String> value = new ArrayList<String>();

    submit = (Button) findViewById(R.id.submit);
    email = (EditText) findViewById(R.id.edittext_email);
    password = (EditText) findViewById(R.id.edittext_pwd);

    type.add("user_email");
    type.add("user_password");

    value.add(email.getText().toString().trim());
    value.add(password.getText().toString().trim());

    submit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
         net.networkCallByVolley(type, value);
         String response = net.getCharlie();

    Log.i("pref resonse", response);

        }
    });

}
}

A: You need to use ASYNC task or handler.
What you are doing is calling getCharlie() method right after you made the call net.networkCallByVolley(type, value); It takes some time to get response from the sever after which only it will write the response to the shared prefrences. You are getting no result found because at that time there is no response. Respone is being calculated on some another parallel thread. As soon as that thread gets the response it show that to you but until then you will be having null. So wait for the thread to get response using ASYNC task.
@Override
        public void onClick(View v) {
         net.networkCallByVolley(type, value);
         String response = net.getCharlie();
         while(response.equalsIgnorecase("no result found")){}
         Log.i("pref resonse", response);

        }

A: Actually you need to wait until getting response from Volley.
You can use a BroadcastReceiver in your Login Activity
and send a broadcast from NetworkCall Activity after you get a response from the server, and when you receive a broadcast do what you want to do e.g checking SharedPreferences.
Alternative way you can use is Observer Pattern to get notice when you get response from server.


text:
Q: GAMS - logical equations & binary variables I got another question on logical equations or rather binary variables. This is again a beginner question.
So, right now I'm trying to understand how to set the value of binary variables with conditions.
Consider the binary variable x and variable m.
If I would write the code in other language syntax, what I'm trying to do would look like:
if m > 0
x = True
else
x = False
end
So, I'm trying to set the value of x to 1, when the variable m is greater than zero.
How do I model this in GAMS? Do I need to use logical equations for it?
I can't find a solution for this.
Thanks again for your help.
Cheers
Max

A: Maybe you can add the following constraints to the model
 Eq..    m =g= (x-1)*M

where M is a very large positive number representing a lower bound on the variable m.

A: I got a helpful answer from another forum:
https://forum.gamsworld.org/viewtopic.php?f=2&t=10286
This should be the solution to the problem.


text:
Q: How to change bars colors with scale_fill_manual() in R? I want my bars to correspond to a legend and to have them colored with my own color, not the default one.
# library
library(ggplot2)

# create a dataset
specie <- c(rep("IFNg_WNH", 2) ,
            rep("IFNg_AA", 2),
            rep("IL1b_WNH", 2),
            rep("IL1b_AA", 2),
            rep("IL6_WNH", 2),
            rep("IL6_AA", 2)
)

condition <- rep(c("down", "up"), 6)

value <- c(452,216,
           348,327,
           207,61,
           75,53,
           177,191,
           379,318)
data <- data.frame(specie,condition,value)

data

# Grouped
p <- ggplot(data, aes(fill=condition, y=value, x=specie)) +
  geom_bar(position="dodge", stat="identity")

z <- p+labs(y = "Number of genes", x = "Cytokines")+
  theme_classic()+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.line=element_line(size=1))+
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))+
  scale_fill_discrete(labels=c('up', 'down'))

z

Once I add
z + scale_fill_manual(values=c('#eb4034','#0a0a0a'))

The color is changing but the legend reverts to the wrong one. What is happening?

A: Adding type to scale_fill_discrete

type: One of the following:
• A character vector of color codes.
• A list of character vectors of color codes.
• A function that returns a discrete colour/fill scale

ggplot(data, aes(fill=condition, y=value, x=specie)) +
  geom_bar(position="dodge", stat="identity") +
  labs(y = "Number of genes", x = "Cytokines") +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA)) +
  scale_fill_discrete(labels=c('up', 'down'), type=c('#eb4034','#0a0a0a'))

A: There are a couple issues here. First, scale_fill_manual() essentially "overwrites" scale_fill_discrete(). Instead, use just one scale_fill_*() call including all relevant arguments:
library(ggplot2)

p +
  labs(y = "Number of genes", x = "Cytokines")+
  theme_classic()+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.line=element_line(size=1))+
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))+
  scale_fill_manual(labels = c('up', 'down'), values=c('#eb4034', '#0a0a0a'))

However - currently, the labels argument is in effect recoding your data, so that "up" values are labeled "down" and vice versa, which I assume isn't what you want. My best guess is you're actually trying to change the order the labels appear in the legend. If so, you can change the factor levels of condition to the order you want:
data$condition <- factor(data$condition, c("up", "down"))

p <- ggplot(data, aes(fill=condition, y=value, x=specie)) +
  geom_bar(position="dodge", stat="identity")

p +
  labs(y = "Number of genes", x = "Cytokines")+
  theme_classic()+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.line=element_line(size=1))+
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))+
  scale_fill_manual(values=c('#eb4034', '#0a0a0a'))


text:
Q: How to measure moped insert runtime in a ruby mongoid app? I'm currently writing a moped log parser in order to monitor moped queries runtime.
It's work great for QUERY command using the runtime parameter, but INSERT and UPDATE have no runtime parameter. All INSERT and UPDATE are followed by a getLastError COMMAND which contains a runtime.
Here are some samples of moped logs:
QUERY with runtime
MOPED: 127.0.0.1:27017 QUERY        database=X collection=X selector=X
flags=[] limit=-1 skip=0 batch_size=nil fields=nil runtime: 0.6950ms

INSERT without runtime but with COMMAND
MOPED: 127.0.0.1:27017 INSERT       database=X collection=X documents=X flags=[]
                       COMMAND      database=X command={:getlasterror=>1, :w=>1}
runtime: 0.4750ms

I'm pretty sure that COMMAND runtime is for the getlasterror call and not for my INSERT one.
So is there a way to get this runtime info for an INSERT query?

A: Instead of using a log parser, I use something like this and it works great:
ActiveSupport::Notifications.subscribe('query.moped') do |name, start, finish, id, payload|
    runtime = (finish - start)*1000
    moped_ops = payload[:ops]
    moped_ops.each do |op|
      unless op.collection == '$cmd'
        query = op.class.name.split('::').last.downcase
        query = op.selector.first[0].to_s.gsub(/\$/, '') if query == 'command'
        DO SOMETHING WITH #{op.database}.#{op.collection}.#{query}
      end
    end

  end


text:
Q: Create a XML from SQL Server I need some help. I'm trying to create an XML with this query:
WITH XMLNAMESPACES ('Envelope' AS soapenv)
    SELECT *
    FROM CrearViaje4
    JOIN transporte ON CrearViaje4.Cod_viaje = transporte.Cod_viaje
    JOIN depositoSalida ON transporte.Cod_viaje = depositoSalida.cod_viaje
    FOR XML AUTO, ROOT('soapenv:Body'), ELEMENTS

and I get this result:
  <soapenv:Body xmlns:soapenv="Envelope">
      <CrearViaje4>
        <cod_viaje>A02VAIFHDXH</cod_viaje>
        <Empresa>Tradelog</Empresa>
        <transporte>
          <cod_viaje>A02VAIFHDXH</cod_viaje>
          <depositoSalida>
            <cod_viaje>A02VAIFHDXH</cod_viaje>
          </depositoSalida>
        </transporte>
      </CrearViaje4>
    </soapenv:Body>

Why is transporte is under the table depositoSalida?
I am trying to get this result, what can I do?
<soapenv:Body xmlns:soapenv="Envelope">
  <CrearViaje4>
    <cod_viaje>A02VAIFHDXH</cod_viaje>
    <Empresa>Tradelog</Empresa>
        <transporte>
           <cod_viaje>A02VAIFHDXH</cod_viaje>
        </transporte>
      <depositoSalida>
        <cod_viaje>A02VAIFHDXH</cod_viaje>
      </depositoSalida>
   </CrearViaje4>
</soapenv:Body>

A: you could try joining depositoSalida on CrearViaje4.Cod_viaje = depositoSalida.cod_viaje
with xmlnamespaces ('Envelope' as soapenv)
select  *
from    CrearViaje4
join    transporte on CrearViaje4.Cod_viaje = transporte.Cod_viaje
join    depositoSalida on CrearViaje4.Cod_viaje = depositoSalida.cod_viaje
for xml auto, root('soapenv:Body'), elements

or using sub queries to get your extra data
with xmlnamespaces ('Envelope' as soapenv)
select  *
        , (   select    *
              from      transporte
              where     CrearViaje4.Cod_viaje = transporte.Cod_viaje
              for xml path(''), type ) as transporte
        , (   select    *
              from      depositoSalida
              where     CrearViaje4.Cod_viaje = depositoSalida.Cod_viaje
              for xml path(''), type ) as depositoSalida
from    CrearViaje4
for xml auto, root('soapenv:Body'), elements


text:
Q: Unable to stop and rm docker containers from Scala script I am trying to execute the following command from within an ammonite Scala script:
 Process("docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)")

I always get the following output:
unknown shorthand flag: 'a' in -a
See 'docker stop --help'.

I've tried so many different variations without any luck, however it works fine from the console. Some help would be much appreciated.

A: If you pass a string to Process then scala will just split it on spaces, and it won't be clever enough to interpret things like bash's command substitution $().
The easiest workaround would be to use a Seq of commands, and wrap your stuff in a call to bash:
Process(Seq("bash", "-c", "docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)"))


text: Q: Made an own DNS server, how to add photos to the host? I made a DNS server using simple DNS, added a host (ip linked to domain). The site does open on chrome (I disconnected from my default DNS) but without photos. How do I fix that?


text:
Q: MSB4044: The "KillProcess" task was not given a value for the required parameter "ImagePath" Long story short, I was able to build a bitbucket .NET/MVC/Angular project successfully on windows 2019 azure hosted agent, but I am unable to make it build successfully on ubuntu agent. The reason I want to build it on ubuntu is because I noticed the build time is way faster than that of the windows agent, which makes sense considering the platforms.
I am facing this error:
Copying file from "/home/vsts/work/1/s/Bobby.ProjectA/obj/Debug/Bobby.ProjectA.pdb" to "/home/vsts/work/1/s/Bobby.ProjectA/bin/Bobby.ProjectA.pdb".
CopyRoslynCompilerFilesToOutputDirectory:
  Creating directory "/bin/roslyn".
  Creating directory "/bin/roslyn".
  Creating directory "/bin/roslyn".
  Creating directory "/bin/roslyn".

/home/vsts/work/1/s/packages/Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.8/build/net45/Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props(17,5):
warning MSB3021: Unable to copy file "/home/vsts/work/1/s/packages/Microsoft.Net.Compilers.2.4.0/build/../tools/csc.exe" to "/bin/roslyn/csc.exe". Access to the path '/bin/roslyn' is denied. [/home/vsts/work/1/s/Bobby.ProjectA/Bobby.ProjectA.csproj]
"/home/vsts/work/1/s/Bobby.ProjectA/Bobby.ProjectA.csproj" (default target) (1) ->
(KillVBCSCompilerAndRetryCopy target) ->
/home/vsts/work/1/s/packages/Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.8/build/net45/Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props(23,5):
error MSB4044: The "KillProcess" task was not given a value for the required parameter "ImagePath". [/home/vsts/work/1/s/Bobby.ProjectA/Bobby.ProjectA.csproj]

According to this post, the issue is because the VBCSCompiler is locking the src.
So i have exhausted all of these solutions here to kill the VBCCompiler, but none of them worked. I also can't restart the ubuntu agent during a build due to CI limitation, and killall VBCSCompiler bash script before msbuild task resulted in this error: VBCSCompiler: no process found
So now i am sure that this has to do with the last error message on the log which is error MSB4044: The "KillProcess" task was not given a value for the required parameter "ImagePath".
According to this post here, I would need to specify an image path but since this is running on a build agent, I can't do that since i can't simply click on the error message like the person did to open the Microsoft.codeDom.Providers.DotNetCompilerPlatform.props file.
and i couldn't locate this file in the project, so i think it gets created during the build...
and even if am able to specify an image path, what would be the path? /bin/roslyn?

A: It finally worked! I don't know why removing these lines resolved the VBCSCompiler issue, but by doing so, the msbuild completed successfully on Ubunutu 20 agent!!
Remove the following lines from the .csproj file:
<Import Project="..\packages\Microsoft.Net.Compilers.2.4.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.2.4.0\build\Microsoft.Net.Compilers.props')" />

<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.2.4.0\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.2.4.0\build\Microsoft.Net.Compilers.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.8\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.8\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />

To give some context to the answer, this post here indicated that converting from MSBuild-Integrated Package Restore to Automatic Package Restore (nuget restore task) implied that the Microsoft.Net.Compilers <Import> and <Error Condition> snippets are no longer relevant/needed in the .csproj file.
UPDATE:
When running this on windows agent, you will also need to remove the following line as well from the .csproj file
<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.8\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.8\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />

to resolve these warnings when building on windows agent:
Warning MSB3030: Could not copy the file "\pagefile.sys" because it was not found.
Warning MSB4181: The "Copy" task returned false but did not log an error.

A: I removed these from .csproj project file and cleared the bin and obj folder. Now it's working as expected.
  <Import Project="..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\build\net472\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.targets" Condition="Exists('..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\build\net472\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.targets')" />

and
  <Error Condition="!Exists('..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\build\net472\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\build\net472\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.targets'))" />


text:
Q: How to refactor a function with different struct pointers as parameters? Suppose I have this piece of code, with 2 structs and a big function that receives this 2 structs as parameters:
typedef struct
{
  int field_A;
  int field2_A;
} A;

typedef struct
{
  int field_B;
  int field2_B;
} B;

void function_need_refactor(A *a, B *b)
{
  for(i = 0; i < SIZE; i++)
  {
    do_something(a->field_A);
  }

  for(i = 0; i < SIZE; i++)
  {
    do_something(b->field2_B);
  }
}

How can I replace the both for loops to a single function? I thought about using void pointer and an identifier for each struct, but couldn't come up with an answer. Is there a clean way to refactor this or is it impossible?
void refactored_function(void* my_struct, char type_identifier)
{
  //code to identify the type
  for(i=0; i < SIZE; i++)
  {
    do_something((cast)my_struct->????);
  }
}

A: There are two modifications that come to mind here. First of all, both loops rely on the same counter and the counter is independent of the items in the loop body... Thus, logically, you should at least be able to do this:
typedef struct
{
  int field_A;
  int field2_A;
} A;

typedef struct
{
  int field_B;
  int field2_B;
} B;

void function_need_refactor(A *a, B *b)
{
  for(i = 0; i < SIZE; i++)
  {
    do_something(a->field_A);
    do_something(b->field2_B);
  }
}

But you may also be able to refactor do_something() to operate on both:
typedef struct
{
  int field_A;
  int field2_A;
} A;

typedef struct
{
  int field_B;
  int field2_B;
} B;

void function_need_refactor(A *a, B *b)
{
  for(i = 0; i < SIZE; i++)
  {
    do_something(a->field_A, b->field2_B);
  }
}

That way, you're only using one loop total, and the function is handling both fields on each loop iteration.


text:
Q: if can? does not hide links on show.html I have just installed cancan and I have run into a quick, small issue. I should be able to use if_can? to apply action to hide links. This is so only the information that was created by user can of course view the edit/delete links.
I haven't been able to find someone else who has had the same problem. If someone could take a look and help me out that would be greatly appreciated.
show.html:

    <% for photo in @gallery.photos %>

        <%= image_tag photo.image_url(:thumb).to_s %>

<%= photo.name %>

            <% if can? :update, @photo %>
            <%= link_to "edit", edit_photo_path(photo) %> |
            <% end %>
            <% if can? :remove, @photo %>
            <%= link_to "remove", photo, :confirm => 'Are you sure?', :method => :delete %>
            <% end %>

    <% end %>

  <%= link_to "Add a Photo", new_photo_path(:gallery_id => @gallery) %>
|
  <%= link_to "Remove Gallery", @gallery, :confirm => 'Are you sure?', :method => :delete %> |
  <%= link_to "View Galleries", galleries_path %>

ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    can :read, :all
  end
end

A: OK, each controller must be authorized.  The easiest way to do this is to start at photo's and make sure that it cannot be deleted.  You will need something like:
can :delete, Photo do |photo|
  question.try(:user) == user
end

in your ability.rb.  In your photo's controller you will need to put in either load_and_authorize_resource or authorize_resource.
Then in your view you want <%if can :remove, photo %> not <%if can :remove, @photo>.  It seems odd to me you are trying to use @photo when you have <for photo in @gallery.photos %>

A: i also has passed through this problem. solution is simple in Ability.rb class do something as follows
class Ability
  include CanCan::Ability

  def initialize(user)
  user ||= User.new # guest user (not logged in)
  if user.role == "admin"
    can :update, Photo, :user_id => user.id
  end
end

then in index.html.erb do something as follows
<% @photos.each do |photo| %>
 <%if can? :update, photo %>

 <%end%>
<%end%>

Note: in "<%if can? :update, photo %>" write "photo" instead of "Photo" or "@photo". because here photo is a veriable which will iterate through out the loop.


text:
Q: Citrus Framework - upload file via SFTP using Spring Integration As part of a Citrus test I'd like to push a CSV file to a server via SFTP. It seems this should be possible using Spring Integration. I've attempted using the code below:
citrus-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:citrus="http://www.citrusframework.org/schema/config"
       xmlns:citrus-test="http://www.citrusframework.org/schema/testcase"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:int-sftp="http://www.springframework.org/schema/integration/sftp"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/integration/sftp http://www.springframework.org/schema/integration/sftp/spring-integration-sftp.xsd
       http://www.citrusframework.org/schema/config http://www.citrusframework.org/schema/config/citrus-config.xsd
       http://www.citrusframework.org/schema/testcase http://www.citrusframework.org/schema/testcase/citrus-testcase.xsd
">

    <!-- Common settings -->
    <context:property-placeholder location="classpath:citrus.properties"/>

    <citrus:schema-repository id="schemaRepository"/>

    <!-- SFTP component -->
    <bean id="sftpSessionFactory" class="org.springframework.integration.file.remote.session.CachingSessionFactory">
        <constructor-arg ref="defaultSftpSessionFactory" />
    </bean>

    <bean id="defaultSftpSessionFactory"
          class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
        <property name="host" value="${sftp.host}"/>
        <property name="privateKey" value="${sftp.private.keyfile}"/>
        <property name="port" value="${sftp.port}"/>
        <property name="user" value="${sftp.username}"/>
        <property name="allowUnknownKeys" value="true"/>
    </bean>

    <int-sftp:outbound-channel-adapter id="sftpOutboundAdapter"
                                       session-factory="sftpSessionFactory"
                                       channel="inputChannel"
                                       remote-filename-generator-expression="payload.getName()"
                                       remote-directory="/tmp/citrus">
        <int-sftp:request-handler-advice-chain>
            <int:retry-advice />
        </int-sftp:request-handler-advice-chain>
    </int-sftp:outbound-channel-adapter>

    <int:channel id="inputChannel"/>

    <citrus:channel-endpoint id="sftpEndpoint" channel="inputChannel" />
</beans>

SftpTransferIT.java
public class SftpTransferIT extends TestNGCitrusTestDesigner {

    @Autowired
    ChannelEndpoint sftpEndpoint;

    @Test @Parameters("context")
    @CitrusTest(name = "SftpTransferIT.sendFileByFTP")
    public void sendFileByFTP(@Optional @CitrusResource TestContext context) {

        final File file = new File("C:\\Temp\\example.xml");
        final org.springframework.messaging.Message<File> message = MessageBuilder.withPayload(file).build();
        Message ftpMessage = new ChannelMessageConverter().convertInbound(message,sftpEndpoint.getEndpointConfiguration(),context);

        send(sftpEndpoint).message(ftpMessage);

    }
}

The following exception is thrown in this situation:
Caused by: org.springframework.messaging.MessagingException: Failed to write to '/tmp/citrus/example.xml.writing' while uploading the file; nested exception is org.springframework.core.NestedIOException: failed to write file; nested exception is 2: No such file
    at org.springframework.integration.file.remote.RemoteFileTemplate.sendFileToRemoteDirectory(RemoteFileTemplate.java:537)
    at org.springframework.integration.file.remote.RemoteFileTemplate.lambda$send$0(RemoteFileTemplate.java:310)
    ... 69 more
Caused by: org.springframework.core.NestedIOException: failed to write file; nested exception is 2: No such file
    at org.springframework.integration.sftp.session.SftpSession.write(SftpSession.java:158)
    at org.springframework.integration.file.remote.session.CachingSessionFactory$CachedSession.write(CachingSessionFactory.java:228)
    at org.springframework.integration.file.remote.RemoteFileTemplate.sendFileToRemoteDirectory(RemoteFileTemplate.java:509)
    ... 70 more
Caused by: 2: No such file
    at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2873)

I think the error is in how I'm sending the message via Citrus. Can someone please advise on how to send the org.springframework.messaging.Message correctly via Citrus?
Or is it better practice to use pure Spring Integration without Citrus' send() to perform tasks like this?

A: Try to configure use-temporary-file-name = "false":

By default, every file that is in the process of being transferred will appear in the file system with an additional suffix which, by default, is .writing; this can be changed using the temporary-file-suffix attribute.
However, there may be situations where you don't want to use this technique (for example, if the server does not permit renaming files). For situations like this, you can disable this feature by setting use-temporary-file-name to false (default is true). When this attribute is false, the file is written with its final name and the consuming application will need some other mechanism to detect that the file is completely uploaded before accessing it.

And be sure that /tmp/citrus really exists on your SFTP.


text:
Q: Rails3: Make update/create fail from model? There's got to be an easy way to do this, but I cannot find an answer...
When some creates or updates a WorkRequest in my app, I do other processing, including creating a Workflow object. I do some checking to make sure, for example, there isn't more than one Workflow already created for this WorkRequest. If there is, I want the update/create to fail with an error message. I just can't see how to do this. I tried returing false from my before_update callback method, but this did not work.
Do I raise an error and rescue it in my controller? What is the right way to do this in Rails 3?
Any help would be much appreciated.

A: This is why you have validations. You can implement an own validation like this:
class ...
  validate :my_validation

  def my_validation
    if workflows > 1
      errors.add(:workflow, "cannot be more than one" )
    end
  end
end


text:
Q: Custom Post Types Archives and Single Pages not showing custom taxonomy data I have a custom post type called "Newsitems" that I have registered two custom taxonomies for: "newsitem types" and "news item tags"
I want these two taxonomies' terms to appear almost like the typical post meta info would for categories and tags, but at the client's request they need to function separately than the default post meta.
Despite almost 15 hours of working on this, I still can't get them to render.
Notes:

*

*On the single post page, I do get the "newsitem type" ID number, but
have been unable to output the actual tax term name.

*I realize you'll see some Genesis related code, as I'm working with Genesis and used the Genesis Custom Meta Box template to build this. However, my problem (I hope) has a lot less to do with Genesis functionality and moreso regular WordPress behavior. I don't feel this is a case for the Genesis support forums.

*I'm not a noob, but clearly I don't understand the WordPress loop as well as I should.

My code for the archive page:
function custom_do_loop() {

// Intro Text (from page content)
echo '
';
echo '
'. get_the_title() .'
';
echo '
' . get_the_content() ;

$args = array(
    'post_type' => 'newsitem', // enter your custom post type
    'orderby' => 'date',
    'order' => 'DESC',
    'posts_per_page'=> '12',  // overrides posts per page in theme settings
    'paged' => get_query_var( 'paged' ),
);

$terms = get_the_terms( $post->ID , 'newsitem-type' );

$loop = new WP_Query( $args );
if( $loop->have_posts() ):

    while( $loop->have_posts() ): $loop->the_post(); global $post;

    echo '
';
        echo '
' . get_the_title() . '
';
        echo '
' . genesis_get_custom_field( '_cmb_newsitem_subtitle' ) . '
'; //retrieve custom field
        echo '
' . genesis_get_custom_field( '_cmb_newsitem_source' ) . '
'; //retrieve custom field
        echo '
' . $terms->name . '
'; //retrieve custom field
        echo '
' . genesis_get_custom_field( '_cmb_newsitem_author' ) . '
'; //retrieve custom field
        echo '
' . genesis_get_custom_field( '_cmb_newsitem_pub_date' ) . '
'; //retrieve custom field
        echo '
' . get_the_content() . '
';
    echo '
';

    endwhile;

    genesis_posts_nav();

endif;

wp_reset_query();

// Outro Text (hard coded)
echo '
';
echo '
';

}
My code for the single posts:
add_action('genesis_before_post_content', 'envision_newsitem_meta');
 function envision_newsitem_meta() {
 global $wp_query;

 $postid = $wp_query->post->ID;
 $subtitle = get_post_meta($postid, '_cmb_newsitem_subtitle' , true);
 $source = get_post_meta($postid, '_cmb_newsitem_source' , true);
 $cattypes = get_post_meta($postid, '_cmb_newsitem_cat_type' , true);
 $author = get_post_meta($postid, '_cmb_newsitem_author' , true);
 $date = get_post_meta($postid, '_cmb_newsitem_pub_date' , true);
 $url = get_post_meta($postid, '_cmb_newsitem_url' , true);
 $tag = get_post_meta($posid, 'post_tag' , true);

 $cattypeString = implode (',' , $cattypes);

 echo '
Subtitle: ' . $subtitle . '
' .       '
Source: ' . $source . '
' . '
Author: ' . $author . '
' . '
Article Type: ' . $cattypeString . '
' . '
Date Published: ' . $date . '
' . '
URL: ' . $url . '
';

 wp_reset_query();
 }

A: get_the_terms() you are using is returning array of items, which cannot be simply echoed to page.
You should try using higher level get_the_term_list() function, which returns string of concatenated results and can be echoed.


text:
Q: How should I give images rounded corners in Android? I would like to change an image I loaded to have round corners.
Any hints, tutorials, best practices you know of?

A: Here's a way I discovered to do it with an ImageView. I tried other methods, including the answers here and on similar questions, but I found that they didn't work well for me, as I needed the corners to be applied to the image view and not directly to the bitmap. Applying directly to the bitmap won't work if you're scaling/cropping/panning that bitmap, since the corners will also be scaled/cropped/panned.
public class RoundedCornersImageView extends ImageView {
    private final Paint restorePaint = new Paint();
    private final Paint maskXferPaint = new Paint();
    private final Paint canvasPaint = new Paint();

    private final Rect bounds = new Rect();
    private final RectF boundsf = new RectF();

    public RoundedCornersImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public RoundedCornersImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RoundedCornersImageView(Context context) {
        super(context);
        init();
    }

    private void init() {
        canvasPaint.setAntiAlias(true);
        canvasPaint.setColor(Color.argb(255, 255, 255, 255));
        restorePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
        maskXferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.getClipBounds(bounds);
        boundsf.set(bounds);

        canvas.saveLayer(boundsf, restorePaint, Canvas.ALL_SAVE_FLAG);
        super.onDraw(canvas);

        canvas.saveLayer(boundsf, maskXferPaint, Canvas.ALL_SAVE_FLAG);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(boundsf, 75, 75, canvasPaint);

        canvas.restore();
        canvas.restore();
    }
}

Here's an alternative that uses hardware layers for the final layer composite:
public class RoundedCornersImageView extends ImageView {
    private final Paint restorePaint = new Paint();
    private final Paint maskXferPaint = new Paint();
    private final Paint canvasPaint = new Paint();

    private final Rect bounds = new Rect();
    private final RectF boundsf = new RectF();

    public RoundedCornersImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public RoundedCornersImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RoundedCornersImageView(Context context) {
        super(context);
        init();
    }

    private void init() {
        canvasPaint.setAntiAlias(true);
        canvasPaint.setColor(Color.argb(255, 255, 255, 255));
        restorePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
        maskXferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));

        setLayerType(View.LAYER_TYPE_HARDWARE, restorePaint);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.getClipBounds(bounds);
        boundsf.set(bounds);

        super.onDraw(canvas);

        canvas.saveLayer(boundsf, maskXferPaint, Canvas.ALL_SAVE_FLAG);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(boundsf, 75, 75, canvasPaint);

        canvas.restore();
    }
}

At first I wasn't able to get it to work with this method because my corners were becoming black; I later realized what the problem was after reading this question: Android how to apply mask on ImageView?. It turns out that modifying the alpha in the canvas is actually "scratching it out" directly on the screen, and punching a hole to the underlying window which is black. That's why two layers are needed: one to apply the mask, and another to apply the composited image to the screen.

A: How about creating a NinePatchDrawable image that has just rounded corners and has a transparent body. Overlay your image with an appropriately re-sized version of your NinePatchDrawable.

A: For a more controlled method draw a rounded rectangle and mask it onto your image using the porter-duff Xfer mode of the paint.
First setup the Xfer paint and the rounded bitmap:
Bitmap myCoolBitmap = ... ; // <-- Your bitmap you want rounded
int w = myCoolBitmap.getWidth(), h = myCoolBitmap.getHeight();

// We have to make sure our rounded corners have an alpha channel in most cases
Bitmap rounder = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(rounder);

// We're going to apply this paint eventually using a porter-duff xfer mode.
// This will allow us to only overwrite certain pixels. RED is arbitrary. This
// could be any color that was fully opaque (alpha = 255)
Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
xferPaint.setColor(Color.RED);

// We're just reusing xferPaint to paint a normal looking rounded box, the 20.f
// is the amount we're rounding by.
canvas.drawRoundRect(new RectF(0,0,w,h), 20.0f, 20.0f, xferPaint);

// Now we apply the 'magic sauce' to the paint
xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

Now apply this bitmap ontop of your image:
Bitmap result = Bitmap.createBitmap(myCoolBitmap.getWidth(), myCoolBitmap.getHeight() ,Bitmap.Config.ARGB_8888);
Canvas resultCanvas = new Canvas(result)
resultCanvas.drawBitmap(myCoolBitmap, 0, 0, null);
resultCanvas.drawBitmap(rounder, 0, 0, xferPaint);

Bitmap with rounded corners now resides in result.

A: package com.pkg;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView;

public class RoundedImage extends Activity {
    /** Called when the activity is first created. */
    ImageView imag;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imag=(ImageView)findViewById(R.id.image);

        //ImageView img1=(ImageView)findViewById(R.id.imageView1);
        BitmapFactory.Options bitopt=new BitmapFactory.Options();
        bitopt.inSampleSize=1;
        // String img=Environment.getExternalStorageDirectory().toString();
        // String filepath =Environment.getExternalStorageDirectory().toString();
        String filepath ="/mnt/sdcard/LOST.DIR";
        File imagefile = new File(filepath + "/logo.jpg");
        FileInputStream fis = null;
        try
        {
        fis = new FileInputStream(imagefile);
        }
        catch (FileNotFoundException e1)
        {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        }
        Bitmap bi = BitmapFactory.decodeStream(fis);
        if(bi!=null){
            imag.setImageBitmap(getRoundedCornerBitmap(bi));
        }

    }

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
         bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = 12;

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);

    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    return output;
    }
}

A: Why not use clipPath?
protected void onDraw(Canvas canvas) {
    Path clipPath = new Path();
    float radius = 10.0f;
    float padding = radius / 2;
    int w = this.getWidth();
    int h = this.getHeight();
    clipPath.addRoundRect(new RectF(padding, padding, w - padding, h - padding), radius, radius, Path.Direction.CW);
    canvas.clipPath(clipPath);
    super.onDraw(canvas);
}

A: Romain Guy himself writes about this in his blog:

To generate the rounded images I simply wrote a custom Drawable that
  draws a rounded rectangle using Canvas.drawRoundRect(). The trick is
  to use a Paint with a BitmapShader to fill the rounded rectangle with
  a texture instead of a simple color. Here is what the code looks like:

BitmapShader shader;
shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);

RectF rect = new RectF(0.0f, 0.0f, width, height);

// rect contains the bounds of the shape
// radius is the radius in pixels of the rounded corners
// paint contains the shader that will texture the shape
canvas.drawRoundRect(rect, radius, radius, paint);

The sample application goes a little further and fakes a vignette
  effect by combining the BitmapShader with a RadialGradient.

A: Here's another rounded ImageView implementation using Path. The performance is great, but in certain conditions some bugs may appear on emulators because of the hardware drawing.
public class RoundImageView extends ImageView {

    private Path mPath;
    private RectF mRect;
    private Paint mPaint;

    private int mCornerRadius;
    private float mImageAlpha;
    private boolean mIsCircular;

    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.roundImageViewStyle);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.RoundImageView, defStyle, 0);

        mCornerRadius = a.getDimensionPixelSize(R.styleable.RoundImageView_cornerRadius, 0);
        mIsCircular = a.getBoolean(R.styleable.RoundImageView_isCircular, false);
        mImageAlpha = a.getFloat(R.styleable.RoundImageView_imageAlpha, 1);

        a.recycle();

        setAlpha((int) (mImageAlpha * 255));

        // Avoid expensive off-screen drawing
        setLayerType(LAYER_TYPE_HARDWARE, null);

        mPath = new Path();

        mRect = new RectF();

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mPath.reset();

        if (mIsCircular) {
            float halfWidth = canvas.getWidth() / 2;
            float halfHeight = canvas.getHeight() / 2;
            float radius = Math.max(halfWidth, halfHeight);

            mPath.addCircle(halfWidth, halfHeight, radius, Path.Direction.CW);
        } else {
            mRect.right = canvas.getWidth();
            mRect.bottom = canvas.getHeight();

            mPath.addRoundRect(mRect, mCornerRadius, mCornerRadius, Path.Direction.CW);
        }

        canvas.drawPath(mPath, mPaint);
    }
}

P.S. Learn OpenGL ES provided the best solution. It's very smooth and works on emulators too.

A: best solution I found ->
1) create rounded corner drawable. And set to imageview as background.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
    android:radius="10dp" /></shape>

2) Then set image view object property of setClipToOutline(true) in java code.
imageview.setClipToOutline(true);

It works like charm


text:
Q: Filter objects that have a timestamp from 2 days ago I'm working in apps script . I have a series of objects that have a date_time property that is a timestamp. I want to select all objects that were timestamped 2 days ago only (I don't want 1 day ago or three days ago).
As an example assume today is 3/19/2019. 2 days ago is 3/17/2019. I want all the time stamps that include 3/17/2019
I'm reading https://www.digitalocean.com/community/tutorials/understanding-date-and-time-in-javascript .
Assuming I have:
objs = [{'name':'tom','timestamp':'3/18/2019 11:42:23'},
{'name':'bob','timestamp':'3/19/2019 11:42:23'}, {'name':'dave','timestamp':'3/20/2019 11:42:23'}

]

I can get the date from 2 days ago with:
var d = new Date();
var 2daysago = d.setDate(d.getDate() - daysAgo);

I could then filter with:
var filtered = objs .filter(function (obj) {
return X
});

What is the best way to compare 2daysago each objects timestamp? would it be better to use date objects or use some kind of string method?

A: *

*At first, all values from Spreadsheet were retrieved and put it to objs.

*You want to retrieve the required values from objs using Google Apps Script.

*

*In the case of the image, those are objects of 3/17/2019 10:11:47, 3/17/2019 10:11:49, when the today is 3/19/2019.

If my understanding is correct, how about this answer? In this answer, I proposed 2 patterns for your situation.
Pattern 1:
In this pattern, timestamp is used as a string. When the today is 3/19/2019, the values including 3/17/2019 at timestamp are retrieved as the values of 2 days ago.
var nDaysAgo = 2; // 2 days ago
var date = new Date();
date.setDate(date.getDate() - nDaysAgo);
//  var checkDate = Utilities.formatDate(d, Session.getScriptTimeZone(), "M/dd/yyyy"); // If the day is 01,02,,, please use this.
var checkDate = Utilities.formatDate(date, Session.getScriptTimeZone(), "M/d/yyyy"); // If the day is 1,2,,, please use this.
var res = objs.filter(function(e) {return e.timestamp.indexOf(checkDate) > -1});
Logger.log(res)

Pattern 2:
In this pattern, timestamp is used as a date object. When the today is 3/19/2019, the values from 3/17/2019 00:00:00 to 3/18/2019 00:00:00 are retrieved as 2 days ago.
var nDaysAgo = 2; // 2 days ago
var d1 = new Date();
d1.setHours(0, 0, 0, 0);
var d1c = d1.setDate(d1.getDate() - nDaysAgo + 1);
var d2 = new Date();
d2.setHours(0, 0, 0, 0);
var d2c = d2.setDate(d2.getDate() - nDaysAgo);
var res = objs.filter(function(e) {
  var temp = new Date(e.timestamp).getTime();
  return temp < d1c && temp > d2c;
});
Logger.log(res)

Note:

*

*If you want to test as 3/19/2019, please use new Date("3/19/2019 00:00:00") instead of new Date().

Reference:

*

*formatDate()
If I misunderstood your question and this was not the result you want, I apologize.

A: const day = 24 * 60 * 60 * 1000;
const oneDayAgo = Date.now() - day;
const twoDaysAgo = Date.now() - 2 * day;

const isTwoDaysOld = function(obj) {
    const d = new Date(obj.timestamp);
    return d > twoDaysAgo && d < oneDayAgo;
}

const filtered = objs.filter(isTwoDaysOld);

In JS Date is converted to ms for numberical operations like +, -, >, < etc.
Then all we need to do is find out the point of time (in ms) for 2 days ago and the point in time for 1 day ago. And then check if the date in question is in-between.
Note: this assumes you mean "24 hours" by "day", not the "day part of the date"


text:
Q: Angular form error Property does not exist on type I created this simple form form1.component.html in Angular
    <form #personForm="ngForm" (ngSubmit)="submitForm(personForm)" novalidate>

             Enter First Name
            <input
            type="text"
            [(ngModel)]="person.firstName"
            required
            pattern="[A-Za-z]*"
            #firstName="ngModel"
            name="fName"
            />

        <button type="submit" class="btn-solid">Submit</button>
        <button type="button" (click)="clearForm(personForm)">Reset</button>

    </form>

The ts file form1.component.ts is as follows
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-form1',
  templateUrl: './form1.component.html',
  styleUrls: ['./form1.component.css']
})
export class Form1Component implements OnInit {
  person!: {};

  constructor() { }

  ngOnInit(): void {
    this.person = {
      firstName: 'John',
      lastName: 'Black'
    };

  }
  submitForm = (form: any) => {
  }

  clearForm = (form: any) => {
    form.reset();
    form.submitted = false;
  }
}

When I run ng serve in VS Code, I get following error

Error: src/app/components/form1/form1.component.html:6:33 - error TS2339: Property 'firstName' does not exist on type '{}'.

6             [(ngModel)]="person.firstName"
                                  ~~~~~~~~~

  src/app/components/form1/form1.component.ts:5:16
    5   templateUrl: './form1.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component Form1Component.

I tried to initialize the person class in constructor, but still gives the same error

A: You have a wrong type declaration
Change the declared type in your component
export class Form1Component implements OnInit {
  person!: { firstName: string; lastName: string };

Otherwise you can make it even more lighter by
 export class Form1Component implements OnInit {
      person!: any;

Also if you don't want to duplicate your code of { firstName: string; lastName: string } create an interface type
interface Person{
  firstName: string;
  lastName: string;
}

and then you can use it in multiple places like
export class Form1Component implements OnInit {
  person!: Person;

  doSomething(person: Person) {

  ...
  }

A: While the form is incomplete (since it only has first name) you can declare an interface to use throughout your component. This will give you better type security instead of having any scattered through the component.
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';

interface Person{
  firstName: string;
  lastName: string;
}

@Component({
  selector: 'app-form1',
  templateUrl: './form1.component.html',
  styleUrls: ['./form1.component.css']
})
export class Form1Component implements OnInit {
  person: Person;

  constructor() { }

  ngOnInit(): void {
    this.person = {
      firstName: 'John',
      lastName: 'Black'
    };

  }
  submitForm = (form: NgForm) => {
    this.person = form.value as Person;
  }

  clearForm = (form: NgForm) => {
    form.reset();
    form.submitted = false;
  }
}