PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label message. Show all posts
Showing posts with label message. Show all posts

Wednesday, July 13, 2022

[FIXED] Which protocol to use for sending JMS messages?

 July 13, 2022     jms, message, protocols     No comments   

Issue

I need some advise to implement the best protocol (not http, tcp, ...) te send messages.

  • Should I send Serialized Objects? (POJO's)
  • Should I send technology independent XML messages?
  • What would be recommended? Both will work, but what is best practice. Sharing a library is not what I prefer, but is it easy to work with XML? Are there better alternatives? Thanks in advance!

I have one server, with a 1000 clients connected. The server delivers task to the clients. The clients send information back after executing different tasks.

How should I send a task to a JMS client with some parameters?

A task is nothing more than an action and some parameters.

  • Example: "action=measure; parameters: duration=100sec; samples=100" --> collect 100 samples during 100 seconds.
  • Example: "action=config; parameters: set of configuration parameters" --> to change the client configuration
  • Example: "action=stop" --> Stop the client (the system wil restart after a daily reboot)

A report is nothing more than data.

  • Example: "list of 100 values from measurement"
  • Example: "the content of a log-file"

I have read many articles, but couldn't find an answer for this question. Thanks in advance.


Solution

This is our current implementation.

We define a protocol with an XSD and let this generate classes (POJO's). This allows us to marshal/unmarshal the objects and send them as XML objects.

Our XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
           jaxb:version="2.0">

    <!-- Ping
        The server will send a ping to a client and waits for a pong.
    ****************************************************************** -->
    <xs:element name="Ping">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="client" type="xs:string"/>
                <xs:element name="message" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <!-- Pong
        The client will send a pong back to the server.
    ****************************************************************** -->
    <xs:element name="Pong">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="client" type="xs:string"/>
                <xs:element name="message" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <!-- Alive
        The client will send an alive message when it starts up.
        The time is local client time.
    ****************************************************************** -->
    <xs:element name="Alive">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="client" type="xs:string"/>
                <xs:element name="time" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <!-- ... Many more message definitions ...
    ****************************************************************** -->

</xs:schema>

Our test class:

public class JaxbFacadeTest {

    @Test
    public void testPing() throws JAXBException, SAXException, UnsupportedEncodingException {
        System.out.println("testPing");
        Ping ping = new Ping();
        ping.setClient("guid-client");
        ping.setMessage("Ping Message");
        String marshalToString = JaxbFacade.getInstance().marshalToString(ping);
        System.out.println(marshalToString);
    }

    @Test
    public void testPong() throws JAXBException, SAXException, UnsupportedEncodingException {
        System.out.println("testPong");
        Pong pong = new Pong();
        pong.setClient("guid-client");
        pong.setMessage("Ping Message");
        String marshalToString = JaxbFacade.getInstance().marshalToString(pong);
        System.out.println(marshalToString);
    }

    @Test
    public void testAlive() throws JAXBException, SAXException, UnsupportedEncodingException {
        System.out.println("testAlive");
        Date now = new Date();
        Alive alive = new Alive();
        alive.setClient("guid-client");
        alive.setTime(now.toString());
        String marshalToString = JaxbFacade.getInstance().marshalToString(alive);
        System.out.println(marshalToString);
    }

    //Many more
}

The classes are generated with maven:

<build>
    <resources>
        <resource>
            <directory>${project.basedir}/src/main/xsd</directory>
            <targetPath>com/test/package/client/jaxb</targetPath>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <executions>
                <execution>
                    <id>jaxb</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <generatePackage>com.test.package.client.jaxb</generatePackage>
                <schemaDirectory>${project.basedir}/src/main/xsd</schemaDirectory>
            </configuration>
        </plugin>
    </plugins>
</build>


Answered By - Dimitri Dewaele
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to change sending messages in android?

 July 13, 2022     android, message, sms     No comments   

Issue

I want to change text messages when they are in sending status.

In fact, I need to change text of message written by user before sending and add some advertisement in it (maybe add a link). How can I do so?

Is device needed to be root?


Solution

No. You can't do that. You should not do that. It's very intrusive. If you want to do that, create an Sms Client of your own and do that.



Answered By - Seshu Vinay
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to show validation errors in the single message Codeigniter?

 July 13, 2022     codeigniter, message, show, validation     No comments   

Issue

I have a problem with codeigniter, when checking the fields it shows errors as follows:

The Username field is required. The Password field is required. 
The Another field is required

but I need it so like this:

Required fields a Username, Password, Another.

How to do it?


Solution

I wouldn't do that. But you have numerous number of choices. For example: don't use form validation library at all or develop your own. Try something like this:

$errorArray = array();
if (!$this->input->post('username')) {
    $errorArray[] = 'Username';
}
if (!$this->input->post('Password')) {
    $errorArray[] = 'Password';
}
if (count($errorArray)!==0) {
    $allErrorFields = implode(",", $errorArray);
    $errorMessage = 'Required fields: '.$allErrorFields;
    $data['errorMessage'] = $errorMessage;
}

$this->load->view('myview', $data);


Answered By - cssBlaster21895
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why isn't my f:param rendering inside h:outputText?

 July 13, 2022     jsf, message, parameters     No comments   

Issue

I have a message.properties file which contains:

success_text=How cool... You have guessed the number.  {0} is correct! 

I have a JSF which contains:

<h:outputText value="#{msg.success_text}" >
    <f:param value="#{numberBean.userNumber}" />
</h:outputText>

No matter what the value of is, the HTML comes out:

How cool... You have guessed the number. {0} is correct!

Why isn't {0} changing to the value indicated in the <f:param> and how can I fix it?


Solution

The <f:param> isn't supported by <h:outputText>. It works in <h:outputFormat> only.

<h:outputFormat value="#{msg.success_text}" >
    <f:param value="#{numberBean.userNumber}" />
</h:outputFormat>


Answered By - BalusC
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to delete Multiple messages or single message from the Inbox in Android?

 July 13, 2022     android, android-contentresolver, message     No comments   

Issue

I access all Message from the Inbox with the help of Content Resolver But Now the problem is that I want to delete Multiple Message Or a single Message from the Inbox. I have found delete functionality for all messages not for a single message or multiple message. I store all message in a ArrayList. Any Help will be appreciated.

My code for read Message is:--

Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI , null, null, null,
                null);
        startManagingCursor(cur);

        int size=cur.getCount();


        if (cur.moveToFirst()) 
        {

            for(int i=0;i<size;i++)
            {
                    InboxField tempInboxField = new InboxField();
                    tempInboxField.body = cur.getString(cur.getColumnIndexOrThrow("body"));
                    tempInboxField.protocol = cur.getString(cur.getColumnIndexOrThrow("protocol"));
                    tempInboxField.type =cur.getString(cur.getColumnIndexOrThrow("type"));
                    tempInboxField.status = cur.getInt(cur.getColumnIndexOrThrow("status"));
                    tempInboxField.address =cur.getString(cur.getColumnIndexOrThrow("address"));
                    String tempdate =cur.getString(cur.getColumnIndexOrThrow("date"));
                    tempInboxField.id = cur.getInt(cur.getColumnIndexOrThrow("_id"));
                    tempInboxField.person = cur.getString(cur.getColumnIndexOrThrow("person"));
                    Long timestamp = Long.parseLong(tempdate);    
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(timestamp);
                    Date finaldate = calendar.getTime();
                    tempInboxField.date = finaldate.toString();
                    arrayList.add(tempInboxField);
                    cur.moveToNext();
                }

            }

Solution

You can delete a single message using this:

Uri deleteUri = Uri.parse("content://sms");
int count = 0;
Cursor c = context.getContentResolver().query(deleteUri, null, null,
        null, null);
while (c.moveToNext()) {
   try {
   // Delete the SMS
   String pid = c.getString(0); // Get id;
   String uri = "content://sms/" + pid;
   count = context.getContentResolver().delete(Uri.parse(uri),
               null, null);
   } catch (Exception e) {

   }
}

If you want to delete a conversation thread you can use something like this:

String uri = "content://sms/conversations/" + pid;
getContentResolver().delete(Uri.parse(uri), null, null);  

where pid is the id of the thread.



Answered By - frayab
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to avoid error messages in c++ caused by memory overflow

 July 13, 2022     c++, memory, message, overflow     No comments   

Issue

I have a C++ program which sometimes crashes because of memory overflow (max memory is 2GB, in some cases the program just needs more...).

I know that and I want the program to behave like that (because of reasons).

But the thing is, that windows opens a window with "Program stops working...".

How do I avoid these error messages and just get my application to shutdown without telling anything to the user?

Thanks in advance.


Solution

if you allocate memory using new you can try to catch std::bad_alloc exception

try
{
  buffer = new Type[HUGE_VAL];
}
catch (const std::bad_alloc& e)
{
  gracefulExit();
}

Remember, that try & catch can be somewhere at top level (in main for example), while allocation itself deep inside processing etc.

Still, reconsider doing your task in different way - split it into smaller tasks, or use some temporary files etc.



Answered By - Hcorg
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to implement a GCM Hello World for Android using Android Studio

 July 13, 2022     android, google-app-engine, google-cloud-messaging, message     No comments   

Issue

I have been searching for some days now how to implement Google Cloud Messaging for Android, but I'm with some serious doubts about it.

I mean, apparently Google put some good informations online, like here and here, but I'm confused about all the logic. One page talks about the client side, and another about the server side. Great, but how do I bind all of it together? How do I implement HTTP and/or XMPP protocol to communicate with the GCM connection server(s)?

I would like implement a basic HelloWorld for GCM, that would work with the following steps:

1. App send a message (say "HelloWorld") to GCM;
2. Receive that message from GCM and add it to a TextView.

What are the steps needed to achieve this basic app?

Thank you,


Solution

If you have read the two links in your question and understood GCM key concepts, then you can refer to the following sample codes:

Of course, let's assume that you have finished:

  • Create a project and its server API key at Google Developers Console
  • Set permissions in your AndroidManifest files like this <uses-permission android:name="android.permission.INTERNET" />

Server side:

public class MainActivity extends AppCompatActivity {

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = (TextView) findViewById(R.id.textView);

        new GCMRequest().execute();
    }

    ...    

    private class GCMRequest extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {

            final String API_KEY = "..."; // An API key saved on the app server that gives the app server authorized access to Google services
            final String CLIENT_REG_ID = "..."; //An ID issued by the GCM connection servers to the client app that allows it to receive messages
            final String postData = "{ \"registration_ids\": [ \"" + CLIENT_REG_ID + "\" ], " +
                    "\"delay_while_idle\": true, " +
                    "\"data\": {\"tickerText\":\"My Ticket\", " +
                    "\"contentTitle\":\"My Title\", " +
                    "\"message\": \"Test GCM message from GCMServer-Android\"}}";

            try {                        
                URL url = new URL("https://android.googleapis.com/gcm/send");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestProperty("Authorization", "key=" + API_KEY);

                OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
                writer.write(postData);
                writer.flush();
                writer.close();
                outputStream.close();

                int responseCode = urlConnection.getResponseCode();
                InputStream inputStream;
                if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
                    inputStream = urlConnection.getInputStream();
                } else {
                    inputStream = urlConnection.getErrorStream();
                }
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp, response = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    response += temp;
                }
                return response;
            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            }
        }

        @Override
        protected void onPostExecute(String message) {
            super.onPostExecute(message);

            if (mTextView != null) {
                try {
                    JSONObject jsonObject = new JSONObject(message);
                    mTextView.setText(jsonObject.toString(5));
                } catch (JSONException e) {
                    e.printStackTrace();
                    mTextView.setText(e.toString());
                }
            }
        }
    }
}

