hi i'm using mapbox to display map in android app. I'm stuck in a situation where I need to get radius of a map that is visible to the user. if user zoomin or zoomout the radius of the map changes. Can anyone tell me how do I do this. or suggest me any reference link regarding this

I am learning to develop android mobile apps. I made a simple app to send a sms. I am using the ADB emulator running marshmallow. I have read about it new permissions here and found lots of questions with answers to my problem with no resolve.

When I do a CLEAN and BUILD I am greeted with the following message:

Error:Gradle: java.io.FileNotFoundException: C:Examples\MySMSApplication\app\build\intermediates\res\resources-debug.ap_ (Access is denied)

Note: I am able to successfully build and run the app when I remove the "uses-permission android:name="android.permission.SEND_SMS". However, I will always get my message "Permission denied" when attempting to send a SMS to say another emulator number 5554.

I have the Android manifest with the two user-permissions set.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.fisher.app">
    <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/mysmsapp"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

Then in the mainActivity

public class MainActivity extends AppCompatActivity {

    Button buttonSend;
    EditText textPhoneNo;
    EditText textSMS;

    private static final int PERMISSION_REQUEST = 100;

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

        buttonSend = (Button) findViewById(R.id.buttonSend);
        textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
        textSMS = (EditText) findViewById(R.id.editTextSMS);

        buttonSend.setOnClickListener(new View.OnClickListener() {
            //this is the onclick listener of send button
            @Override
            public void onClick(View v) {
                String phoneNo = textPhoneNo.getText().toString();
                String sms = textSMS.getText().toString();

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                        if (shouldShowRequestPermissionRationale(Manifest.permission.SEND_SMS)) {
                            Snackbar.make(findViewById(R.id.myView), "You need to grant SEND SMS permission to send sms",
                                    Snackbar.LENGTH_LONG).setAction("OK", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    requestPermissions(new String[]{Manifest.permission.SEND_SMS}, PERMISSION_REQUEST);
                                }
                            }).show();
                        } else {
                            requestPermissions(new String[]{Manifest.permission.SEND_SMS}, PERMISSION_REQUEST);
                        }
                    } else {
                        sendSMS(phoneNo, sms);
                    }
                } else {
                    sendSMS(phoneNo, sms);
                }
            }
        });
    }

    private void sendSMS(String phoneNo, String message) {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNo, null, message, null, null);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            Snackbar.make(findViewById(R.id.myView), "Permission Granted",
                    Snackbar.LENGTH_LONG).show();
            sendSMS(textPhoneNo.getText().toString(), textSMS.getText().toString());

        } else {

            Snackbar.make(findViewById(R.id.MyView), "Permission denied",
                    Snackbar.LENGTH_LONG).show();

        }
    }
}

Here is the Gradle Build for ref:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.fisher.myapp"
        minSdkVersion 23
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.1.1'
}

Here is my code

1.Java Code

class makePOST extends AsyncTask<String, Void, Double> {
    int duration = Toast.LENGTH_SHORT;
    @Override
    protected void onPreExecute() {
        Toast.makeText(update.this, "onPreExecute", Toast.LENGTH_LONG).show();
    }
    protected Double doInBackground(String... params) {
            try {
                url = new URL("http://student.96.lt/Android/update.php");
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");
                String postdat = "code" + "=" + URLEncoder.encode(mCode, "UTF-8") + "&" + "latitude" + "=" + URLEncoder.encode(mLatitudeText, "UTF-8") + "&" + "longitude" + "=" + URLEncoder.encode(mLongitudeText, "UTF-8");
                //String postdat=mLatitudeText;
                conn.setFixedLengthStreamingMode(postdat.getBytes().length);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                OutputStream OS = conn.getOutputStream();
                InputStream in = conn.getInputStream();

                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                bufferedWriter.write(postdat);
                bufferedWriter.flush();
                // Get output
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");
                }

                in.close();
                bufferedWriter.close();
//            java.io.BufferedOutputStream out = new java.io.BufferedOutputStream(conn.getOutputStream());
//            PrintStream pstream = new PrintStream(out);
//            pstream.print(postdat);
//            pstream.close();
            } catch (java.net.MalformedURLException ex) {
                //Toast.makeText(this, ex.toString(), duration ).show();
            } catch (java.io.IOException ex) {
                //Toast.makeText(this, ex.toString(), duration).show();
            }
            return null;
        }

    };  

2. PHP Code(update.php)

