text:
Q: how to extract zip file content into sd card? i want to extract my .obb file contents which contain zip file for .zim file and want to extract these files into my sd card. how can I do that I tried the following way with java helperclass?
Is that correct?
   public class MainActivity extends Activity implements IDownloaderClient {
    private static final String LOG_TAG = "LVLDownloader";
    private ProgressBar mPB;

    private TextView mStatusText;
    private TextView mProgressFraction;
    private TextView mProgressPercent;
    private TextView mAverageSpeed;
    private TextView mTimeRemaining;

    private View mDashboard;
    private View mCellMessage;

    private Button mPauseButton;
    private Button mWiFiSettingsButton;

    private boolean mStatePaused;
    private int mState;

    private IDownloaderService mRemoteService;

    private IStub mDownloaderClientStub;

    private void setState(int newState) {
        if (mState != newState) {
            mState = newState;
            mStatusText.setText(Helpers.getDownloaderStringResourceIDFromState(newState));
        }
    }

    private void setButtonPausedState(boolean paused) {
        mStatePaused = paused;
        int stringResourceID = paused ? R.string.text_button_resume :
                R.string.text_button_pause;
        mPauseButton.setText(stringResourceID);
    }

    /**
     * This is a little helper class that demonstrates simple testing of an
     * Expansion APK file delivered by Market. You may not wish to hard-code
     * things such as file lengths into your executable... and you may wish to
     * turn this code off during application development.
     */
    private static class XAPKFile {
        public final boolean mIsMain;
        public final int mFileVersion;
        public final long mFileSize;

        XAPKFile(boolean isMain, int fileVersion, long fileSize) {
            mIsMain = isMain;
            mFileVersion = fileVersion;
            mFileSize = fileSize;
        }
    }

    /**
     * Here is where you place the data that the validator will use to determine
     * if the file was delivered correctly. This is encoded in the source code
     * so the application can easily determine whether the file has been
     * properly delivered without having to talk to the server. If the
     * application is using LVL for licensing, it may make sense to eliminate
     * these checks and to just rely on the server.
     */
    private static final XAPKFile[] xAPKS = {
            new XAPKFile(
                    true, // true signifies a main file
                    4, // the version of the APK that the file was uploaded
                       // against
                    240000L // the length of the file in bytes
            ),
            new XAPKFile(
                    true, // false signifies a patch file
                    3, // the version of the APK that the patch file was uploaded
                       // against
                    24000L // the length of the patch file in bytes
            )
    };

    /**
     * Go through each of the APK Expansion files defined in the structure above
     * and determine if the files are present and match the required size. Free
     * applications should definitely consider doing this, as this allows the
     * application to be launched for the first time without having a network
     * connection present. Paid applications that use LVL should probably do at
     * least one LVL check that requires the network to be present, so this is
     * not as necessary.
     *
     * @return true if they are present.
     */
    boolean expansionFilesDelivered() {
        for (XAPKFile xf : xAPKS) {
            String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsMain, xf.mFileVersion);
            if (!Helpers.doesFileExist(this, fileName, xf.mFileSize, false))
                return false;
        }
        return true;
    }

    /**
     * Calculating a moving average for the validation speed so we don't get
     * jumpy calculations for time etc.
     */
    static private final float SMOOTHING_FACTOR = 0.005f;

    /**
     * Used by the async task
     */
    private boolean mCancelValidation;

    /**
     * Go through each of the Expansion APK files and open each as a zip file.
     * Calculate the CRC for each file and return false if any fail to match.
     *
     * @return true if XAPKZipFile is successful
     */
    void validateXAPKZipFiles() {
        AsyncTask<Object, DownloadProgressInfo, Boolean> validationTask = new AsyncTask<Object, DownloadProgressInfo, Boolean>() {

            @Override
            protected void onPreExecute() {
                mDashboard.setVisibility(View.VISIBLE);
                mCellMessage.setVisibility(View.GONE);
                mStatusText.setText(R.string.text_verifying_download);
                mPauseButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mCancelValidation = true;
                    }
                });
                mPauseButton.setText(R.string.text_button_cancel_verify);
                super.onPreExecute();
            }

            @Override
            protected Boolean doInBackground(Object... params) {
                for (XAPKFile xf : xAPKS) {
                    String fileName = Helpers.getExpansionAPKFileName(
                            MainActivity.this,
                            xf.mIsMain, xf.mFileVersion);
                    if (!Helpers.doesFileExist(MainActivity.this, fileName,
                            xf.mFileSize, false))
                        return false;
                    fileName = Helpers
                            .generateSaveFileName(MainActivity.this, fileName);
                    ZipResourceFile zrf;
                    byte[] buf = new byte[1024 * 256];
                    try {
                        zrf = new ZipResourceFile(fileName);
                        ZipEntryRO[] entries = zrf.getAllEntries();
                        /**
                         * First calculate the total compressed length
                         */
                        long totalCompressedLength = 0;
                        for (ZipEntryRO entry : entries) {
                            totalCompressedLength += entry.mCompressedLength;
                        }
                        float averageVerifySpeed = 0;
                        long totalBytesRemaining = totalCompressedLength;
                        long timeRemaining;
                        /**
                         * Then calculate a CRC for every file in the Zip file,
                         * comparing it to what is stored in the Zip directory.
                         * Note that for compressed Zip files we must extract
                         * the contents to do this comparison.
                         */
                        for (ZipEntryRO entry : entries) {
                            if (-1 != entry.mCRC32) {
                                long length = entry.mUncompressedLength;
                                CRC32 crc = new CRC32();
                                DataInputStream dis = null;
                                try {
                                    dis = new DataInputStream(
                                            zrf.getInputStream(entry.mFileName));

                                    long startTime = SystemClock.uptimeMillis();
                                    while (length > 0) {
                                        int seek = (int) (length > buf.length ? buf.length
                                                : length);
                                        dis.readFully(buf, 0, seek);
                                        crc.update(buf, 0, seek);
                                        length -= seek;
                                        long currentTime = SystemClock.uptimeMillis();
                                        long timePassed = currentTime - startTime;
                                        if (timePassed > 0) {
                                            float currentSpeedSample = (float) seek
                                                    / (float) timePassed;
                                            if (0 != averageVerifySpeed) {
                                                averageVerifySpeed = SMOOTHING_FACTOR
                                                        * currentSpeedSample
                                                        + (1 - SMOOTHING_FACTOR)
                                                        * averageVerifySpeed;
                                            } else {
                                                averageVerifySpeed = currentSpeedSample;
                                            }
                                            totalBytesRemaining -= seek;
                                            timeRemaining = (long) (totalBytesRemaining / averageVerifySpeed);
                                            this.publishProgress(
                                                    new DownloadProgressInfo(
                                                            totalCompressedLength,
                                                            totalCompressedLength
                                                                    - totalBytesRemaining,
                                                            timeRemaining,
                                                            averageVerifySpeed)
                                                    );
                                        }
                                        startTime = currentTime;
                                        if (mCancelValidation)
                                            return true;
                                    }
                                    if (crc.getValue() != entry.mCRC32) {
                                        Log.e(Constants.TAG,
                                                "CRC does not match for entry: "
                                                        + entry.mFileName);
                                        Log.e(Constants.TAG,
                                                "In file: " + entry.getZipFileName());
                                        return false;
                                    }
                                } finally {
                                    if (null != dis) {
                                        dis.close();
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                return true;
            }

            @Override
            protected void onProgressUpdate(DownloadProgressInfo... values) {
                onDownloadProgress(values[0]);
                super.onProgressUpdate(values);
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (result) {
                    mDashboard.setVisibility(View.VISIBLE);
                    mCellMessage.setVisibility(View.GONE);
                    mStatusText.setText(R.string.text_validation_complete);
                    mPauseButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            finish();
                        }
                    });
                    mPauseButton.setText(android.R.string.ok);
                } else {
                    mDashboard.setVisibility(View.VISIBLE);
                    mCellMessage.setVisibility(View.GONE);
                    mStatusText.setText(R.string.text_validation_failed);
                    mPauseButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            finish();
                        }
                    });
                    mPauseButton.setText(android.R.string.cancel);
                }
                super.onPostExecute(result);
            }

        };
        validationTask.execute(new Object());
    }

    /**
     * If the download isn't present, we initialize the download UI. This ties
     * all of the controls into the remote service calls.
     */
    private void initializeDownloadUI() {
        mDownloaderClientStub = DownloaderClientMarshaller.CreateStub
                (this, ExpansionFileDownloaderService.class);
        setContentView(R.layout.activity_main);

        mPB = (ProgressBar) findViewById(R.id.progressBar);
        mStatusText = (TextView) findViewById(R.id.statusText);
        mProgressFraction = (TextView) findViewById(R.id.progressAsFraction);
        mProgressPercent = (TextView) findViewById(R.id.progressAsPercentage);
        mAverageSpeed = (TextView) findViewById(R.id.progressAverageSpeed);
        mTimeRemaining = (TextView) findViewById(R.id.progressTimeRemaining);
        mDashboard = findViewById(R.id.downloaderDashboard);
        mCellMessage = findViewById(R.id.approveCellular);
        mPauseButton = (Button) findViewById(R.id.pauseButton);
        mWiFiSettingsButton = (Button) findViewById(R.id.wifiSettingsButton);

        mPauseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mStatePaused) {
                    mRemoteService.requestContinueDownload();
                } else {
                    mRemoteService.requestPauseDownload();
                }
                setButtonPausedState(!mStatePaused);
            }
        });

        mWiFiSettingsButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            }
        });

        Button resumeOnCell = (Button) findViewById(R.id.resumeOverCellular);
        resumeOnCell.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRemoteService.setDownloadFlags(IDownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR);
                mRemoteService.requestContinueDownload();
                mCellMessage.setVisibility(View.GONE);
            }
        });

    }

    /**
     * Called when the activity is first create; we wouldn't create a layout in
     * the case where we have the file and are moving to another activity
     * without downloading.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /**
         * Both downloading and validation make use of the "download" UI
         */
        initializeDownloadUI();

        /**
         * Before we do anything, are the files we expect already here and
         * delivered (presumably by Market) For free titles, this is probably
         * worth doing. (so no Market request is necessary)
         */
        if (!expansionFilesDelivered()) {

            try {
                Intent launchIntent = MainActivity.this
                        .getIntent();
                Intent intentToLaunchThisActivityFromNotification = new Intent(
                        MainActivity
                        .this, MainActivity.this.getClass());
                intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                        Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());

                if (launchIntent.getCategories() != null) {
                    for (String category : launchIntent.getCategories()) {
                        intentToLaunchThisActivityFromNotification.addCategory(category);
                    }
                }

                // Build PendingIntent used to open this activity from
                // Notification
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        MainActivity.this,
                        0, intentToLaunchThisActivityFromNotification,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                // Request to start the download
                int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
                        pendingIntent, ExpansionFileDownloaderService.class);

                if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
                    // The DownloaderService has started downloading the files,
                    // show progress
                    initializeDownloadUI();
                    return;
                } // otherwise, download not needed so we fall through to
                  // starting the movie
            } catch (NameNotFoundException e) {
                Log.e(LOG_TAG, "Cannot find own package! MAYDAY!");
                e.printStackTrace();
            }

        } else {
            validateXAPKZipFiles();
        }

    }

    /**
     * Connect the stub to our service on start.
     */
    @Override
    protected void onStart() {
        if (null != mDownloaderClientStub) {
            mDownloaderClientStub.connect(this);
        }
        super.onStart();
    }

    /**
     * Disconnect the stub from our service on stop
     */
    @Override
    protected void onStop() {
        if (null != mDownloaderClientStub) {
            mDownloaderClientStub.disconnect(this);
        }
        super.onStop();
    }

    /**
     * Critical implementation detail. In onServiceConnected we create the
     * remote service and marshaler. This is how we pass the client information
     * back to the service so the client can be properly notified of changes. We
     * must do this every time we reconnect to the service.
     */
    @Override
    public void onServiceConnected(Messenger m) {
        mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
        mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
    }

    /**
     * The download state should trigger changes in the UI --- it may be useful
     * to show the state as being indeterminate at times. This sample can be
     * considered a guideline.
     */
    @Override
    public void onDownloadStateChanged(int newState) {
        setState(newState);
        boolean showDashboard = true;
        boolean showCellMessage = false;
        boolean paused;
        boolean indeterminate;
        switch (newState) {
            case IDownloaderClient.STATE_IDLE:
                // STATE_IDLE means the service is listening, so it's
                // safe to start making calls via mRemoteService.
                paused = false;
                indeterminate = true;
                break;
            case IDownloaderClient.STATE_CONNECTING:
            case IDownloaderClient.STATE_FETCHING_URL:
                showDashboard = true;
                paused = false;
                indeterminate = true;
                break;
            case IDownloaderClient.STATE_DOWNLOADING:
                paused = false;
                showDashboard = true;
                indeterminate = false;
                break;

            case IDownloaderClient.STATE_FAILED_CANCELED:
            case IDownloaderClient.STATE_FAILED:
            case IDownloaderClient.STATE_FAILED_FETCHING_URL:
            case IDownloaderClient.STATE_FAILED_UNLICENSED:
                paused = true;
                showDashboard = false;
                indeterminate = false;
                break;
            case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION:
            case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
                showDashboard = false;
                paused = true;
                indeterminate = false;
                showCellMessage = true;
                break;

            case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
                paused = true;
                indeterminate = false;
                break;
            case IDownloaderClient.STATE_PAUSED_ROAMING:
            case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE:
                paused = true;
                indeterminate = false;
                break;
            case IDownloaderClient.STATE_COMPLETED:
                showDashboard = false;
                paused = false;
                indeterminate = false;
                validateXAPKZipFiles();
                return;
            default:
                paused = true;
                indeterminate = true;
                showDashboard = true;
        }
        int newDashboardVisibility = showDashboard ? View.VISIBLE : View.GONE;
        if (mDashboard.getVisibility() != newDashboardVisibility) {
            mDashboard.setVisibility(newDashboardVisibility);
        }
        int cellMessageVisibility = showCellMessage ? View.VISIBLE : View.GONE;
        if (mCellMessage.getVisibility() != cellMessageVisibility) {
            mCellMessage.setVisibility(cellMessageVisibility);
        }

        mPB.setIndeterminate(indeterminate);
        setButtonPausedState(paused);
    }

    /**
     * Sets the state of the various controls based on the progressinfo object
     * sent from the downloader service.
     */
    @Override
    public void onDownloadProgress(DownloadProgressInfo progress) {
        mAverageSpeed.setText(getString(R.string.kilobytes_per_second,
                Helpers.getSpeedString(progress.mCurrentSpeed)));
        mTimeRemaining.setText(getString(R.string.time_remaining,
                Helpers.getTimeRemaining(progress.mTimeRemaining)));

        progress.mOverallTotal = progress.mOverallTotal;
        mPB.setMax((int) (progress.mOverallTotal >> 8));
        mPB.setProgress((int) (progress.mOverallProgress >> 8));
        mProgressPercent.setText(Long.toString(progress.mOverallProgress
                * 100 /
                progress.mOverallTotal) + "%");
        mProgressFraction.setText(Helpers.getDownloadProgressString
                (progress.mOverallProgress,
                        progress.mOverallTotal));

    try {
        ZipResourceFile expansionFile = APKExpansionSupport
                .getAPKExpansionZipFile(this, 4, 0);

        ZipEntryRO[] zip = expansionFile.getAllEntries();
        Log.e("", "zip[0].isUncompressed() : " + zip[0].isUncompressed());
        Log.e("",
                "mFile.getAbsolutePath() : "
                        + zip[0].mFile.getAbsolutePath());
        Log.e("", "mFileName : " + zip[0].mFileName);
        Log.e("", "mZipFileName : " + zip[0].mZipFileName);
        Log.e("", "mCompressedLength : " + zip[0].mCompressedLength);

        File file = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "");
        ZipHelper.unzip(zip[0].mZipFileName, file);

        if (file.exists()) {
            Log.e("", "unzipped : " + file.getAbsolutePath());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

    @Override
    protected void onDestroy() {
        this.mCancelValidation = true;
        super.onDestroy();
    }

}

A: Use this helper class to unzip the obb
package com.example.dummy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.util.Log;

public class ZipHelper
{
boolean zipError=false;

public boolean isZipError() {
    return zipError;
}

public void setZipError(boolean zipError) {
    this.zipError = zipError;
}

public void unzip(String archive, File outputDir)
{
    try {
        ZipFile zipfile = new ZipFile(archive);
        //AvazAppActivity.printLog("TOTAL ZIP ENTRIES",zipfile.size()+":");
        for (Enumeration e = zipfile.entries(); e.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            unzipEntry(zipfile, entry, outputDir);

        }
    }
    catch (Exception e) {
        setZipError(true);
    }
}

private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException
{
    if (entry.isDirectory()) {
        createDirectory(new File(outputDir, entry.getName()));
        return;
    }

    File outputFile = new File(outputDir, entry.getName());
    if (!outputFile.getParentFile().exists()){
        createDirectory(outputFile.getParentFile());
    }

    //AvazAppActivity.printLog("control","ZipHelper.unzipEntry() - Extracting: " + entry);
    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

    try {
        copy(inputStream, outputStream);
    }
    catch (Exception e) {
        setZipError(true);
    }
    finally {
        outputStream.close();
        inputStream.close();
    }
}

private void createDirectory(File dir)
{
    if (!dir.exists()){
        if(!dir.mkdirs()) throw new RuntimeException("Can't create directory "+dir);
    }
    else
        Log.d("control","ZipHelper.createDir() - Exists directory: "+dir.getName());
}
private void copy(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}
}

In your class to unzip the obb use the below snippet.
ZipHelper helper = new ZipHelper();
File file = new File("/sdcard/Android/data/"+PACKAGE_NAME+"/");
helper.unzip("/sdcard/Android/obb/"+PACKAGE_NAME+"/main."+ versionCode + "."+PACKAGE_NAME+".obb", file);

this code will extract the obb content in data folder.

A:     try {
        ZipResourceFile expansionFile = APKExpansionSupport
                .getAPKExpansionZipFile(this, 4, 0);

        ZipEntryRO[] zip = expansionFile.getAllEntries();
        Log.e("", "zip[0].isUncompressed() : " + zip[0].isUncompressed());
        Log.e("",
                "mFile.getAbsolutePath() : "
                        + zip[0].mFile.getAbsolutePath());
        Log.e("", "mFileName : " + zip[0].mFileName);
        Log.e("", "mZipFileName : " + zip[0].mZipFileName);
        Log.e("", "mCompressedLength : " + zip[0].mCompressedLength);

        File file = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "");
        ZipHelper.unzip(zip[0].mZipFileName, file);

        if (file.exists()) {
            Log.e("", "unzipped : " + file.getAbsolutePath());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

    @Override
    protected void onDestroy() {
        this.mCancelValidation = true;
        super.onDestroy();
    }

and use java helper class.
 public class ZipHelper {
static boolean zipError = false;

public static boolean isZipError() {
    return zipError;
}

public static void setZipError(boolean zipError) {
    ZipHelper.zipError = zipError;
}

public static void unzip(String archive, File outputDir) {
    try {
        Log.d("control", "ZipHelper.unzip() - File: " + archive);
        ZipFile zipfile = new ZipFile(archive);
        for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e
                .hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            unzipEntry(zipfile, entry, outputDir);

        }
    } catch (Exception e) {
        Log.d("control", "ZipHelper.unzip() - Error extracting file "
                + archive + ": " + e);
        setZipError(true);
    }
}

private static void unzipEntry(ZipFile zipfile, ZipEntry entry,
        File outputDir) throws IOException {
    if (entry.isDirectory()) {
        createDirectory(new File(outputDir, entry.getName()));
        return;
    }

    File outputFile = new File(outputDir, entry.getName());
    if (!outputFile.getParentFile().exists()) {
        createDirectory(outputFile.getParentFile());
    }

    Log.d("control", "ZipHelper.unzipEntry() - Extracting: " + entry);
    BufferedInputStream inputStream = new BufferedInputStream(
            zipfile.getInputStream(entry));
    BufferedOutputStream outputStream = new BufferedOutputStream(
            new FileOutputStream(outputFile));

    try {
        IOUtils.copy(inputStream, outputStream);
    } catch (Exception e) {
        Log.d("control", "ZipHelper.unzipEntry() - Error: " + e);
        setZipError(true);
    } finally {
        outputStream.close();
        inputStream.close();
    }
}

private static void createDirectory(File dir) {
    Log.d("control",
            "ZipHelper.createDir() - Creating directory: " + dir.getName());
    if (!dir.exists()) {
        if (!dir.mkdirs())
            throw new RuntimeException("Can't create directory " + dir);
    } else
        Log.d("control",
                "ZipHelper.createDir() - Exists directory: "
                        + dir.getName());
}
}


text:
Q: Amazon Elastic Transcoder error 3003 Does Not Have Read Permission to S3 Bucket I am having trouble getting access to my input S3 bucket for my Amazon Elastic Transcoder pipeline.
3003   Does Not Have Read Permission   The IAM role specified in the Role object in the pipeline that you used for this job doesn't have permission to read from the Amazon S3 bucket that contains the file you want to transcode.

3003 d6a37de0-6404-4cde-9c37-7aada57d54b2: You do not have the permissions required to read the specified object from the specified bucket: bucket=mybucket, key=myinputfile.MOV.

*

*The bucket mybucket does not have a bucket policy

*the AIM role also has both AmazonS3FullAccess and AmazonElasticTranscoderFullAccess
Managed Policies

here is the custom inline policy for the IAM role that is attached to the Pipeline (Amazon Elastic Transcoder Pipeline):
{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "1",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:Put*",
                "s3:Get*",
                "s3:*MultipartUpload*"
            ],
            "Resource": "*"
        },
        {
            "Sid": "2",
            "Effect": "Allow",
            "Action": "sns:Publish",
            "Resource": "*"
        },
        {
            "Sid": "3",
            "Effect": "Deny",
            "Action": [
                "s3:*Policy*",
                "sns:*Permission*",
                "sns:*Delete*",
                "s3:*Delete*",
                "sns:*Remove*"
            ],
            "Resource": "*"
        },
        {
            "Sid": "4",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::mybucket/*"
        }
    ]
}

If somebody could point me in the right direction and shed some light on how to grant my Amazon Elastic Transcoder access to my S3 bucket I would greatly appreciate it.

A: I know it's very late to reply to your question. I also got the same error today and found that the error was thrown due to presence of file with same name in the output bucket. Solution is to generate a different name or to delete your previous output files. I don't know why aws throws Permission errors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: xdmp:email filtering out email addresses that don't pass a predicate Let's say I have a predicate:
declare function local:should-send-email($email-address) {
  ... fn:true() ...
  ... fn:false() ...
};

And then I have an email element for use with xdmp:email:
<em:Message
 xmlns:em="URN:ietf:params:email-xml:"
 xmlns:rf="URN:ietf:params:rfc822:">
  <rf:subject>Test</rf:subject>
  <rf:from>
    <em:Address>
      <em:name>Test Name</em:name>
      <em:adrs>test-from@test000.com</em:adrs>
    </em:Address>
  </rf:from>
  <rf:to>
    <em:Address>
      <em:name>Test Name</em:name>
      <em:adrs>test-to-1@test000.com</em:adrs>
    </em:Address>
    <em:Address>
      <em:name>Test Name</em:name>
      <em:adrs>test-to-2@test000.com</em:adrs>
    </em:Address>
  </rf:to>
  <em:content>Hello World</em:content>
</em:Message>

Lets say one of the to addresses passes the predicate and one doesn't. What is an efficient way to remove the em:Address element for the one that doesn't pass?

A: Assuming you intend to start with the complete <em:Message> element, you can use a recursive typeswitch to filter out the invalid email addresses - the logic is very similar to XSLT:
declare function local:filter-addresses(
  $node as node()
) as item()*
{
  typeswitch ($node)
  case element(em:Address) return
    if (not(local:should-send-email($node/em:adrs)))
    then () (: Filter :)
    else $node
  case element() return (: Passthrough :)
    element { node-name($node) } {
      $node/@*,
      for $child in $node/node()
      return local:filter-addresses($child)
    }
  default return $node
};


text:
Q: Insert new method call in InvocatioExpression I am writing a visual studio code fix with provider which will insert AsEnumerable call inside this kind of statement:
model.clients.Take(10).Select(c => new Client(c));

I am able to detect such statements but have issues inserting the AsEnumerable before Select method. This is what I have tried:
        var expressionSyntax = SyntaxFactory.ParseExpression(".AsEnumerable()");
        var memberAccessExpressionSyntax = invocationExpr.Expression as MemberAccessExpressionSyntax;

        var root = await document.GetSyntaxRootAsync(cancellationToken);

        var newRoot = root.InsertNodesAfter(memberAccessExpressionSyntax.Expression, new[] {expressionSyntax});

        return document.WithSyntaxRoot(newRoot);

but I get

"System.InvalidOperationException: The item specified is not the
  element of a list."

See stacktrace at: https://gist.github.com/anonymous/02c41f232829163b25ae
What is a proper way to call InsertNodesAfter method?

A: This is how I solved it:
var memberAccessExpressionSyntax = invocationExpr.Expression as MemberAccessExpressionSyntax;

var root = await document.GetSyntaxRootAsync(cancellationToken);

var accessExpression = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessExpressionSyntax.Expression, SyntaxFactory.IdentifierName("AsEnumerable"));

var invocationExpression = SyntaxFactory.InvocationExpression(accessExpression);
var enumerableMemberAccessExpression = memberAccessExpressionSyntax.WithExpression(invocationExpression);

root = root.ReplaceNode(invocationExpr, invocationExpr.WithExpression(enumerableMemberAccessExpression));

A: InsertNodesAfter only works for nodes in a list.  Method calls are not a list, but rather a tree of call expressions.
You need to replace the expression in the XXX.Select(...) call with XXX.AsEnumerable() (reusing the same XXX node).
To understand how these expression trees work, use the Roslyn Syntax Visualizer.


text:
Q: Unexpected CFBundleExecutable Key. The bundle at Aviary SDK Resources.bundle I have following error when trying to upload an AppStore.
Unexpected CFBundleExecutable Key. The bundle at Aviary SDK Resources.bundle does not contain a bundle executable. If this bundle intentionally does not contain an executable, consider removing the CFBundleExecutable key from its Info.plist and using a CFBundlePackageType of BNDL. If this bundle is part of a third-party framework, consider contacting the developer of the framework for an update to address this issue.
a) tried to remove BNDL from plist but noting happens.
How i can fix it ?

A: remove CFBundleExecutable key. but please do not touch main Info.plist file of the project. only change in Aviary SDK Info.plist


text:
Q: Rstudio loading workspace failed When I want to work with Rstudio , I get an error
"bad restore file magic number" error in R

I tried to do research on the internet to solve the problem but it does not work
Any idea please !!!

A: It seems as if R tries to automatically load a previously saved workspace that's corrupted. Take a look at your home directory and check if you can locate the .RData file. Delete that one and the problem should go away.
On Windows that's most likely in the folder:
C:/Users/YourUserName/Documents
Remember that the file is only the extension .RData and is -depending on your settings- sometimes automatically saved by both R and RStudio.  (depending on your settings it might ask to save the workspace on exiting, do so without asking or don't do it at all. see also ?quit)
Because it's only an extension, on Windows it will be a hidden file. In order to be able to see and delete it, change your Windows settings so you can see hidden files.


text:
Q: Ferry loading problem I have a difficulty with an undermentioned algorithmic problem:

There is a three-lane ferry in a port and in front of it there is a queue of N
  vehicles. Each of them has got specified lenght in cm. We also know
  the lenght (L) of the ferry. We have to propose an algorithm, which enables to
  load the ferry with the maximum amount of cars from the queue. Each car can choose between taking one of the three lanes: left, center or right. Cars have to be processed in order - for each car (starting from the front) we have to decide on which lane it will drive onto. If there is no enought free space for the car being in the front of the queue at the moment we finish. Remaining cars wait for the next ferry.

Greedy method (first-fit) isn't the most efficent in every case (e.g. if L is 5 and we have the queue 5 2 2 3 3). Thus I were trying to figure out what is the solution if we will think of it as an dynamic programming problem. Still I'm trying to find any, but all dynamic algorithms I know (especially from the Introduction to Algorithms) seem not to fit that problem.
Thank you in advance for any suggestions. :)

A: First, notice the similarities between this problem and the knapsack problem, the partition problem, and the bin packing problem.
This suggests a pseudopolynomial time dynamic programming solution. In each of those problems, we kept track of the optimal solution for a knapsack of every size less than the one we're interested in. In this case, our knapsacks are the three lanes. Now I hope the algorithm isn't too far from your mind yet.
I'm not going to give you the complete answer since this is a problem from UVa Online Judge. However I hope this puts you in the right direction. There is a lot of information out there on how to solve knapsack-related problems.


text:
Q: Creating a file using exec in Bash I am trying to use a shell program that I have been left to get running. The program starts as shown below.
#!/usr/bin/env bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>$1/logs/$(date '+%Y%m%d_%H%M%S')_start.log 2>&1

The program is a .sh with the input ($1) being the output folder such that it is looking in /output/logs..., the program fails on the exec line, this is my first time using bash and shell scripting but I think this line essentially redirects all the standard outputs to the log file?
The program error say
cannot create /output/logs/20230203_12345_start.log: directory non-existent

should this line also create the log file if it is non existent? I don't see how you could create the .log file first as otherwise you would get the seconds part of the title wrong?

A: It's not complaining about the file name, it says directory non-existent. I/O redirection can't make directories. Create it first with mkdir -p "$1"/logs, then your line should work.


text:
Q: Using USB barcode scanner in angular application I have an application in Angular 10 and I would like to implement USB barcode scanner input (for example in keyboard mode). The problem is that I'm using package ngx-barcodeput where I need an input field which should be active when barcodes is scanning. How can I use something like ngx-barcodeput without input field? I would like to have my scanner active all the time on the page not only when I click on input field. Have any tips? I searched the web and I cannot find any another package which can be used for usb barcode scanners in angular apps.

A: This code scans barcode from USB bacode scanner in angular application,
HTML file:

My App title

            <input type="text" (window:keypress)="onKey($event)"  autofocus />

barcode: {{ barcode }}

app component:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'barcode-scanner',
  templateUrl: './scan-barcode.component.html',
  styleUrls: ['./scan-barcode.component.css'],

})
export class ScanBarcodeComponent implements OnInit {
  barcode: string='';
  values: string[] =[];
  constructor() { }

  ngOnInit(): void {
  }
  onKey(event: any) {
    this.barcode=event.target.value;
}

}

See complete code here: https://github.com/saurabhku/ex-angular-barcode-scan


text:
Q: Error in Angular I have this component in angular:

import { Component, AfterViewInit, ElementRef, ViewChild} from '@angular/core';
@Component({
    selector: 'jhi-login-modal',
    templateUrl: './login123.component.html'
})
export class JhiLoginModalComponent implements AfterViewInit {
   a: number;
   @ViewChild('hiddenLabel') hidden: ElementRef;
     ngAfterViewInit() {
      const a = 5;
      console.log('Print a' + a);
     console.log('Print htmlcontent' + this.hidden);
   }
}

My HTML file is like this:

<label #hiddenLabel>Visible!</label>

And then I have a testing file for these where I want to test the html element. But firstly I want to make sure that I can print it and then test the value. Here is my test file:

import { ComponentFixture, TestBed, async, inject, fakeAsync, tick } from '@angular/core/testing';
import { JhiLoginModalComponent } from '../../../../../../main/webapp/app/shared/login/login.component';

describe('Component Tests', () => {
    describe('LoginComponent', () => {

        let comp: JhiLoginModalComponent;
        let fixture: ComponentFixture<JhiLoginModalComponent>;

    beforeEach(async(() => {
            TestBed.configureTestingModule({
                declarations: [JhiLoginModalComponent]
            })
            .overrideTemplate(JhiLoginModalComponent, '')
            .compileComponents();
        }));

        beforeEach(() => {
            fixture = TestBed.createComponent(JhiLoginModalComponent);
            comp = fixture.componentInstance;
        });
        it ('first test', async(() => {
            console.log('holaaa');
            fixture.detectChanges();
        }));
    });
});

What I get as a result in my console is that test passed. Normally this should be ok. And then it prints holaaa and then print a5 which is again alright. Then it prints Print htmlcontentundefined instead of printing Visible. What is the difference between teh number and teh HTMLElement?? Is there another way to reference the HTML elements?? As much as I have read on this it should be this way.
Thanks!

A: It seems that your hiddenLabel child is undefined, meaning it is not being picked up by your component typescript spec file. This is due to the .overrideTemplate(JhiLoginModalComponent, ''). This line replaces your JhiLoginModalComponent template with nothing. Thus, when your JhiLoginModalComponent trys to get the hiddenLabel viewChild it cannot find anything, therefore it is undefined.
You should change your spec to look like the following:
import { ComponentFixture, TestBed, async, inject, fakeAsync, tick } from '@angular/core/testing';
import { JhiLoginModalComponent } from '../../../../../../main/webapp/app/shared/login/login.component';

describe('Component Tests', () => {
    describe('LoginComponent', () => {

        let comp: JhiLoginModalComponent;
        let fixture: ComponentFixture<JhiLoginModalComponent>;

    beforeEach(async(() => {
            TestBed.configureTestingModule({
                declarations: [JhiLoginModalComponent]
            }).compileComponents();
        }));

        beforeEach(() => {
            fixture = TestBed.createComponent(JhiLoginModalComponent);
            comp = fixture.componentInstance;
            fixture.detectChanges();
        });
        it ('first test', async(() => {
            console.log('holaaa');
            fixture.detectChanges();
        }));
    });
});


text:
Q: Zendesk REST API Url for articles returning data in Browser, but giving unauthorized error in Visual Studio
I am working with ZENDESK Rest API. All the API URLS are returning me
  expected result in my development environment visual studio, But
  exceptionally there is one API URL provided by Zendesk which gives me
  always Unauthorize Error, while the same URL returns data in Browser.
  I have mentioned the URL follows

https://YourDomain/api/v2/help_center/articles.json

Request to zendesk API is as follows:

Response  from zendesk API is asl follows :

A frequent help will be much appreciated.
Thanks

A: If your Help Center is not active, you may receive that error.  Can you confirm that the Help Center is active?  Can you also share the URLs you've tried which do work?  For example, can you load https://yourdomain.zendesk.com/api/v2/help_center/categories.json ?


text:
Q: Aspas duplas ao exportar arquivos Podem me tirar uma dúvida referente a exportação de arquivos no Mysql?, já dei uma pesquisa sobre mas não encontrei nenhuma resposta...
Seguinte, tenho uma tabela que armazena o NOME de alguns clientes, preciso colocar essa coluna em um determinado layout para importar em outro CRM.

Quando vou fazer a exportação desses dados a coluna de NOME recebe aspas duplas e isso não pode acontecer porquê vai ocasionar erro ao importar no CRM.

Aqui esta o Load que faço para inserir os dados na tb teste2.
Load data local infile 'C:/sql/31.03/Nao_part02.txt'
INTO TABLE teste2
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(nome,@dt_imp)
SET
dt_imp= date(now())
;

Todos os arquivos importados para a tb teste2 não tem nenhuma aspa dupla.

Alguém tem alguma ideia do por que isso acontece ?
obg!

A:
Alguém tem alguma ideia do por que isso acontece ?

Verifiquei que este problema acontece porque no arquivo de origem existem dois caracteres que não estamos vendo a princípio, mas estão presentes. Para ver esses caracteres, você pode abrir o arquivo com o aplicativo Notepad++ e verá algo parecido com o seguinte:

Caso não veja os caracteres no aplicativo Notepad++, mostrarei como habilitar essa visualização no final da resposta.
Observe que no final das linhas, com exceção da última, temos CR e LF que são conhecidos também como \r e \n respectivamente.
Na computação, line feed (LF), nova linha ou quebra de linha é um caractere de controle que indica que uma linha deve ser acrescentada.
Já o carriage return (CR, um comando que fazia a cabeça da impressora retornar para a posição mais à esquerda).
Saiba um pouco mais sobre os caracteres especiais

LF (caractere: \n, Unicode: U + 000A, ASCII: 10, hex: 0x0a): Este é
simplesmente o caractere '\n' que todos conhecemos desde os primeiros
dias de programação. Esse caractere é comumente conhecido como
'Alimentação de linha' ou 'Caractere de nova linha'.
CR (caractere: \r, Unicode: U + 000D, ASCII: 13, hex: 0x0d): Este é
simplesmente o caractere '\r'. Esse caractere é comumente conhecido
como carriage return ou 'Retorno de carro'.

O Problema na importação
O problema é que no momento da importação, está sendo informado LINES TERMINATED BY '\n' quando na verdade deveria está informando LINES TERMINATED BY '\r\n'.
Solução para corrigir a importação:

*

*Altere a linha LINES TERMINATED BY '\n' para LINES TERMINATED BY '\r\n'

*Verifique se a última linha foi inserida corretamente, caso
contrário, basta acrescentar uma linha em branco no final, mas
provavelmente não será necessário. Falo isso, pois podemos observar que na última linha não existem os caracteres de marcação CR e LF.

Corrigindo dados já existentes no Banco de Dados
Execute a consulta na tabela teste2 :
SELECT replace(nome,char(13),'***') FROM teste2;

Visto que sua importação inicial considerou apenas o \n, significa que o \r foi incluso no banco de dados, a consulta acima evidenciará esse caractere conforme imagem abaixo:

Solução para os dados já existentes:
Sugiro realizar um UPDATE atualizando os registros que possuem o \r da seguinte forma:
UPDATE teste2
SET
    nome = REPLACE(nome, CHAR(13), '')
WHERE
    nome LIKE '%\r'

Caso não veja os caracteres no aplicativo Notepad++:
Habilite a opção "Exibir final de linha" conforme imagem abaixo.

Fonte pesquisada sobre os caracteres: EOL or End of Line or newline ascii character


text:
Q: htaccess redirect when https host with full uri including search an hash I have activated a shared SSL on my domain.
I am attempting to redirect if the calling host is HTTPS and is attempting to load one of my pages in an iframe.
Let's assume my webpage is:
http://bitbenderz.com/chartticker/?symbol=msft

Now your HTTPS page wants to use my webpage in an <iframe> by calling it with:
https://bitbenderz.com/chartticker/?symbol=msft

I want to redirect to ... https://bitbenderz.websitesource.net/chartticker/?symbol=msft
I also need to remove any WWW before the domain name.
Thank you, in advance, for your valued assistance!

A: put this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^bitbenderz\.com$ [NC]
RewriteRule ^ https://bitbenderz.websitesource.net%{REQUEST_URI} [L,R,NE]


text:
Q: SQL Server is not connecting with node app I am trying to connect my nodejs/express app to SQL Server 2017 using Sequelize ORM. This is my first time of using SQL Server. I am not sure where is the problem.
Situation:-

*

*I create a database using SQL Server Management Studio

*I create an another user under security > login (for eg:- userName, passWord)

*And make this user the owner of that database
Issues:

*

*When I tried to connect to SQL Server using Management Studio (using SQL Server authentication), my connection is established every time.

*But when I tried to connect same database with my nodejs app I got errors:

Error:- [SequelizeAccessDeniedError: Login faled for user '']##

Note: I already tried mssql npm package but could not connect to SQL Server from nodejs
Here is my code for index.js file using sequelize
const express = require('express');

const app = express();

const Sequelize = require('sequelize');
const sequelize = new Sequelize("demo", "demoUser", "dPass", {
    host: "localhost",
    dialect: "mssql",
    pool: {
        max:  1,
        min: 0,
        idle: 5000,
        acquire: 5000
    },
    dialectOptions: {
        encrypt: true
    }
});

sequelize
    .authenticate()
    .then(() => {
        console.log("connection established");
    })
    .catch(err => {
        if (err) {
            console.log(`unable to connect database Error ${err}`);
        }
    });

app.listen(3000, (err) => {
    if (err) throw err;
    console.log("Server connect to port 3000");
})

A:
you have to add npm package sequelize-msnodesqlv8

const Sequelize = require('sequelize');

    let connectionString = {
        dialect: 'mssql',
        dialectModulePath: 'msnodesqlv8/lib/sequelize',
        dialectOptions: {
          driver: "SQL Server Native Client 11.0",
          instanceName: 'MSSQLSERVER',//in my condition //check it in server configuration manager which instance is running
          trustedConnection: true
        },
        host: 'localhost',
        database: 'dbname'
      }

const sequelize = new Sequelize(connectionString);

driver-go to odbc driver
then in 'system dns' tab
Add
select SQL Server Native Client 11.0 then press finish
put name as SQL Server Native Client 11.0 then select server from
   dropdown then next
next
next
next
finish
test data source


text:
Q: Install older version of VirtualBox (4.3.6-91406) on OS X El Capitan I am trying to install VirtualBox 4.3.6-91406 on OS X El Capitan because I want to run an old version of Minix.
It is advised to run my version of Minix on VirtualBox 4.3.6 as it may not be compatible with the newest VirtualBox 5.0.12-104815 and anything between.
Running the old VirtualBox 4.3.6-91406:
This is what I get when I try to install VirtualBox 4.3.6-91406:

Running latest VirtualBox 5.0.12-104815:
And this is what I get when I try to run my old version of Minix on the latest VirtualBox:

Implementation of the USB 2.0 controller not found!
Because the USB
  2.0 controller state is part of the saved VM state, the VM cannot be started. To fix this problem, either install the 'Oracle VM VirtualBox
  Extension Pack' or disable USB 2.0 support in the VM settings
  (VERR_NOT_FOUND).
Result Code:  NS_ERROR_FAILURE (0x80004005)
  Component:  ConsoleWrap
  Interface:  IConsole {872da645-4a9b-1727-bee2-5585105b9eed}

Is there anything I can do about it? I want to run this version of Minix and preferably VirtualBox 4.3.6.

A: I had to do the following things:

*

*Boot the image on Linux with VirtualBox 4.3.6 installed from a terminal using the following command:
$ VBoxSDL --startvm MINIX3 --norawr0 --norawr3 --nohwvirtex

*Apply this patch which resolves the guru meditation problem.

*

*Go to /usr/src/drivers/e1000 and in the e1000.c file you have to replace line
e1000_reg_write(e, E1000_REG_MTA + i, 0);

with
e1000_reg_write(e, E1000_REG_MTA + i * 4, 0);

*Run make and make install in /usr/src/drivers/e1000.

*Turn off your virtual machine.

*Copy the whole directory of your virtual machine to OS X.

*Install latest VirtualBox.

*Download Oracle VM VirtualBox Extension Pack and add this extension to your VirtualBox.

*Done!


text:
Q: Can the if / else inside the for loop be converted/simplified to Java 8 I have the below piece of code. I need to convert into java 8.
I tried my luck , but was stuck with else part.
Kindly help me if this could be achieved.
    List<String> modelValues = new ArrayList<>();
    modelValues.add("one");
    modelValues.add("two");
    modelValues.add("three");

    List<String> selectedValues = new ArrayList<>(); //Orignally fetched from the database
    selectedValues.add("four");
    selectedValues.add("five");
    selectedValues.add("six");

    for (String value : modelValues) {
        if (isSelected(value)) { //isSelected returns true or false
            selectedValues.add(value);
        } else {
            if (isNotSelected(value)) { //isNotSelected returns true or false
                selectedValues.remove(value);
            }
        }
    }

A:     modelValues.stream().filter(this::isSelected).forEach(selectedValues::add);
    modelValues.stream().filter(this::isNotSelected).forEach(selectedValues::remove);

Not the best choice since u go twice through the for loop. I would stick to you original loop.
modelValues.forEach(value -> {
        if (isSelected(value)) { // isSelected returns true or false
            selectedValues.add(value);
        } else if (isNotSelected(value)) { // isNotSelected returns true or false
            selectedValues.remove(value);
        }
    });


text:
Q: is this a way to search substring and ignore specific cells? c# I need to search a string which, for example, looks like this: 113312312, within
in a string looking like 11211201222110.
The meaning is to look for the substring in the original. Note where the 3 appears in the substring can be anything in the original.
original : 111222121212

scenario 1:  func(131222121212) return true
scenario 2:  func(333222) return true
scenario 3:  func(3333333333) return true
scenario 4:  func(333333333333) return true
scenario 5:  func(233333333333) return false

A: public bool match(string original, string pattern)
{
    if (string.IsNullOrEmpty(original)) return false;
    if (string.IsNullOrEmpty(pattern)) return false;
    if (pattern.Length > original.Length) return false;

    pattern = "^" + pattern.Replace("3", @"\d");
    return System.Text.RegularExpressions.Regex.IsMatch(original, pattern);
}

See it work:

https://dotnetfiddle.net/LYbdrj


text:
Q: Validate an XML against a Schematron using PHP There are a lot of resources about Schematron... however I cant find anything related or an example on how to validate an xml against a Schematront .sch file.
Anyone?
I already found 1 or 2 very old classes that return errors... so if anyone knows how to do this, please help.

A: I use the 'ANT' option..
Build.xml
<project name="myName" default="all" basedir=".">
  <taskdef name="schematron"
          classname="com.schematron.ant.SchematronTask"
          classpath="lib/ant-schematron-2010-04-14.jar;lib/saxon9he.jar"/>

  <target name="all" description="test it">
    <schematron schema="sch/test.sch" failonerror="false" debugMode="true">
      <fileset dir="./xml" includes="*.xml"/>
    </schematron>
  </target>

</project>

debugMode=true shows you the intermediate XSLT file


text:
Q: Attempting to convert SWF to standalone EXE in AIR with FlashDevelop This problem has been bugging me for a while now, I'm trying to make a standalone EXE from a SWF of a game I'm making, but I've had tons of trouble during the way. I want it standalone, meaning no installer, I want the user to be able to open the EXE and start playing automatically. I'm using FlashDevelop's AIR AS3 Projector Project and have gotten almost all the kinks out, but there's still a snag I'm hitting in the end. I've been able to build the EXE, but upon launch attempt I'm hit with an error that reads: "This application requires a version of Adobe AIR which cannot be found." I've ensured both my AIR project and game project are using AIR version 17, but it's still not working.
I'll provide the code for the bats below and hopefully someone can figure this out.
Packager.bat
@echo off

:: Set working dir
cd %~dp0 & cd ..

if not exist %CERT_FILE% goto certificate

:: AIR output
if not exist %AIR_PATH% md %AIR_PATH%
set OUTPUT=%AIR_PATH%\%AIR_NAME%%AIR_TARGET%.air

:: Package
echo.
echo Packaging %AIR_NAME%%AIR_TARGET%.air using certificate %CERT_FILE%...
adt -package -keystore bat\TheLabyrinth.p12 -storetype pkcs12 -target bundle The_Labyrinth application.xml -C bin TheLabyrinth.swf TheLabyrinthGame.swf lib\backgrounds\cobblestone.png lib\backgrounds\frameBackground.png lib\backgrounds\fullscreenCobble.png lib\backgrounds\parchment.png lib\backgrounds\parchmentFrameBackground.png lib\spritesheet.png
call adt -package %OPTIONS% %SIGNING_OPTIONS% %OUTPUT% %APP_XML% %FILE_OR_DIR%
if errorlevel 1 goto failed
goto end

:certificate
echo.
echo Certificate not found: %CERT_FILE%
echo.
echo Troubleshooting:
echo - generate a default certificate using 'bat\CreateCertificate.bat'
echo.
if %PAUSE_ERRORS%==1 pause
exit

:failed
echo AIR setup creation FAILED.
echo.
echo Troubleshooting:
echo - verify AIR SDK target version in %APP_XML%
echo.
if %PAUSE_ERRORS%==1 pause
exit

:end
echo.

Application.xml
<?xml version="1.0" encoding="utf-8" ?>
<application xmlns="http://ns.adobe.com/air/application/17.0">

    <id>TheLabyrinth</id>
    <versionNumber>1.0</versionNumber>
    <filename>TheLabyrinth</filename>

    <name>The Labyrinth</name>
    <description></description>
    <copyright></copyright>

    <initialWindow>
        <title>The Labyrinth</title>
        <content>TheLabyrinth.swf</content>
        <systemChrome>standard</systemChrome>
        <transparent>false</transparent>
    <visible>true</visible>
    <minimizable>true</minimizable>
    <maximizable>true</maximizable>
    <resizable>true</resizable>
</initialWindow>

<!--
More options:
http://livedocs.adobe.com/flex/3/html/File_formats_1.html#1043413
-->
</application>

Thanks for any help regarding this, I've searched far and wide for an answer and I've yet to come across a fix.

A: Okay, I forgot about this question but I'm coming back to answer it in case anyone else stumbles upon it. Whenever using FlashDevelop with the intent of creating a standalone executable, I choose the AIR AS3 Projector when creating a new project. This will already contain the batch files you're going to need to change using my files below (I'll also show any unique changes you need to make). From there here are the settings for the batch files that I copy over from a previous project that works.
First I'll show the application.xml since that has a few things we want to check out beforehand. The settings will automatically populate in this xml when you launch your program in either Debug or Release mode. This specific example is from a game titled Charlene for my girlfriend:
<?xml version="1.0" encoding="utf-8"?>
<application xmlns="http://ns.adobe.com/air/application/21.0">
    <id>Charlene</id>
    <versionNumber>1.0</versionNumber>
    <filename>Charlene</filename>
    <name>Charlene</name>
    <initialWindow>
        <title>Charlene</title>
        <content>Charlene.swf</content>
        <systemChrome>standard</systemChrome>
        <transparent>false</transparent>
        <visible>true</visible>
        <minimizable>true</minimizable>
        <maximizable>false</maximizable>
        <resizable>false</resizable>
        <x>0</x>
        <y>0</y>
        <minSize>800 800</minSize>
    </initialWindow>
    <!--
    More options:
    http://livedocs.adobe.com/flex/3/html/File_formats_1.html#1043413
    -->
    <supportedProfiles>extendedDesktop</supportedProfiles>
    <android>
        <manifestAdditions><![CDATA[<manifest android:installLocation="auto" xmlns:android="http://schemas.android.com/apk/res/android" />]]></manifestAdditions>
    </android>
</application>

There are two things to note here: the application xmlns version MUST be the same version as the AIR version you're using (this can be viewed by clicking Project, and then Properties). If this is not the same version, simply change either the xml or the version in the Properties otherwise your program won't compile.
The next thing to note is the supportedProfiles. The extendedDesktop setting is required if you want the keyboard to work while your program is in fullscreen.
Now we're going to look at CreateCertificate.bat. You need to run this batch file before any others, as the compiler needs a certificate to package your program. This will create a unique key for your program with the name "YourProgramTitle.p12":
@echo off

:: Set working dir
cd %~dp0 & cd ..

set PAUSE_ERRORS=1
call bat\SetupSDK.bat
call bat\SetupApp.bat

:: Generate
echo.
echo Generating a self-signed certificate...
call adt -certificate -cn %CERT_NAME% 2048-RSA %CERT_FILE% %CERT_PASS%
if errorlevel 1 goto failed

:succeed
echo.
echo Certificate created: %CERT_FILE% with password "%CERT_PASS%"
echo.
if "%CERT_PASS%" == "fd" echo Note: You did not change the default password
echo.
echo HINTS:
echo - you only need to generate this certificate once,
echo - wait a minute before using this certificate to package your AIR application.
echo.
goto end

:failed
echo.
echo Certificate creation FAILED.
echo.

:end
pause

No special settings here, moving on to the PackageApp.bat. This is another batch that doesn't require specific changing, the settings here should work for compiling your project:
@echo off

:: Set working dir
cd %~dp0 & cd ..

set PAUSE_ERRORS=1
call bat\SetupSDK.bat
call bat\SetupApp.bat

set AIR_TARGET=air/Setup.exe
::set AIR_TARGET=-captive-runtime
set OPTIONS=-tsa none
call bat\Packager.bat

pause

Next up is the big one, Packager.bat. Again, no special settings here, this batch file should be good to copy over and not change:
@echo off

:: Set working dir
cd %~dp0 & cd ..

if not exist %CERT_FILE% goto certificate

:: AIR output
if not exist %AIR_PATH% md %AIR_PATH%
set OUTPUT=-target bundle %AIR_NAME%

:: Package
echo.
echo Packaging %AIR_NAME%%AIR_TARGET%.air using certificate %CERT_FILE%...
call adt -package %OPTIONS% %SIGNING_OPTIONS% %OUTPUT% %APP_XML% %FILE_OR_DIR%
if errorlevel 1 goto failed
goto end

:certificate
echo.
echo Certificate not found: %CERT_FILE%
echo.
echo Troubleshooting:
echo - generate a default certificate using 'bat\CreateCertificate.bat'
echo.
if %PAUSE_ERRORS%==1 pause
exit

:failed
echo AIR setup creation FAILED.
echo.
echo Troubleshooting:
echo - verify AIR SDK target version in %APP_XML%
echo.
if %PAUSE_ERRORS%==1 pause
exit

:end
echo.

Next up is RunApp.bat. There's not much here but I'll include it anyway:
@echo off

:: Set working dir
cd %~dp0 & cd ..

set PAUSE_ERRORS=1
call bat\SetupSDK.bat
call bat\SetupApp.bat

echo.
echo Starting AIR Debug Launcher...
echo.

adl "%APP_XML%" "%APP_DIR%"
if errorlevel 1 goto error
goto end

:error
pause

:end

You can actually change the echo Starting AIR Debug Launcher... line if you want the cmd to show a different message before the debugger launches.
We're gonna look at the SetupApp.bat. This has some parameters you're going to have to change to fit your program:
:: Set working dir
cd %~dp0 & cd ..

:user_configuration

:: About AIR application packaging
:: http://livedocs.adobe.com/flex/3/html/help.html?content=CommandLineTools_5.html#1035959
:: http://livedocs.adobe.com/flex/3/html/distributing_apps_4.html#1037515

:: NOTICE: all paths are relative to project root

:: Your certificate information
set CERT_NAME="Charlene"
set CERT_PASS=fd
set CERT_FILE="bat\Charlene.p12"
set SIGNING_OPTIONS=-storetype pkcs12 -keystore %CERT_FILE% -storepass %CERT_PASS%

:: Application descriptor
set APP_XML=application.xml

:: Files to package
set APP_DIR=bin
set FILE_OR_DIR=-C %APP_DIR% .

:: Your application ID (must match <id> of Application descriptor) and remove spaces
for /f "tokens=3 delims=<>" %%a in ('findstr /R /C:"^[  ]*<id>" %APP_XML%') do set APP_ID=%%a
set APP_ID=%APP_ID: =%

:: Output
set AIR_PATH=air
set AIR_NAME=Charlene

:validation
findstr /C:"<id>%APP_ID%</id>" "%APP_XML%" > NUL
if errorlevel 1 goto badid
goto end

:badid
echo.
echo ERROR:
echo   Application ID in 'bat\SetupApp.bat' (APP_ID)
echo   does NOT match Application descriptor '%APP_XML%' (id)
echo.
if %PAUSE_ERRORS%==1 pause
exit

:end

Here, the set CERT_NAME="Charlene" line should have the string name that's equal to the name parameter in the application.xml. The set CERT_FILE="bat\Charlene.p12" file name should be the same name your CreateCertification.bat created when you ran it (run it now if you haven't). set AIR_NAME=Charlene should again have the same name as the CERT_NAME (assuming you want your finished project to have the same name as your debugged one).
Lastly we're going to look at the SetupSDK.bat. This one has one line you're going to have to change:
:: Set working dir
cd %~dp0 & cd ..

:user_configuration

:: Static path to Flex SDK
set FLEX_SDK=C:\Users\Alec\AppData\Local\FlashDevelop\Apps\flexairsdk\4.6.0+21.0.0

:: Use FD supplied SDK path if executed from FD
if exist "%FD_CUR_SDK%" set FLEX_SDK=%FD_CUR_SDK%

:validation
if not exist "%FLEX_SDK%\bin" goto flexsdk
goto succeed

:flexsdk
echo.
echo ERROR: incorrect path to Flex SDK in 'bat\SetupSDK.bat'
echo.
echo Looking for: %FLEX_SDK%\bin
echo.
if %PAUSE_ERRORS%==1 pause
exit

:succeed
set PATH=%FLEX_SDK%\bin;%PATH%

set FLEX_SDK should have the path to your Flex+AIR SDK. If you need to know the path, click the Project tab, then Properties, navigate to the SDK tab, click Manage, click the Installed Flex SDKs parameter, click the ellipses square on the right side of the InstalledSDK[] Array, make sure you've selected the most current version of the SDK on the left Members side (or the one that has the same version as your application.xml file), expand the window and you should see the path under the Location field.
Okay, it's been a long road. Test your project to make sure your local swf is updated, then run the PackageApp.bat. If everything was set up properly there should be no errors and after a few second the cmd will say "Press any key to continue" and a new folder with the name of your project should appear in your project's directory. This folder should contain another folder called Adobe AIR, a lib folder, a META-INF folder, an exe with your project's name, an swf with your project's name, and a mimetype file. You should be able to run the exe with no issue. And there you have it! Hopefully this works for anyone else with this problem.
Just a quick note: I noticed when packaging relatively large projects, sometimes the batch files don't compile a full project. It can take many attempts before it compiles fully, but I found a cheat. It requires an already existing, fully compiled project. All you need to do is copy over your project's swf (normally housed in your bin folder) over to the packaged project's folder. You may also need to copy over other files if you've changed them, such as the application.xml (the compiled file is located in the META-INF\AIR directory), or the lib folder if you import anything during run-time. This lets you bypass recompiling!


text:
Q: where is setHeaderData defined in pyside2 qsqltablemodel class inheritance from qabstractitemmodel? I am trying to understand where the setHeaderData virtual method is defined in qSqlTableModel class. I followed the inheritance chain up through the other classes but don't see it mentioned.
When I replace class MyClass(QSqlTableModel): with class MyClass(QAbstractTableModel):, everything works except I don't get column headings, just numbers; I also don't get an error about a virtual function not being defined.
The heading code works with the QSqlTableModel, just does not seem to do anything for QAbstractTableModel. It has to be defined somewhere in the QSqlTableModel to work. If I 'knew' what SetHeaderData did I could try to implement it, but I've not found any examples of its code, just mentions of it.
def set_header_data(self):
    """
    from __init__, load the headers into the model
    """
    for headix, head in enumerate(self._head):
        self.setHeaderData(headix, Qt.Horizontal, head, role=Qt.EditRole)

PySide2 5.15.2
Python 3.9.1


text:
Q: fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree when using git diff I am trying to take out git diff of a particular file in a folder using below command on azure devops pipeline:
git diff --name-only HEAD^ .\dev-artifacts.properties .\dev-artifacts.properties

or
git diff --name-status HEAD HEAD^

or
git diff --name-only dev-artifacts.properties dev-artifacts.properties

After running this command, I am getting below error:

fatal: ambiguous argument 'HEAD^': unknown revision or path not in the
working tree. Use '--' to separate paths from revisions, like this:
'git  [...] -- [...]'

I tried switching the branch (main branch), but still it is not working. But in my local I am able to get the difference using git diff.
I want to get the difference using git diff, so that I can run a python script when there is a change in file.

A: You have a shallow repository with only a single commit. You can verify by executing git rev-parse --is-shallow-repository.
HEAD^ points to the commit before your current commit – which does not exist in shallow clones of depth 1. You have to unshallow your clone or deepen it to include the commits which you are referencing.
For instance, to deepen your shallow clone to include the latest 5 commits, run git fetch --depth=5


text:
Q: VS 2008 C++ error C2059 and C2238 I'm trying to port a program/game that was developed in linux/g++ so that it runs on windows 7 VS 2008 C++. The program uses libraries such as OpenGL, SDL, and Boost.
I've solved a lot of errors but I'm kind of stuck on this one.
I get error code C2059 and C2238. The actual error messages are:
------ Build started: Project: Asteroid Blaster, Configuration: Release Win32 ------
Compiling...
WeaponDisplay.cpp
Weapon.cpp
ViewFrustum.cpp
Vector3D.cpp
UDP_Server.cpp
d:\College\AsteroidBlaster\Utility/ViewFrustum.h(40) : error C2059: syntax error : ';'
d:\College\AsteroidBlaster\Utility/ViewFrustum.h(40) : error C2238: unexpected token(s) preceding ';'
d:\College\AsteroidBlaster\Utility/ViewFrustum.h(41) : error C2059: syntax error : ';'
d:\College\AsteroidBlaster\Utility/ViewFrustum.h(41) : error C2238: unexpected token(s) preceding ';'
UDP_Client.cpp
d:\College\AsteroidBlaster\Utility/ViewFrustum.h(40) : error C2059: syntax error : ';'
d:\College\AsteroidBlaster\Utility/ViewFrustum.h(40) : error C2238: unexpected token(s) preceding ';'
d:\College\AsteroidBlaster\Utility/ViewFrustum.h(41) : error C2059: syntax error : ';'
d:\College\AsteroidBlaster\Utility/ViewFrustum.h(41) : error C2238: unexpected token(s) preceding ';'
TractorBeamShot.cpp

The ViewFrustum.h file is as follows:
  /**
   * viewFrustum: It's got useful functions to cull items that aren't in your view frustum
   *
   * 2-7-11
   * CPE ---
   */

  #ifndef __VIEW_FRUSTUM_H__
  #define __VIEW_FRUSTUM_H__

  #include "Items/Object3D.h"
  #include "Utility/Plane.h"
  #include "Utility/Matrix4.h"
  #include <vector>
  #include <set>

  class ViewFrustum {
     public:

        ViewFrustum();
        virtual ~ViewFrustum();

        /* Takes in a list of all the Object 3D's around, and culls them down to only the ones
         * that are inside the view frustum.
         */
        virtual std::list<Drawable*>* cullToViewFrustum(std::vector<Drawable*>* all, bool skipParticles);
        virtual std::list<Object3D*>* cullToViewFrustum(std::vector<Object3D*>* all);

        /* Prints out details about all of the planes of the view frustum.
         */
        virtual void print();

     private:
        Matrix4 projMatrix;
        Matrix4 modelViewMatrix;
        Plane* top;
        Plane* bottom;
        Plane* left;
        Plane* right;
        Plane* near;
        Plane* far;

        /**
         * A modified version of chedDrawableOutside, used by the AI. This stops the
         * AI from targeting Drawable objects which are slightly outside the field
         * of view, which still need to be drawn.
         */
        bool checkTargetableOutside(Drawable* obj);

        /* Returns true if the Drawable object is completely outside of the
         * view frustum planes.
         * Returns false if it's even part-way inside.
         */
        virtual bool checkDrawableOutside(Drawable* obj);
  };

  #endif

The offending lines (40-41) are:
  Plane* near;
  Plane* far;

It's kind of confusing because the ViewFrustum obj got compiled already but when it gets to UDP_Server.cpp and UDP_Client.cpp, it throws an error. I'm not sure if it matters but the UDP classes use Boost's aiso and serialization modules. I know Boost sometimes gives out weird warnings but I'm not sure if Boost has to do anything with this error.
If anyone has any idea why this is or if you need more code posted, please let me know.

A: Chances are you're including a windows header before that one, and near and far are defined somehwere in there. Those are (legacy) things from the 16bit era.
See this related question Is there a clean way to prevent windows.h from creating a near & far macro? for workarounds.


text:
Q: How do i find a matching string, when it contains errors? This is NOT about string1 == string2. Its a little more complicated :-)
I have different people create a lot of PDF-files and report the filenames in a spreadsheet-file.
(This procedure will not be changed for a long time, so please don't suggest so...)
Every week I have to check if all Files in the list are available as PDFs too.
The Strings have to be IDENTICAL and of course there are always all sorts of errors.
Uppercase vs. lowercase, blank missing, blank at the beginning, character left out, wrong Character inserted...
So currently I'm writing a script that is supposed to find all those strings in both lists that have no match in the other list.
What the strings have in common is, that they contain a date and a number. This number is mostly, but not always unique.
When the number is used more than once, the rest of the string is different.
So far i can find errors caused by mixing upper- and lowercase. That's easy.
And my script can find matches when the error is caused by leaving out one character.
My question now is: how can I find the matching string, when more than one Character is wrong and/or the stringlength differs?
This is what the strings look like:
mip - 20140512 - 11     Mip - 20140512 - 11
mip - 20140512 - 27     MiP - 20140512 - 27
mip - 20140512 - 33     mip -20140512 - 33
coty - 20140512 - 35    cotY -20140512 -35

A: well to solve for case and spaces you can compare everything as a lower case and remove all the spaces.
var str = "Hello World!";
    var tst = "helloworld!";

var res = str.toLowerCase();
res = res.replace(" ", "");
    if(str == tst)
    {
      // it worked
    }

this may not solve for all but should resolve for most of your issues i think.
Should solve for the examples you posted.

A: You can use a regular expression to parse the strings in a relaxed way, for example:
MatchCollection m = Regex.Matches(str, @"^\s*([a-z]+)\s*-\s*(\d+)\s*-\s*(\d+)\s*$", RegexOptions.IgnoreCase);

This will allow for leading and trailing spaces, optional spaces around the dashes, and mixed upper and lower case characters.
You can then put the matched parts together in a well formed string:
if (m.Count == 1) {
  string wellFormed = m[0].Groups[1].Value.ToLower() + " - " + m[0].Groups[2].Value + " - " + m[0].Groups[3].Value;
  ...
}

This would turn for example the string "cotY -20140512 -35" into "coty - 20140512 - 35".
If the string doesn't match the pattern, m.Count is zero, and you might want to do some secondary checking, or reject it as an invalid string.
You might want to make the pattern more or less relaxed depending on your needs, for example requiring that the date is exact 8 digits to match it ((\d{8})).

A: There is a common pattern in the sample you listed. If this is always the case you can build a regex that uses the pattern to normalize all the filenames. Once they are all normalized it should be easy to find matches.
var coll=[
    ['mip - 20140512 - 11'],
    ['mip - 20140512 - 27    '],
    ['mip - 20140512 - 33   '] ,
    ['coty - 20140512 - 35  '] ,
    ['Mip - 20140512 - 11'],
    ['  MiP - 20140512 - 27'],
    ['mip -20140512 - 33'],
    ['cotY -20140512 -35']
];

var regx = new RegExp(/([A-Za-z]*)\s*-\s*(\d*)\s*-\s*(\d*)/);
// ([A-Za-z]*)  ... Match1 [$1] group of letters
// \s*          ... followed by zero or more spaces
// -            ... followed by a hypen
// \s*          ... followed by zero or more spaces
// (\d*)        ... Match2 [$2] a group of digits
// \s*          ... followed by zero or more spaces
// -            ... followed by a hyphen
// \s*          ... followed by zero or more spaces
// (\d*)        ... Match3 [$3] a group of digits

function cleanAndPush(el){
    el.push(
        el[0].trim().replace(regx,"$1-$2-$3").toUpperCase()
    );
}

coll.map(cleanAndPush);

http://jsfiddle.net/fH95m/


text:
Q: Nsis temp folder Function .onInit
DetailPrint "Temp folder - $TEMP"
System::Call 'Kernel32::GetTempFileName(t $TEMP, t "tmp", i 0, t.r0) i.r1
DetailPrint "Temp folder name - $0" //$0  gives empty string
FunctionEnd

When I call Kernel32::GetTempFileName in .onInit function i retrieves an empty file name. But when i call it from section everything is ok!
Can you explain me why?

A: I recommend you just call InitPluginsDir in .onInit and use $PLUGINSDIR as temp folder. It will be deleted automatically on exit.

$PLUGINSDIR
The path to a temporary folder created upon the first usage of a
  plug-in or a call to InitPluginsDir. This folder is automatically
  deleted when the installer exits.

A: It is important to quote all string parameters when using System::Call:
Section
System::Call 'Kernel32::GetTempFileName(t "$TEMP", t "tmp", i 0, t.r0) i.r1'
DetailPrint |$0|
SectionEnd

Please consider using $pluginsdir like the other answer suggests, it is a much better solution because it will not leave behind junk on the end-users machine...


text:
Q: WebService GET/POST Call and SOAP I was going through this link below:
http://support.microsoft.com/kb/819267
Here it explains to enable HTTP GET/POST calls for web service, for calling a service directly through the browser.
Questions:

*

*While calling through browser are we
using GET or POST? How it gets
decided?

*If we are using regular HTTP
GET/POST instead of SOAP, where does
SOAP comes in? Or is it wrong to say
that web services always use SOAP protocol for sending receiving messages?

A: *

*If you're passing all parameters through the query string of the URL, then you're using GET. If you're building the request using something Fiddler to explicitly use POST, then you're using POST.

*If you're using GET/POST with .NET Web Services, SOAP doesn't come in to the picture at all. You'll also notice that as your service gets more complex, you lose the ability to call the Service through GET/POST because the complexity of SOAP is needed to wrap the data.

A: *

*If the request you are making has a payload/request body then a POST request will be used.

*The SOAP protocol defines the type of message that is sent, typically as the body of an HTTP POST request or the body of an HTTP response. Not all web services use SOAP, although rightly or wrongly it has become the de facto standard.


text:
Q: How can I make validation behave properly? I am using WebMatrix, asp.net and razor. I have been following these tutorials.
This page must insert values into a database, it does it prefectly at first but then when I add validation, it gives me this error "Exception Details: System.OverflowException: Value was either too large or too small for an Int32." The database used is all nvarchar except for Techid that is an int. But what I don't understand is when I comment out
Validation.Add("no", Validator.Range(9,10 ,"Contact number can not be longer or shorter than 10 digits"));
Validation.Add("num", Validator.Range(13,13,"Is number must be 13 digits"));
Validation.Add("name", Validator.Regex("^[a-zA-Z ]+$", "Invalid format for a name"))

it works quite fine.
@{
    var db = Database.Open("ProjectTest");
    var Name = Request.Form["name"];
    var Surname = Request.Form["surname"];
    var IDNumber = Request.Form["num"];
    var Address = Request.Form["add"];
    var ContactNumber = Request.Form["no"];
    var Course = Request.Form["course"];
    var TechID = Request.Form["techID"];
    var grade = Request.Form["grade"];

    Validation.RequireField("name", "Name is needed");
    Validation.RequireField("surname", "Surname is needed");
    Validation.RequireField("num", "num is needed");
    Validation.RequireField("add", "add is needed");
    Validation.RequireField("no", "no is needed");
    Validation.RequireField("course", "course is needed");
    Validation.RequireField("grade", "grade is needed");

    Validation.Add("no", Validator.Range(9,10 ,"Contact number can not be longer or shoter than 10 digits"));
    Validation.Add("num", Validator.Range(13,13,"Is number must be 13 digits"));
    Validation.Add("name", Validator.Regex("^[a-zA-Z ]+$", "Invalid format for a name"));

    if (IsPost)
    {
        if (Validation.IsValid())
        {
            var insertQuery = "INSERT INTO UserInfo (Name, Surname, IdNum, Address, ContNum, Course, Grade) VALUES (@0, @1, @2, @3 ,@4, @5, @6)";
            db.Execute( insertQuery, Name, Surname, IDNumber, Address, ContactNumber, Course, grade );
        }
    }
    else
    {
          ModelState.AddFormError("There are some errors with your submission");
    }
}

<!DOCTYPE html>

        <meta charset="utf-8" />
        <title></title>

        Home

              If you are an Student that wants to register use this form.

       <form method="post">

            Name:	<input type="text" name="name">

            Surname:	<input type="text" name="surname">

            ID Number:	<input type="text" name="num">

            Address:	<input type="text" name="add">

            Contact Number:	<input type="text" name="no">

            Course:	<input type="text" name="course" value="">

            Grade:	<input type="text" name="grade">

<input type="submit" value="Submit">

           @Html.ValidationMessage("name")

           @Html.ValidationMessage("surname")

           @Html.ValidationMessage("num")

           @Html.ValidationMessage("add")

           @Html.ValidationMessage("no")

           @Html.ValidationMessage("course")

           @Html.ValidationMessage("grade")
       </form>
       <select name="courses">
           <option value="1" id="test">S7</option>
           <option value="2">Commerce</option>
       </select>

A: Validator.Range will validate if a numeric value is between minimum and maximum. Looks like you want to validate the length of the input, so you should use Validator.StringLength().


text:
Q: Wordpress View profile page I need to create a public Profile page for wordpress. I have create a page named profile and created page file named profile.php in the current wp theme folder. Which is working correct for me.
The next I need to do is to rewrite the profile page as /profile/username, I have done server httaccess rewrites and add add_rewrite_rule function in it , But its not working properly for me.

A: after extensive search, I have got answer to do that. The following page is describing about it.
https://wordpress.stackexchange.com/questions/58683/how-to-create-a-front-end-user-profile-with-a-friendly-permalink


text:
Q: Data disapearing after AJAX request I'm learning jquery and using fake data for Ajax requests. Here is simple HTML:

$(function() {
  $('.tasks__form').on('submit', function() {
    let id = $('.tasks__input').val();
    $.ajax({
      type: 'GET',
      url: 'https://jsonplaceholder.typicode.com/todos',
      data: {
        id: id
      },
      caches: false,
      dataType: 'json',
      success: function(result) {
        console.log(result);
      },
    }).done(function(data) {
      $.each(data, function(key, value) {
        $.each(value, function(indexInArray, valueOfElement) {
          $('.tasks').append('
' + valueOfElement + '
');
        });
      });
    });
  });
});

    <form action="#" method="GET" class="tasks__form">
      <input class="tasks__input" name="send-id" type="text" placeholder="Type an id" />
      <button name="send-id" type="submit" class="tasks__button">
            Find task by id
          </button>
    </form>

Everything was working yesterday. But today, when I run the script, it builds divs with data and then everything disappears (without reloading).


text:
Q: How do I resolve this filtering challenge in data to DataFrame? My data in code snippet below refers.
I'm stuck in trying to filter out values inside the list of dictionaries in step2.
**Desired goal:**

0      0.00\0.00
1    1.765\n2.035
2      0.00\n0.00
3      1.65\n2.21

Where 0.00 values are filtered-out because 'P' the specific key-value is not desired ie. 8.50 in this case. I only want to return values of 6.00 and default any other to 0.00 .
Updated:
I've added extra line of data where both key 'P' is missing & has negative value. This is throwing KeyError in both solutions provided. How best to handle the KeyError inside the solutions provided?
Step1:

data = [[{'A': 2.25, 'G': 17, 'P': 8.50, 'T': 9},
  {'A': 1.63, 'G': 17, 'P': 8.50, 'T': 10}],
 [{'A': 1.765, 'G': 17, 'P': 6.00, 'T': 9},
  {'A': 2.035, 'G': 17, 'P': 6.00, 'T': 10}],
 [{'A': 2.33, 'G': 17, 'P': 8.50, 'T': 9},
  {'A': 1.59, 'G': 17, 'P': 8.50, 'T': 10}],
 [{'A': 1.65, 'G': 17, 'P': 6.00, 'T': 9},
  {'A': 2.21, 'G': 17, 'P': 6.00, 'T': 10},
[{'A': 2.046, 'G': 8, 'T': 6}, {'A': 2.245, 'G': 2, 'P': -1.5, 'T': 7}]]

Step2:

df = pd.Series(pd.DataFrame(data).applymap(lambda x:x['C']).astype('str').values.tolist()).str.join("\n")
df
0      2.25\1.63
1    1.765\n2.035
2      2.33\n1.59
3      1.65\n2.21

As you can see, values in rows (0) & (3) should read 0.00\n0.00 as desired.
Help is very much appreciated.

A: This matches your output. Column 2 is the output:
Input:
data = [[{'A': 2.25, 'G': 17, 'P': 8.50, 'T': 9},
  {'A': 1.63, 'G': 17, 'P': 8.50, 'T': 10}],
 [{'A': 1.765, 'G': 17, 'P': 6.00, 'T': 9},
  {'A': 2.035, 'G': 17, 'P': 6.00, 'T': 10}],
 [{'A': 2.33, 'G': 17, 'P': 8.50, 'T': 9},
  {'A': 1.59, 'G': 17, 'P': 8.50, 'T': 10}],
 [{'A': 1.65, 'G': 17, 'P': 6.00, 'T': 9},
  {'A': 2.21, 'G': 17, 'P': 6.00, 'T': 10}]]
df = pd.DataFrame(data)

Code:
df[2] = df[0].apply(lambda x: ['0.00\\0.00'  for (a,b) in x.items() if a == 'P' if b == 8.5]).str[0]
df[2] = (df[2].fillna(df[0].apply(lambda x: [f'{b}' for (a,b) in x.items() if a == 'A']).str[0] + '\n' +
         df[1].apply(lambda x: [f'{b}' for (a,b) in x.items() if a == 'A']).str[0]))
df

Output:
Out[1]:
                                         0  \
0   {'A': 2.25, 'G': 17, 'P': 8.5, 'T': 9}
1  {'A': 1.765, 'G': 17, 'P': 6.0, 'T': 9}
2   {'A': 2.33, 'G': 17, 'P': 8.5, 'T': 9}
3   {'A': 1.65, 'G': 17, 'P': 6.0, 'T': 9}

                                          1              2
0   {'A': 1.63, 'G': 17, 'P': 8.5, 'T': 10}      0.00\0.00
1  {'A': 2.035, 'G': 17, 'P': 6.0, 'T': 10}   1.765\n2.035
2   {'A': 1.59, 'G': 17, 'P': 8.5, 'T': 10}      0.00\0.00
3   {'A': 2.21, 'G': 17, 'P': 6.0, 'T': 10}     1.65\n2.21

Full Explanation and output with more intermediate columns:
data = [[{'A': 2.25, 'G': 17, 'P': 8.50, 'T': 9},
  {'A': 1.63, 'G': 17, 'P': 8.50, 'T': 10}],
 [{'A': 1.765, 'G': 17, 'P': 6.00, 'T': 9},
  {'A': 2.035, 'G': 17, 'P': 6.00, 'T': 10}],
 [{'A': 2.33, 'G': 17, 'P': 8.50, 'T': 9},
  {'A': 1.59, 'G': 17, 'P': 8.50, 'T': 10}],
 [{'A': 1.65, 'G': 17, 'P': 6.00, 'T': 9},
  {'A': 2.21, 'G': 17, 'P': 6.00, 'T': 10}]]
df = pd.DataFrame(data)

#condition of a key-value pair being P and 8.5...
# ...calling x.items() allows you to simultaneously loop through key value pairs
# ...and return the desired output for the condition while NaN for those that don't meet it
#... we use list comprehension to achieve this and you can use `.str[0]` to transform from list with one value to value
df[2] = df[0].apply(lambda x: ['0.00\\0.00'  for (a,b) in x.items() if a == 'P' if b == 8.5]).str[0]

#... just like above logic is easier but conditionally return values if A for column 1
df[3] = df[0].apply(lambda x: [f'{b}' for (a,b) in x.items() if a == 'A']).str[0]

#... just like above logic is easier but conditionally return values if A for column 2
df[4] = df[1].apply(lambda x: [f'{b}' for (a,b) in x.items() if a == 'A']).str[0]

# fill NaN values for column 3 with combined string of columns 4 and 5
df[5] = df[2].fillna(df[3] + '\n' + df[4])
df
Out[839]:
                                         0  \
0   {'A': 2.25, 'G': 17, 'P': 8.5, 'T': 9}
1  {'A': 1.765, 'G': 17, 'P': 6.0, 'T': 9}
2   {'A': 2.33, 'G': 17, 'P': 8.5, 'T': 9}
3   {'A': 1.65, 'G': 17, 'P': 6.0, 'T': 9}

                                          1          2      3      4  \
0   {'A': 1.63, 'G': 17, 'P': 8.5, 'T': 10}  0.00\0.00   2.25   1.63
1  {'A': 2.035, 'G': 17, 'P': 6.0, 'T': 10}        NaN  1.765  2.035
2   {'A': 1.59, 'G': 17, 'P': 8.5, 'T': 10}  0.00\0.00   2.33   1.59
3   {'A': 2.21, 'G': 17, 'P': 6.0, 'T': 10}        NaN   1.65   2.21

              5
0     0.00\0.00
1  1.765\n2.035
2     0.00\0.00
3    1.65\n2.21

A: update with dict's get method.
df = pd.DataFrame(data)
df.apply(lambda x: f'''
{x[0]['A'] if x[0].get('P', 0) == 6.00 else '0.00'}
{x[1]['A'] if x[1].get('P', 0) == 6.00 else '0.00'}
'''.strip(), axis=1)

same solution with different denote:
df.apply(lambda x: [
         str(x[col]['A'])
           if x[col].get('P', 0) == 6.00
           else '0.00'
         for col in df.columns
], axis=1).str.join('\n')

data = [[{'A': 2.25, 'G': 17, 'P': 8.50, 'T': 9},
  {'A': 1.63, 'G': 17, 'P': 8.50, 'T': 10}],
 [{'A': 1.765, 'G': 17, 'P': 6.00, 'T': 9},
  {'A': 2.035, 'G': 17, 'P': 6.00, 'T': 10}],
 [{'A': 2.33, 'G': 17, 'P': 8.50, 'T': 9},
  {'A': 1.59, 'G': 17, 'P': 8.50, 'T': 10}],
 [{'A': 1.65, 'G': 17, 'P': 6.00, 'T': 9},
  {'A': 2.21, 'G': 17, 'P': 6.00, 'T': 10}],
[{'A': 2.046, 'G': 8, 'T': 6},
 {'A': 2.245, 'G': 2, 'P': -1.5, 'T': 7}]
]

output:
0      0.00\n0.00
1    1.765\n2.035
2      0.00\n0.00
3      1.65\n2.21
4      0.00\n0.00
dtype: object


text:
Q: Chi-Square Test Statistic Help
SOA Exam C Question #140

Solution

My question is, how did they solve the expected counts 4.8, 3.3 etc?
I understand the overall solution but I can't just get how they ended up with that expected count. Thank you.

A: The expected counts in each interval are computed by taking the hypothesized probability of an observation occurring in that interval, and multiplying by the total number of observed events in your sample.  So for the interval $(0, 500]$, we have $F(500) = 0.27$, so for $n = 30$, we should see $(0.27)(30) = 8.1$ events.
For the next interval, you simply calculate $$\Pr[500 < X \le 2498] = F(2498) - F(500) = 0.55 - 0.27 = 0.28,$$ then multiply by $30$ to get $8.4$.  The rest is similar.
However, since you don't know in advance which groupings will result in each expected count in each group exceeding $5$, you would calculate the expected count for each percentile in the second table; so this is where the $4.8$, $3.3$, etc. numbers come from:  they arise from computing $$30 F(310), \\ 30(F(500) - F(310)), \\ 30(F(2498) - F(500)), \\ \text{etc}.$$  Then you group them so that each expected count is at least $5$, and this results in the table that is provided.

A: The proportion less than or equal to $310$ according to the null hypothesis is $0.16$.
The proportion less than or equal to $500$ but more than $300$ is $0.27-0.16= 0.11.$
The proportion less than or equal to $2498$ but greater than $500$ is $0.55-0.27 = 0.28$
And so on.
Now multiply all of those by $30,$ since that's how many claims you've got.
Then apply the rule that a group where the expected number is less than $5$ must be conjoined with an adjacent group.


text:
Q: jquery пробежать по всем дочерним элементам Мне необходимо найти все элементы с классом incorrect, когда у меня есть this объекта одного из input в таблице (не важно какого), после этого по набору этих полей мне надо пробежать и посчитать их количество, если текст уникален то класс я удаляю.
Все инпуты для выборки имею класс typeahead
function ValidProduct(Obj,Metka){
    var Input = $(Obj);
    console.log("--",Input.closest('tbody').find('input.typeahead.incorrect').length);
    Input.closest('tbody').find('input.typeahead.incorrect').each(function(){
                console.log(this);
    });

}

И вот получается что this объект функции не учитывается в обходе. Что не так?

A: $.each принимает 2 аргумента. Первый как индекс, и второй как само значение (в данном случае - объект):
function ValidProduct(Obj, Metka) {
        var Input = $(Obj);

        console.log("--", Input
            .closest('tbody')
            .find('input.typeahead.incorrect')
            .length);

        Input
            .closest('tbody')
            .find('input.typeahead.incorrect')
            .each(function (index, object) {
                console.log(object);
            });
    }