Client-side:

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private final Context mContext = this;
    private final String SENDER_ID = "..."; // Project Number at https://console.developers.google.com/project/...
    private final String SHARD_PREF = "com.example.gcmclient_preferences";
    private final String GCM_TOKEN = "gcmtoken";    
    public static TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences appPrefs = mContext.getSharedPreferences(SHARD_PREF, Context.MODE_PRIVATE);
        String token = appPrefs.getString(GCM_TOKEN, "");
        if (token.isEmpty()) {
            try {
                getGCMToken();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        mTextView = (TextView) findViewById(R.id.textView);
    }

    ...    

    private void getGCMToken() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    InstanceID instanceID = InstanceID.getInstance(mContext);
                    String token = instanceID.getToken(SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                    if (token != null && !token.isEmpty()) {
                        SharedPreferences appPrefs = mContext.getSharedPreferences(SHARD_PREF, Context.MODE_PRIVATE);
                        SharedPreferences.Editor prefsEditor = appPrefs.edit();
                        prefsEditor.putString(GCM_TOKEN, token);
                        prefsEditor.apply();
                    }
                    Log.i("GCM", token);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();
    }
}

GcmService.java:

public class GcmService extends GcmListenerService {

    @Override
    public void onMessageReceived(String from, Bundle data) {
        JSONObject jsonObject = new JSONObject();
        Set<String> keys = data.keySet();
        for (String key : keys) {
            try {
                jsonObject.put(key, data.get(key));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        try {
            sendNotification("Received: " + jsonObject.toString(5));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDeletedMessages() {
        sendNotification("Deleted messages on server");
    }

    @Override
    public void onMessageSent(String msgId) {
        sendNotification("Upstream message sent. Id=" + msgId);
    }

    @Override
    public void onSendError(String msgId, String error) {
        sendNotification("Upstream message send error. Id=" + msgId + ", error" + error);
    }

    private void sendNotification(final String msg) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {                    
                if (MainActivity.mTextView != null) {
                    MainActivity.mTextView.setText(msg);
                }
            }
        });
    }
}

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gcmandroid" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission android:name="com.example.gcm.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />

    <application
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.example.gcm" />
            </intent-filter>
        </receiver>
        <service android:name=".GcmService" android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Answered By - BNK
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to display an error message for incorrect input?

 July 13, 2022     c, input, message, multiple-choice     No comments   

Issue

I am currently trying to make code for a calculator that will calculate the area of a circle, cube, or square, depending on which integer the user enters in the beginning, then prompt for the measurements, etc.
I want the user to choose between 1, 2, or 3.

My current code:

 #include <stdio.h>
 #include <math.h>

 int main(void){

     int shape;

     printf("\nArea calculation\n(1) Square\n(2) Cube \n(3) Circle \nPlease make a selection"); 
     scanf("%d", &shape);

     else{ 
         printf("\nIncorrect Choice");
     }

 return 0;
 }

My question is:

  1. How can I make an error message pop up if they haven't entered that info?
  2. How I can make it loop and ask the same question again if they enter something other than 1, 2,3.
  3. How do I make it so if the user enters something line: 99 then the program shuts off?

Solution

You need to read and probably do a few c tutorials before you try to do this. These will get you started toward learning how to (1) print error output, (2) handle input, and (3) manage program control, which are the three things you seemed to ask about. There are a lot of ways to do this.

  1. For error printing, look up stdout and stderr. A common strategy when learning might be using the function fprintf to write to standard error.

fprintf(stderr, "Error: incorrect value inputted. Please enter 1, 2, or 3.\n");