<?php
include 'connect.php';
$m_lat=$_POST['latitude'];
$m_lng=$_POST['longitude'];
$m_code=$_POST['code'];
$query="update `location` set `longitude`='$m_lng',`latitude`='$m_lat' where `code`='$m_code'";
mysqli_query($connect,$query);
mysqli_close($connect);
?>

3. AndroidManifest.xml File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.project.nikhil.gpslocation">
<permission
    android:name="com.javapapers.currentlocationinmap.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.javapapers.currentlocationinmap.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <uses-feature
        android:name="android.hardware.location.gps"
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="MyKey" />
    <activity
        android:name=".update"
        android:label="@string/title_activity_update"
        android:exported="true"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

And I also want to update longitude and latitude every 10 seconds. This is my First app. I'm at beginning level of android development, Please help me !

Now My php code is working you can check this out at : student.96.lt/Android/test.php

I'm working with android crop image , this is my code for cropping image :

private void performCrop() {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        //indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        //set crop properties
        cropIntent.putExtra("crop", "true");
        //indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        //indicate output X and Y
        cropIntent.putExtra("outputX", 500);
        cropIntent.putExtra("outputY", 500);
        //retrieve data on return
        cropIntent.putExtra("return-data", true);
        //start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);
    } catch (ActivityNotFoundException anfe) {
        //display an error message
        String errorMessage = "err";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

I have tested this code on android 4.2 , 4.3 and the was no problem , but on android 5,6 , it's returning null pointer exception and I don't know why .

what is wrong with this code ? how can I make it compatible with all version of android ?

This code is for my splash screen Activity:

    @Override
    protected void onResume() {
    super.onResume();
    handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(intent);
        }
    }, 5000);
}

When I click the device back button ,MainActivity become finish and again SplashActivity comes to up,and again it's onResume method get call, problem is here that handler doesn't execute again and MainActivity doesn't start again after 5 second ! I want it execute again!

what's the problem and what should i do?

thanks for attention.

is there any action available to listen audio so that when I say my preset word like "good morning", it should launch my app. It means I want to make a broadcast receiver with the action define 'listen audio' as any one say "good morning" like "Ok google", my receiver should listen this and do my task.

Please help me that will be great. Thank you in advance.

I have ViewPager, couple of pages contain EditText fields. The task is to open soft keyboard on page with first EditText (phone number), after click on Done button switch to another page and set focus on second EditText (verification code). Keyboard must be always opened, EditText field must be above. On second page it got covered.

<android.support.percent.PercentFrameLayout
    android:id="@+id/verification"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/superup_logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        app:layout_marginTopPercent="33%"
        app:layout_widthPercent="65%"
        app:srcCompat="@drawable/animated_superup_logo_white"/>

    <superup.onboarding.NonSwipeableViewPager
        android:id="@+id/verifyPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/transition">

        <android.support.percent.PercentRelativeLayout
            android:id="@+id/layout_start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <android.support.v7.widget.AppCompatImageView
                android:id="@+id/superup_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                app:layout_marginTopPercent="67%"
                app:layout_widthPercent="50%"
                app:srcCompat="@drawable/superup_name"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/superup_name"
                android:layout_centerHorizontal="true"
                android:text="@string/layout_start_text"
                android:textColor="@color/white"
                android:textSize="18dp"
                android:textStyle="bold"/>

        </android.support.percent.PercentRelativeLayout>

        <android.support.percent.PercentRelativeLayout
            android:id="@+id/layout_number"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layoutDirection="ltr">

            <TextView
                android:id="@+id/txt_number"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:text="@string/layout_number_text"
                android:textColor="@color/white"
                android:textSize="18dp"
                android:textStyle="bold"
                app:layout_marginTopPercent="3%"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                app:layout_marginBottomPercent="23%"
                app:layout_widthPercent="75%">

                <superup.onboarding.CountryCodePicker
                    android:id="@+id/country_code"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:contentColor="@color/white"
                    app:countryPreference="IL"
                    app:defaultNameCode="IL"
                    app:hideNameCode="true"
                    app:textSize="24sp"/>

                <EditText
                    android:id="@+id/et_number"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:digits="1234567890"
                    android:gravity="center"
                    android:imeOptions="actionDone"
                    android:inputType="number"
                    android:maxLength="10"
                    android:textColor="@color/white"
                    android:textSize="24sp"/>
            </LinearLayout>

        </android.support.percent.PercentRelativeLayout>

        <android.support.percent.PercentRelativeLayout
            android:id="@+id/layout_otp"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <superup.onboarding.PinEntryEditText
                android:id="@+id/et_code"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:cursorVisible="false"
                android:digits="1234567890"
                android:imeOptions="actionDone"
                android:inputType="number"
                android:maxLength="4"
                android:textIsSelectable="false"
                android:textSize="50dp"
                android:textStyle="bold"
                app:layout_marginBottomPercent="23%"
                app:layout_marginLeftPercent="20%"
                app:layout_marginRightPercent="20%"/>

            <TextView
                android:id="@+id/txt_wrong"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/et_code"
                android:layout_centerHorizontal="true"
                android:padding="10dp"
                android:text="@string/wrong_number"
                android:textColor="@color/white"
                android:textSize="16dp"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/txt_phone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/txt_wrong"
                android:layout_centerHorizontal="true"
                android:layoutDirection="ltr"
                android:textColor="@color/white"
                android:textSize="20dp"
                android:textStyle="bold"/>

        </android.support.percent.PercentRelativeLayout>

    </superup.onboarding.NonSwipeableViewPager>