  1. For input handling, you should google examples. Your scanf statement should end in a semicolon, not a colon. Statements in C end in a semicolon. Then you need some control flow to see what they entered and do something different based on that. A switch statement may make sense where, as here, you have a small number of options to deal with.

    /* put in a function so we can call it from main() multiple times. */
    int myFunction() {
     scanf("%d", &shape); 
     switch(shape) {
     case 1:
        /* do stuff */
        break;
     case 2:
        /* do stuff */
        break;
     case 99:
        return 99;
     default:
        fprintf(stderr, "Incorrect Choice");
     }
    }
  2. Program Control. Finally, you want to be able to call this again if they fail. So put it in a function, and call that function from main.

    int main() {
        /* this empty while loop will call myFunction() forever, */
        /* or until it returns a 99 because someone quit. */
        while(myFunction() != 99) ;
    }
    

This is a bit inelegant but should get you started. Again, you really, really want to start looking at tutorials on learning the language.



Answered By - Tom
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 12, 2022

[FIXED] how to intent to native app after sending message from inbuilt message app

 July 12, 2022     android, message, sms     No comments   

Issue

Am using inbuilt message application in my app to send message, but after sending message it stuck there only,while sending message it should intent back to my application how can i do it.

 public void sendSmsIntent(String phoneNumber) {
            Intent intent2 = new Intent(Intent.ACTION_SENDTO);
            intent2.setData(Uri.parse("smsto:" + Uri.encode(phoneNumber)));
            startActivity(intent2);

        }

Solution

Call sendSMS() method wherever you want to send SMS;

 private void sendSMS()
        {

            PendingIntent sent = this.createPendingResult(SENT, new Intent(),   PendingIntent.FLAG_UPDATE_CURRENT);


            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendDataMessage(strcontactnumber, null, SMS_PORT, messageText.getBytes(), sent, null);
        }

onActivityResult();

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    String toast = null;
    switch (requestCode)
    {
    case SENT :
        switch (resultCode)
        {
        case RESULT_OK :
            toast = "OK";
            break;
        case SmsManager.RESULT_ERROR_GENERIC_FAILURE :
            toast = "Generic Failure";
            break;
        case SmsManager.RESULT_ERROR_RADIO_OFF :
            toast = "Radio Off";
            break;
        case SmsManager.RESULT_ERROR_NULL_PDU :
            toast = "Null Pdu";
            break;
        }
        break;
    }