</android.support.percent.PercentFrameLayout>

With page swipe it works perfect, but i need to switch pages with keyboard. After changing page with verifyPager.setCurrentItem EditText is covered with keyboard over it.

et_number.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            switch (actionId) {
                case EditorInfo.IME_ACTION_DONE:
                    verifyPager.setCurrentItem(verifyPager.getChildCount() - 1);
                    return true;
                default:
                    return false;
            }
        }
    });

Samsung with Android 6 has this bug, Nexus 5X/6P/Asus don't.

I have a wordpress woocommerce site and an android mobile app. I want to integrate wordpress site and android app. I want to login and register from android app into wordpress site. then I also sell product by this app.

I'm trying to develop a service that whenever an user opens an app my service will identify it. I'm using the files: /proc/[pid]/cgroup,/proc/[pid]/cmdline,/proc/[pid]/oom_score,/proc/[pid]/oom_score_adj to check if it's an user app running on foreground. Actually it's working but when I try to open any game the service won't recognize it all the time. (The service only identify the files (oom_score) that has the lowest value).

Example: oom_score for "com.google.android.googlequicksearchbox:interactor" is 75, but for "com.king.candycrushsaga" will be >150, so it will never be detected by the code (as it follows).

Service code:

scheduler.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        s=appManager.getAppRunningForeground();
        System.out.println(s);
    }
},1,2,SECONDS);

Function that gets the app running:

private ReadWriteFile readWriteFile = new ReadWriteFile();
public String getAppRunningForeground(){
    int pid;
    File[] files = new File("/proc").listFiles();
    int lowestOomScore = Integer.MAX_VALUE;
    String foregroundProcess = null;
    for (File file : files) {
        if (!file.isDirectory() || (!file.getName().matches(("\\d+"))))
            continue;
        pid = Integer.parseInt(file.getName());
        try {
            String cgroup = readWriteFile.read(String.format("/proc/%d/cgroup", pid));
            String[] lines = cgroup.split("\n");
            if (lines.length != 2)
                continue;
            String cpuSubsystem = lines[0];
            String cpuaccctSubsystem = lines[1];
            if (!cpuaccctSubsystem.endsWith(Integer.toString(pid)) || cpuSubsystem.endsWith("bg_non_interactive"))
                continue;
            String cmdline = readWriteFile.read(String.format("/proc/%d/cmdline", pid));
            if (cmdline.contains("com.android.systemui")||cmdline.contains("com.google.android.googlequicksearchbox:interactor")) {
                continue;
            }
            int uid = Integer.parseInt(cpuaccctSubsystem.split(":")[2].split("/")[1].replace("uid_", ""));
            if (uid > 1000 && uid <= 1038)//System process
                continue;
            File oomScoreAdj = new File(String.format("/proc/%d/oom_score_adj", pid));
            if (oomScoreAdj.canRead()) {
                int oomAdj = Integer.parseInt(readWriteFile.read(oomScoreAdj.getAbsolutePath()));
                if (oomAdj != 0) {
                    continue;
                }
            }
            int oomscore = Integer.parseInt(readWriteFile.read(String.format("/proc/%d/oom_score", pid)));
            if (oomscore < lowestOomScore) {
                lowestOomScore = oomscore;
                foregroundProcess = cmdline.replaceAll("\\p{Cntrl}", "");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return foregroundProcess;
}

Class that reads a file.

public class ReadWriteFile{
    File file;
    StringBuilder teste3 = new StringBuilder();
    FileOutputStream outputStream;
    public static String read(String path) throws IOException {
        StringBuilder output = new StringBuilder();
        BufferedReader reader = new BufferedReader(new FileReader(path));
        output.append(reader.readLine());
        for (String line = reader.readLine(); line != null; line = reader.readLine())
            output.append('\n').append(line);
        reader.close();
        return output.toString();
    }
}

P.S: getRunningTasks is deprecated, so please, don't suggest it.

I just wanna know when jvm runs test cases is that they generate .class files for it in both simple java program or android program.

We are working on android application,in which mp3 files should be downloaded into internal storage in a background service. We have implemented this using with code snippet mentioned below inside an intentservice,But when we try to play the mp3 we are getting an error,like player is not supporting this audio file. If any one has a solution for this issue,Please advise me for the same.

Code Snippet:

String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
//  String fileName = Environment.getExternalStorageDirectory().toString() + "/trail.mp3";
File output = new File(Environment.getExternalStorageDirectory(), fileName);

File dir = new File(output.getAbsolutePath() + "/TRIALS/");

dir.mkdirs();
String path = dir + "/" +"trail" + ".mp3";
File f = new File(path);

if (f.exists()) {
    f.delete();
}

InputStream stream = null;
FileOutputStream fos = null;
try {
    URL url = new URL(urlPath);
    URLConnection conection = url.openConnection();
    conection.connect();
    // getting file length
    int lenghtOfFile = conection.getContentLength();
    // URL url = new URL(urlPath);
    InputStream input = new BufferedInputStream(url.openStream());

    stream = url.openConnection().getInputStream();
    InputStreamReader reader = new InputStreamReader(stream);
    fos = new FileOutputStream(f.getPath());

    byte data[] = new byte[lenghtOfFile];

    long total = 0;

    int times = -1;
    while ((times = reader.read()) != -1) {
        fos.write(times);
    }
    // Successful finished
    result = Activity.RESULT_OK;

} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (stream != null) {
        try {
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

publishResults(output.getAbsolutePath(), result);

I'm following the tutorial of firebase. But I canĀ“t add the rules .read and .write

enter image description here enter image description here

I am creating an android program. In this program, i have a ScrollView inside which there is a Recycler view. I am adding data in this recycler view via RecyclerViewAdapter.

For each item of RecyclerView, there is a NestedScrollview having a single LinearLayout of verticle orientation. I am dynamically adding ImageView in this linear layout.

The problem is the images are not scrolling. In very rare scenario(by tapping so many times on screen), it got scrolled for a once.

Could any buddy help me on this.

Thanks!

I need to adjust sharpness sharpness ,brightness and Contrast of an image . I am not getting proper output . I follow this Sharpness,brightness,contrast.but i am not getting proper oupput in case of sharpness. There are any library can adjust image sharpness ,brightness and Contrast in android .

I would like to develop an android app's UI looks like the Uber's but booking rooms.

I want to implement the function about showing the option's description, from users who are clicking the PagerSlidingTabStrip items which shown on the bottom. The fragment page will be shown when the user click the fragment tab (PagerSlidingTabStrip), also the chosen option will be selected.

I feel puzzled and confused when I am implementing this function, and concern the pagerSlidingTabStrip can trigger events by setOnClickListner or not. Also I don't willing to show the fragment page on the main page once users logged on the page by default.

Thank you.

Main Page Layout

Layout after clicking the PagerSlidingTabStrip's option

My application closes every time I try to see the images. Can you explain why?

I think maybe the problem is the string Glide.with(getApplicationContext()), maybe it isn't correct. But for Android Studio I don't have errors:

All other elements are ok, the problem is only glide.

public class MainActivity extends AppCompatActivity {

    private final String url= "MY ARRAY";
    ...

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
        new gson().execute(url);
    }

    public class gson extends AsyncTask<String,String, List<MovieModel> >{

    ....
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    ....
            Glide.with(getApplicationContext())
                    .load(imageurl)
                    .listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            progressBar.setVisibility(View.GONE);
                            return false;
                        }
                    })
                    .into(imageView);
            }
        }
    }

Need to retrieve all of the text messages from Amy. I have used iPhone 5 guidebook and have not from any directions on finding deleted conversation.

I believe, in Python defaultdict inherited from dict violates Liskov Substitution Principle. defaultdict doesn't raise KeyError while x in d is still False, for instance.

Is that so? If it is, why developer decided to make such a sacrifice?

In the context of MVC sometimes I find myself creating a Factory and injecting the factory with Repository.

While it is certainly possible to use Repository as layer inside the Factory, I wonder if it is an anti-pattern to do so. i.e. is it advisable to keep Factory Repository-free?