    if (toast != null)
    {
        Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
    }
}

It will directly send sms from your app without calling native app

And if you want to return back to your app by your code then

It is possible. Just need to add the following extra to your intent:

sendIntent.putExtra("exit_on_sent", true);


Answered By - KishuDroid
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I get Ruby 2.1.5 to report an object's class for a missing method error?

 July 12, 2022     exception, message, method-missing, ruby     No comments   

Issue

This line:

@page = @page.launch_profile(@profile_name)

is causing this error:

undefined method `launch_profile' for #<Object:0x007f9013d785e8> (NoMethodError)

If I add puts "Page = #{@page} "{@page.class}" immediately before the call that complains, I get

Page = #<OwnProfilePage:0x007f9013bf5e78> OwnProfilePage

What's weird is that on the command-line, the same version of Ruby (2.1.5) does this:

$ ruby -le 'class Dog; end; Dog.new.foo'
-e:1:in `<main>': undefined method `foo' for #<Dog:0x007fb64120c6d8> (NoMethodError)

so I know it usually works.

I've tried adding a method_missing() method to Object, but it affected nothing, so I presume someone else, somewhere else, is monkey-patching or overriding or otherwise meta-buggering things. I even patched NoMethodError.new() to print a stack trace to try to locate the errant code.

Further, is there a reasonably general to work out which bit of a Ruby system is doing what, when there's potentially so much voodoo and other poorly-conceived global-change nonsense going on in far flung and random gems? (In another case, 'fail' started reporting the previous rescued exception's message, instead of the string I supplied it with.)


Solution

OK, I found out what's going on:

It's calabash-android's ABase class, whose method_missing 'helpfully' delegates to its world object, which also doesn't know about my method (unsurprisingly). Unfortunately, its author failed to think about catching exceptions when his/her surprising implementation detail failed, so it's reporting not my page object but the world object and making Ruby look broken.

Had I looked at my logging's hexagibberish carefully, I'd have noticed it wasn't Ruby misreporting my page object's class, but correctly reporting a completely different object (although the object's class isn't Object, but Object+Test::Unit::Assertions+half+a+million+other+mixins which would have more rapidly clued me in that it was reporting about the wrong thing).

I've wrapped that method_missing's body in a try/catch that reports the real object and also mentions that nothing in world knows about it either.

This is one of the main reasons I dislike magic: people generally fail to provide proper diagnostics. The other main reason is because magic used to implement surprising behaviour transparently is evil.



Answered By - android.weasel
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I combine incoming data and character in VHDL?

 July 12, 2022     arrays, lcd, message, vhdl     No comments   

Issue

I want do drive a 4x16 LCD display using VHDL. The first line should say "FREQ: 000 RPM" where the zeroes represent incoming 8-bit frequency data. Same for the next lines with different data, also 8-bit. My VHDL code is as follows:

-- 16 Characters
subtype string16_type is string(1 to 16);
-- 4 string of 16 characters
type message4x16_type is array(1 to 4) of string16_type;
-- Define messages displayed
constant message_home:  message4x16_type := (    --1234567890123456
                                             1 => "FREE MODE       ",
                                             2 => "PARCOURS        ",
                                             3 => "- - - - - - - - ",
                                             4 => " - - - - - - - -");
constant message_info:  message4x16_type := (    --1234567890123456
                                             1 => "FREQ:  000 RPM  ",
                                             2 => "SPEED: 000 KM/H ",
                                             3 => "DIST:  000 KM   ",
                                             4 => "MORE INFO       ");
-- Character amount in  line
signal character_counter: integer range 1 to 16;
-- Line amount on LCD
signal line_counter     : integer range 1 to 4;

Then follows a state machine, with state write_char looking partly like this:

if msg_select = '0' then
    aline := message_home(line_counter);
elsif msg_select = '1' then
    aline := message_info(line_counter);