Example

For example, my QuoteFactory class is tasked with

  • creating Quote class
  • maintaining Repository methods & generally being Repository-aware

Code

$repository = new QuoteRepository(111);
$factory = new QuoteFactory($repository);    
$quote = $factory->loadQuote();

class QuoteRepository
{
    function __construct($id)
    {
        $this->id = $id;
        $this->em = DoctrineConnector::getEntityManager();
    }

    function getLineItems()
    {
        $query = $this->em->createQuery('SELECT s FROM...');
        return $query->getResult();
    }
}

class QuoteFactory
{
    function __construct(QuoteRepository $repository)
    {
        $this->repository = $repository;
    }

    function loadQuote()
    {
        $quote = new Quote();
        $quote->setLines($this->repository->getLineItems());
        return $quote;
    }
}

class Quote
{    
    function setLines(array $lines)
    {
        $this->lines = $lines;
    }
}

i'm attempting to execute a C# program to write to an Azure DocumentDB database. However, I'm very new to C# and am not sure how to get the main() entry to execute CreateDocument() call. Here is the code that I'm using. Any help would be greatly appreciated.

  namespace MyFirstDocDbApp
{
    class Program
    {
        static void Main(string[] args)
        {
           // CreateDocument();
         }

        public const string EndpointUri = "<Uri>";
        public const string PrimaryKey = "<key>";

        public static async Task CreateDocument()
        {
            //attach to DocumentDB using the URI and Key from the Azure portal
            DocumentClient client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);
            //query for the right database inside the DocDB account
            Database database = client.CreateDatabaseQuery().Where(d => d.Id == "SchoolDB").AsEnumerable().FirstOrDefault();
            //find the right collection where we want to add the document
            DocumentCollection collection = client.CreateDocumentCollectionQuery((String)database.SelfLink).
                ToList().Where(cl => cl.Id.Equals("Collect1")).FirstOrDefault();
            //create a simple document in the collection by providing the DocumentsLink and the object to be serialized
            //and stored
            await client.CreateDocumentAsync(
              collection.DocumentsLink,
              new PersonInformation
              {
                  FirstName = "Riccardo",
                  LastName = "Becker",
                  DateOfBirth = new DateTime(1974, 12, 21)
              }
            );
        }

tl;dr-ers:

How does a lexer normally deal with none-inline statements. statements that do not end with a specified statement delimiter. Such as control flow statements?


I believe that I have a fairly good grasp on lexical analysis, and can move on in my quest for understanding lexers/parsers. I do however, understand how lexers deal with 1multi-line statements.

After reading a Wikipedia article on the Comparison of programming languages syntax, The thing that all languages have in common, is that they have a very specfic statement delimeter. Some used semicolons(;) as a statement delimiter, others use whitespace(\ws), and some used periods(.).

Using this method, i fail to see how those programming languages, are able to have functions\class\control flow, that span multiple lines. Correct me if I'm wrong, but I'm pretty sure that most of the popular programming languages(Python, Java, C, C++, C#, Javascript, etc...) Do not use their statement delimiters at the end of functions, or classes(I know that classes in C++ do use semicolons at there end, but that is besides the point), or control flow.

This means that either: A: Lexers make a special exception for statements that span multiple lines. Or B: The lexer just treats multi-line statements as a regular statement, and it is the parser's job to make sense of them.

For example, Take take this pseudo program in C++:

int exampleVar; //<-- inline statement. Delimited with a semicolon

void exampleFunc() { //<-- multi-line statement. This statement is the start of a block.
    // do things
} //<-- this is where the statement that was started above, should end?

Clearly, it's easy to see where you should end the first statement. You end it at the semicolon. But how is the second statement dealt with? Is the statement extend to include everything up until the closing curly brace?

Or I could just be misguided in my thinking. It could be that the lexer has absolutely nothing to to do with 1multi-line statements. Is this the job of the parser? That is, is it the parser's job to make sense of 1multi-line statements?

To as clear as possible, my question is: How(if they should in the first place), should a lexer deal with statements that are not inline, and cannot just be terminated as if they were. How does a lexer normally deal with none-inline statements. statements that do not end with a specified statement delimiter. Such as control flow statements?

1To be clear, I do not mean multi-line statements, in the sense of line continuation. I mean them in the sense of statements that start off a block. Such as a function declaration. When you're defining a function, you also need to know the statements that follow the function definition up to a certain block delimiter. So you can't just terminate the statement after the definition.