end if;
data <= std_logic_vector(to_unsigned(character'pos(aline(character_counter)),8));

Everything works smoothily this way but I can't think of a way to implement the frequency data into the message, like using %i in C. I am aware of the 'record' statement but not sure how to use it in this situation. Any other ways to implement the data are very welcome.

Thanks on forehand.


Solution

Declaring types, constants and signals as before:

-- 16 characters
type lcd_line_type is array(0 to 15) of character;
-- 4 lines of 16 characters
type message4x16_type is array(0 to 3) of lcd_line_type;
-- Define messages displayed
constant message_home : message4x16_type := (
--1234567890123456
 "FREE MODE       ",
 "PARCOURS        ",
 "- - - - - - - - ",
 " - - - - - - - -"
);
constant message_info :  message4x16_type := (
--1234567890123456
 "FREQ:  000 RPM  ",
 "SPEED: 000 KM/H ",
 "DIST:  000 KM   ",
 "MORE INFO       "
);
-- Character amount in line
signal character_counter : integer range 0 to 15;
-- Line amount on LCD
signal line_counter : integer range 0 to 3;

subtype rawchar is std_logic_vector(7 downto 0);
type rawstring is array(natural range <>) of rawchar;
signal rpm : rawstring(2 downto 0);
signal kmh : rawstring(2 downto 0);

function to_rawchar(char : character) return rawchar is
begin
  return std_logic_vector(to_unsigned(character'pos(char), 8));
end function;

Usage example:

if msg_select = '0' then
  data <= to_rawchar(message_home(line_counter)(character_counter));
elsif msg_select = '1' then
  case line_counter is
    when 0 =>
      -- replace 000 by rpm(2:0)
      case character_counter is
        when 6 => data <= rpm(2);
        when 7 => data <= rpm(1);
        when 8 => data <= rpm(0);
        when others => data <= to_rawchar(message_info(0)(character_counter));
      end case;
    when 1 =>
      -- replace 000 by kmh(2:0)
      case character_counter is
        when 7 => data <= kmh(2);
        when 8 => data <= kmh(1);
        when 9 => data <= kmh(0);
        when others => data <= to_rawchar(message_info(1)(character_counter));
      end case;
    -- ...
  end case;
end if;

The first case tests for the requested line. The second case overrides the constant values at particular positions.

I additionally extracted the char to slv conversion into a function.



Answered By - Paebbels
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to add additional data in message asmack/smack?

 July 12, 2022     android, asmack, message, smack     No comments   

Issue

I am sending a message with (a)Smack and Openfire server. I am successfully able to send message with the message body. Now i need to send some additional data with the message. I don't want to append the string to the data and then process it after receiving. Is there any other approach? or with extensions?


Solution

Use a custom PacketExtension.



Answered By - Flow
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to tell an object to execute a message

 July 12, 2022     message, smalltalk, squeak     No comments   

Issue

I have an object, and a string containing a message I would like to send to it.

For example, the string '+ 5', which I would like to send to some integer object.

If it was in the workspace then I would just write "obj + 5", but I need it to be done at running time without knowing the string in advance...


Solution

If you can separate the argument of the message from the message itself, then you can "perform" the message send:

obj := 3.
msg := '+'.
arg := 5.
result := obj perform: msg asSymbol with: arg.

Otherwise, you would have to use the Compiler, which would translate the string into compiled code and execute it:

obj := 3.
msg := 'self + 5'.
result := Compiler evaluate: msg for: obj logged: false.

A common technique to avoid repeated compilation is to compile a block, which can be evaluated more efficiently:

obj := 3.
msg := '[:x | x + 5]'.
block := Compiler evaluate: msg.
result := block value: obj.

Btw, the code above (and below) is for Squeak, other Smalltalks may have a different way to access the Compiler.

There is an even more hackish way that lets you access the variable directly from the string. This is by executing the compiled code in "thisContext" (in this case you need to declare the temp vars even in a workspace):

| obj msg result |
obj := 3.
msg := 'obj + 5'.
result := Compiler new evaluate: msg in: thisContext to: nil.

However, I would not recommend this last technique. Performing is generally safer than involving the Compiler. That said, it can be used to implement some serious meta stuff. E.g.:

| obj |
obj := 3.
'The result is {obj + 5}.' expand

Implementation of the "expand" method is left to the curious reader ;)



Answered By - codefrau
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I send email to someone's @facebook.com address without it landing in the "Other Messages" folder?

 July 12, 2022     email, facebook, message, spam     No comments   

Issue

Facebook filters many messages to the Other Messages folder (http://betabeat.com/2011/12/return-of-laptop-lost-in-taxi-foiled-by-facebooks-obscure-message-folder/).

Does anyone know how they filter incoming mail to @facebook.com email addresses? Can non-friends email users at @facebook? Can apps?


Solution

If the user replies to an e-mail in the Other messages folder, that e-mail address is then whitelisted, and subsequent e-mails will end up in the Messages folder.

I read somewhere that you only have to move a message from Other messages to Messages to whitelist the sender of that message, but that doesn't seem to work.



Answered By - Joakim Syk
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use reflection in Android for sending sms from second sim slot?

 July 12, 2022     android, dual-sim, message, reflection, sms     No comments   

Issue

I need to send sms via second slot of an android device. I searched many times to find a solution for sending sms with second sim slot. But there is not any regular solution for this problem. Some people use reflection for each series of mobile devices for sending sms from second slot. Now, how can I use reflection for this problem?


Solution

You don't mention which cookie you're targeting, but in Lollipop MR1 you can send with the second SIM card by fetching the SmsManager based on subscription:

http://developer.android.com/reference/android/telephony/SmsManager.html#getSmsManagerForSubscriptionId(int)

Every SIM card gets assigned a subscription ID when they are inserted. These IDs and information about the SIM are stored in the siminfo table in the TelephonyProvider. The IDs start from 1. To get information about what subscription IDs you currently have active, you use the SubscriptionManager: http://developer.android.com/reference/android/telephony/SubscriptionManager.html

The method getActiveSubscriptionInfoForSimSlotIndex takes a SIM slot index (normally either 0 or 1) and returns subscription info about that SIM, including the subscription ID which you can use to fetch the right SmsManager.

If you're targeting platforms prior to Lollipop then the DS support is not officially supported by Google and it's most likely added by the platform vendor (Qualcomm, Mediatek etc.) so the API is undocumented. You can query the SmsManager for its methods by calling SmsManager.class.getDeclaredMethods(), but the DS API might be in a completely different and undocumented class.



Answered By - fejd
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to print messages after make done with cmake?

 July 12, 2022     build, cmake, makefile, message, post     No comments   

Issue

I'm trying to print messages after building process done using CMake.

I just want to inform the user after make command is done without any error.

How can I do it? I tried add_custom_target() but I cannot choose when to run.

Also, I tried add_custom_command(), again it doesn't give me the right result.

Any idea?

Thank you for your idea in advance.


Solution

You could, indeed, do the following:

add_custom_target( FinalMessage ALL
    ${CMAKE_COMMAND} -E cmake_echo_color --cyan "Compilation is over!"
    COMMENT "Final Message" )
add_dependencies( FinalMessage ${ALL_TARGETS} )

That custom target depending on the list of all the targets you previously defined, you make sure it will be run last.



Answered By - xStan
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I model this behavior in Django?

 July 12, 2022     django, forms, message, model, python     No comments   

Issue

I want to develop a notification system with Django. So I have an button (and a count of unread messages), that show all messages to the user, so the counter returns to zero again. How can detect my database, that the user already has read the messages and reset the counter? I dont think that I can emulate this with forms, isn't it?


Solution

You should have a look at the django-notifications package: https://github.com/django-notifications/django-notifications

It does exactly what you want. It also comes with a Live Updater Api to keep the unread notification number in sync.



Answered By - ilse2005
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] why am i unable to create a successful message loop with PeekMessage()?

 July 12, 2022     loops, message, winapi     No comments   

Issue

My guess it's somehow receiving a WM_QUIT message, because that is what the while loop revolves around ( which according to the proc function happens whenever a WM_DESTROY message is processed)

The window automatically closes whenever i use PeekMessage instead of GetMessage , Im using PeekMessage in order to run the loop at maximum speed

int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
if(!CreateMainWindow(hinstance, nCmdShow))
   return false;
//this works
while (GetMessage(&msg, (HWND) NULL, 0 , 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
return (int) msg.wParam;
    UNREFERENCED_PARAMETER(lpCmdLine);
}    

//this automatically closes the window
int done = 0;
while (!done)
{
    if (PeekMessage (&msg, NULL, 0 ,0, PM_REMOVE))
    {

        if (msg.message = WM_QUIT)
            done = 1;
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}
return msg.wParam;
    UNREFERENCED_PARAMETER(lpCmdLine);

here's the simple WinProc function

LRESULT CALLBACK WinProc ( HWND hWnd, UINT msg, WPARAM wParam, LPARAM   
lParam)
{
switch( msg)
{
      Case WM_DESTROY: 
      PostQuitMessage(0);
      return 0;
}
return DefWindowProc ( hWnd, msg, wParam, lParam);
}

Solution

You are assigning WM_QUIT to msg.message instead of comparing it.



Answered By - Ton Plooij
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to show unread message count on app icon

 July 12, 2022     android, android-layout, message     No comments   

Issue

In my application I have some options, one is my messages, I need to show the unread count on that icon. How to show?


Solution

How to display count of notifications in app launcher icon

It has already disgussed.

https://github.com/leolin310148/ShortcutBadger

Check this library out.

Edit: https://stackoverflow.com/a/25453979/5073666



Answered By - Burak Uyar
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to stream a file download and display a JSF faces message?

 July 12, 2022     download, jsf, jsf-2, message     No comments   

Issue

We are streaming a binary file to our users, following the procedure elaborated in the SO question How to provide a file download from a JSF backing bean?

In general the workflow works as intended, but during the generation of the export file recoverable errors may occur and we want to display these as a warning to the user. The file itself shall still be generated in that case. So we want that export to continue and display faces messages.

Just to put emphasis on this: Yes, there is something not OK with the data, but our users want the export to continue and receive that flawed file anyway. Then they want to have a look at the file, contact their vendor and send him a message about the flaw.

So I need the export to finish in any case.

But it does not work out as we want it to. I have created a simplified example to illustrate our approach.

As alternative we are considering a Bean that will be hold the messages and display them after the export. But probably there is a way with JSF built-in mechanisms to achieve this.

Controller

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.apache.tomcat.util.http.fileupload.util.Streams;

@ManagedBean
@RequestScoped
public class ExportController {

    public void export() {
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();

        byte[] exportContent = "Hy Buddys, thanks for the help!".getBytes();
        // here something bad happens that the user should know about
        // but this message does not go out to the user
        fc.addMessage(null, new FacesMessage("record 2 was flawed"));

        ec.responseReset();
        ec.setResponseContentType("text/plain");
        ec.setResponseContentLength(exportContent.length);
        String attachmentName = "attachment; filename=\"export.txt\"";
        ec.setResponseHeader("Content-Disposition", attachmentName);
        try {
            OutputStream output = ec.getResponseOutputStream();
            Streams.copy(new ByteArrayInputStream(exportContent), output, false);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        fc.responseComplete();
    }
}

JSF Page

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">

    <f:view contentType="text/html">
        <h:body>
            <h:form prependId="false">
                <h:messages id="messages" />
                <h:commandButton id="download" value="Download"
                                 actionListener="#{exportController.export()}" />
            </h:form>
        </h:body>
    </f:view>
</html>

Solution

Since you're actually performing a file download response and not a JSF one, it's not possible for your message to be added while the same request happens. The most clean solution for me, avoiding hacky asynchronous requests is to use a @ViewScoped bean and do your task in two steps. So, to have a button for preparing your file, notifying the user later on and allowing him to download it when it's ready:

@ManagedBean
@ViewScoped
public class ExportController implements Serializable {

    private byte[] exportContent;

    public boolean isReady() {
        return exportContent != null;
    }

    public void export() {
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
        ec.responseReset();
        ec.setResponseContentType("text/plain");
        ec.setResponseContentLength(exportContent.length);
        String attachmentName = "attachment; filename=\"export.txt\"";
        ec.setResponseHeader("Content-Disposition", attachmentName);
        try {
            OutputStream output = ec.getResponseOutputStream();
            Streams.copy(new ByteArrayInputStream(exportContent), output, false);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        fc.responseComplete();
    }

    public void prepareFile() {
        exportContent = "Hy Buddys, thanks for the help!".getBytes();
        // here something bad happens that the user should know about
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage("record 2 was flawed"));
    }
}
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">

<f:view contentType="text/html">
    <h:body>
        <h:form>
            <h:messages id="messages" />
            <h:commandButton value="Prepare"
                action="#{exportController.prepareFile}" />
            <h:commandButton id="download" value="Download"
                disabled="#{not exportController.ready}"
                action="#{exportController.export()}" />
        </h:form>
    </h:body>
</f:view>
</html>

Note this solution could be valid for small files (their entire content is stored in memory while user keeps in the same view). However, if you're going to use it with large files (or large number of users) your best is to store its content in a temporary file and display a link to it instead of a download button. That's what @BalusC suggests in the reference below.

See also:

  • File download from JSF with a rendered response


Answered By - Aritz
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing