text:
Q: could not able to open the gallery after connecting to a webservice I can connect to a webservice but what I want to do is after connecting the webservice I want to open the gallery and choose a video from there. Could you please help me where is the problem?
here is my code:
package com.isoft.uploader;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class UploaderActivity extends Activity
{

//ArrayList<Response> WebData= new ArrayList<Response>();
public static final int SELECT_VIDEO=1;
public static final String TAG="UploadActivity";
String path="";
final String NAMESPACE = "http://tempuri.org/";
final String SERVICEURL = "http://192.168.10.177/androidws/isandroidws.asmx";
final String METHOD_NAME1="OzelVeriAlanlariniGetir";
final String METHOD_NAME="KullaniciGiris";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button enter=(Button)findViewById(R.id.Enter);
    final EditText username=(EditText)findViewById(R.id.username);
    final EditText password=(EditText)findViewById(R.id.password);
    enter.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View arg0)
        {
            // TODO Auto-generated method stub
            //request code for Webservice
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
            //sending the username to the webservice
            request.addProperty("kullaniciAdi",username.getText().toString());
            //sending the password to the webservice
            request.addProperty("password",password.getText().toString());
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            //Putting the request in an envelope
            envelope.setOutputSoapObject(request);
            HttpTransportSE transport = new HttpTransportSE(SERVICEURL);
            try
            {
                 transport.call("http://tempuri.org/"+METHOD_NAME, envelope);
                 //getting the response from the webservice
                 Integer response = (Integer) envelope.getResponse();
                 if(response!=0)
                 {
                    openGaleryVideo();
                 }//end of if statement
            }//end of try
            catch(Exception exception)
            {
                exception.printStackTrace();
            }//end of catch

        }//end of onClick method
    });//end of OnclickListener method
}//end of onCreate method

public void openGaleryVideo()
{
    Intent intent=new Intent();
    intent.setType("video/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Video"),SELECT_VIDEO);
}//end of openGaleryVideo method

public String getPath(Uri uri)
{
    String[] projection = { MediaStore.Video.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}//end of getPath method
}//end of main

A: Maybe the Android class AsyncTask can be helpfull.
make the WebService request on doInBackground method and show the gallery on postExecute method.
more info: AsyncTask on Android doc
Update:
Replace the onclick method content with:
AsyncTask<String, Void, Integer> task = new AsyncTask<String, Void, Integer>(){

    @Override
    protected Integer doInBackground(String... params) {

        // TODO Auto-generated method stub
        //request code for Webservice
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        //sending the username to the webservice
        request.addProperty("kullaniciAdi",username.getText().toString());
        //sending the password to the webservice
        request.addProperty("password",password.getText().toString());
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        //Putting the request in an envelope
        envelope.setOutputSoapObject(request);
        HttpTransportSE transport = new HttpTransportSE(SERVICEURL);
        try
        {
             transport.call("http://tempuri.org/"+METHOD_NAME, envelope);
             //getting the response from the webservice
             return (Integer) envelope.getResponse();
        }//end of try
        catch(Exception exception)
        {
            exception.printStackTrace();
        }//end of catch
        return 0;
    }

    protected void onPostExecute(Integer result) {
        if(result!=0)
        {
           openGaleryVideo();
        }//end of if statement
    };
};

A: here is the solution:
package com.isoft.uploader;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class UploaderActivity extends Activity
{

//ArrayList<Response> WebData= new ArrayList<Response>();
public static final int SELECT_VIDEO=1;
public static final String TAG="UploadActivity";
String path="";
final String NAMESPACE = "http://tempuri.org/";
final String SERVICEURL = "http://192.168.10.177/androidws/isandroidws.asmx";
final String METHOD_NAME1="OzelVeriAlanlariniGetir";
final String METHOD_NAME="KullaniciGiris";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button enter=(Button)findViewById(R.id.Enter);
    final EditText username=(EditText)findViewById(R.id.username);
    final EditText password=(EditText)findViewById(R.id.password);
    final  AlertDialog ad=new AlertDialog.Builder(this).create();
    enter.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View arg0)
        {
            // TODO Auto-generated method stub
            //request code for Webservice
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
            //sending the username to the webservice
            request.addProperty("kullaniciAdi",username.getText().toString());
            //sending the password to the webservice
            request.addProperty("password",password.getText().toString());
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            //Putting the request in an envelope
            envelope.setOutputSoapObject(request);
            HttpTransportSE transport = new HttpTransportSE(SERVICEURL);
            Object response = null;
            try
            {
                 transport.call("http://tempuri.org/"+METHOD_NAME, envelope);
                 //getting the response from the webservice
                 response= envelope.getResponse();
            }
            catch(Exception exception)
            {
                exception.printStackTrace();
            }//end of catch
            if(response!=null && Integer.parseInt(response.toString()) != 0)
            {
                openGaleryVideo();
            }
            else
            {
                ad.setMessage("Lütfen Kullanıcı Adınızı ve Şifrenizi Kontrol Ediniz.");
                ad.show();
            }

        }//end of onClick method

    });//end of OnclickListener method
}//end of onCreate method
public void openGaleryVideo()
{
    Intent intent=new Intent();
    intent.setType("video/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Video"),SELECT_VIDEO);
}//end of openGaleryVideo method

public String getPath(Uri uri)
{
    String[] projection = { MediaStore.Video.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}//end of getPath method
}//end of main


text:
Q: How to Escape "%" in parameters.yml symfony2 I would like escape a character % in file : parameters.yml, because my password begin by %
database_driver3: pdo_sqlsrv
database_host3: 192.168.10.10
database_port3: 1455
database_name3: MyDB
database_user3: sa
database_password3: %ABC$Admin_2012%

What I really should be doing ?

A: The easiest way is to simply add quotes to the values you want to escape
database_password3: "%ABC$Admin_2012%"

OR by using double % credit - skowron-line
database_password3: %%ABC$Admin_2012%%

redpajama_set_name: RedPajamaStackExchange


text:
Q: If I fill a GridView with anonymous objects, how can i get their properties? I have a GridView what I fill through a LINQ expression.
Something like this:
GridView1.DataSource = from c in customers, o in c.Orders,
  total = o.Total where total >= 2000 select new {id = c.CustomerID,
  order = o.OrderID, total = total};

And in its RowCreated method I try to get a property, for example the id, but it has no a known type:
object element = e.Row.DataItem;
int id = element.id; // It's bad!!!!!!

How can I do?
Thanks!!

A: Name your type!
public class GridType
{
    public int Id {get; set:} . . etc
}

then in linq,
. . . select new GridType {...etc}

Then in the RowCreated method, cast the dataitem to GridType, and you can ccess it's properties.
Otherwise your looking for duck typeing which C# doesn't do.

A: You need to use reflection.
Type t = element.GetType();
int id = 0;

foreach (PropertyInfo p in t.GetProperties())
{
    // Not very nice but finds an integer property called "id"
    if (p.PropertyType == typeof(int) && p.Name == "id")
    {
       id = (int)p.GetValue(element, null);
    }
}

Using Linq:
Type t = element.GetType();
int id = 0;
var pt = new List<PropertyInfo>();
pt.AddRange(t.GetProperties());
id = (int)pt.Where(p => p.PropertyType == typeof(int) && p.Name == "id").First().GetValue(element, null);

Not sure it reads any better though, especially as Type.GetProperties returns an array which has to be converted to a List to get at the Linq methods.

A: This is the cost you have to pay if you want to use anonymous objects : you loose the strong typing when you leave the scope where your object is declared. I'd recommend to explicitly declare your type, unless you want to play with DataBinder.Eval...


text:
Q: How change String to Date format I have this string: 2018-09-22 10:17:24.772000
I want to convert it to Date:
 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");

    String sdate = "2018-09-22 10:17:24.772000";
    Date dateFrom = simpleDateFormat.parse(sdate);

but it shows: Sat Sep 22 10:17:24 GMT+03:30 2018

A: Here is what you should do instead, you are printing date object itself, you should print its format.
I will provide the code with old date api and new local date api :
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");

    String sdate = "2018-09-22 10:17:24.772000";
    Date dateFrom = simpleDateFormat.parse(sdate);

    System.out.println(dateFrom); // this is what you do
    System.out.println(simpleDateFormat.format(dateFrom)); // this is what you should do

    // below is from new java.time package

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
    System.out.println(LocalDateTime.parse(sdate, formatter).format(formatter));

output is :
Sat Sep 22 10:30:16 EET 2018
2018-09-22 10:30:16.000000

2018-09-22 10:17:24.772000

A: Looks to me like you have converted it to a Date. What is your desired result? I suspect what you are wanting to do is to create another Simple date format that shows your expected format and then use simpledateformat2.format(dateFrom)
I should also point out based on past experience that you should add a Locale to your simple date formats otherwise a device with a different language setting may not be able to execute this code
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS", Locale.US);

A: Hope This will help you
public class Utils {

    public static void main(String[] args) {

        String mytime="2018-09-22 10:17:24.772000";
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss.SSSSSS");

        Date myDate = null;
        try {
            myDate = dateFormat.parse(mytime);

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

        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
        String finalDate = timeFormat.format(myDate);

        System.out.println(finalDate);
    }
}


text: Q: Is there an existing function in ArcGIS native API for triangulation? Consider this question. Is there an existing algorithm in ArcGIS runtime sdk to get a list of coordinates and bearings and return the estimated location?


text:
Q: Login failed for user 'WIN-J9A67LA4GER\shahidostovari_web' I uploaded my first asp.net web site
at the local host I didn't any problem with register on site but on server I have this problem
When I want to create an account for first time at Register page , I see this error :
Login failed for user 'WIN-J9A67LA4GER\shahidostovari_web'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'WIN-J9A67LA4GER\shahidostovari_web'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[SqlException (0x80131904): Login failed for user 'WIN-J9A67LA4GER\shahidostovari_web'.]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5352431
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1691
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +69
   System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +30
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +317
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +891
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +518
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +278
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +38
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +732
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +85
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1057
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +78
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +196
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +146
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +16
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +94
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +110
   System.Data.SqlClient.SqlConnection.Open() +96
   System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__38(DbConnection t, DbConnectionInterceptionContext c) +10
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
   System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +360
   System.Data.Entity.SqlServer.<>c__DisplayClass31.<UsingConnection>b__2f() +337
   System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +10
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +189
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) +78
   System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act) +238
   System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act) +556
   System.Data.Entity.SqlServer.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +250
   System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +87

[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
   System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +271
   System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +33

[ProviderIncompatibleException: An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure.]
   System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +246
   System.Data.Entity.Infrastructure.<>c__DisplayClass1.<ResolveManifestToken>b__0(Tuple`3 k) +32
   System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +72
   System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection connection) +251
   System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest) +56
   System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +43
   System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +62
   System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +123
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +610
   System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps() +17
   System.Data.Entity.Database.Exists() +36
   Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext`1.IsIdentityV1Schema(DbContext db) +138
   Basije_daneshgah_marvdasht.UserManager..ctor() +46
   Account_Register.CreateUser_Click(Object sender, EventArgs e) +27
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9750842
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +196
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

A: Your application can't login to the database.
Check if WIN-J9A67LA4GER\shahidostovari_web exists as a login on the database server and if it's password is correct in the connectionstring (if you use one).
Also be careful with posting this kind of information...
It's better to hide the actual user


text:
Q: Updating hexadecimal values in DB2 I have extra characters in my table 'XYZ'. I am comparing the data of this table with other tables. Now XYZ has some extra characters and I want to update the hexadecimal values in other tables. How can I write an update statement for this in DB2 ?
For example : I have character with hex value : 4C6F6E646F6E, I am trying regex to replace 6E to 6F like this :
SELECT REGEXP_REPLACE('LONDON', '\x6E','\x6F') FROM SYSIBM.SYSDUMMY1;

A: Try either of the following equivalent expressions:
SELECT
  STR_ORIG
, STR_REPL
, HEX(STR_ORIG) HEX_ORIG
, HEX(STR_REPL) HEX_REPL
FROM
(
SELECT
  T.STR STR_ORIG
--, REGEXP_REPLACE(T.STR, x'6E', x'6F')  STR_REPL
, REGEXP_REPLACE(T.STR, '\x6E', x'6F')  STR_REPL
FROM (VALUES 'London') T (STR)
);

|STR_ORIG|STR_REPL     |HEX_ORIG    |HEX_REPL                  |
|--------|-------------|------------|--------------------------|
|London  |Loodoo       |4C6F6E646F6E|4C6F6F646F6F              |


text:
Q: Images generated by a button are not loading on first click I am attempting to make a page where you can use buttons to switch between images on a canvas. The images (real time stream data) do not appear on the first click of the button but after clicking around on them or other buttons, will all appear eventually. The images are all very small, and I have tried using an context.onload command but that doenst help.
www.cooswatershed.org/streamdata
Here is how I am drawing them in:
<button id="clickme" onclick="changewfk()">West Fork Millicoma</button>

<canvas id="myCanvas" width="700" height="504"></canvas>


text:
Q: Corona sdk display multi line notification I have some notifications in Corona. The problem is, the text is too big, and I would need to show bigger (multi line) notifications, like the Gmail app, for example. Here is what the notifications look like now:

Here is my code:
local notificationOptions =
{
  alert = text,
  badge = 2,
  sound = "alarm.caf",
  custom = { foo = "bar" }
}

 local notification = notifications.scheduleNotification( nextScheduleTime +  ( day + math.floor(day/7)) * 24 * 60 * 60, notificationOptions )

Any idea how to do this?

A: The notifications by default are not provide multilines.
To use several lines, you have to NotificationCompat.BigTextStyle() in Java (sample) or use your custom or native custom View (example).
Unfortunately, I've not found how you can touch the default view in order to override
Manual:
https://docs.coronalabs.com/daily/guide/events/appNotification/index.html#TOC
and here:
https://docs.coronalabs.com/daily/plugin/notifications/scheduleNotification.html
in the second link you can see that only this properties are used:

alert (optional) String. The notification message to be displayed to
  the user. If the application is not currently running, a system alert
  will display this message. badge (optional) Number. The badge number
  to be displayed on the application icon when the scheduled
  notification triggers. This replaces the last badge number that was
  applied. Set to 0 to omit the badge number. This option is not
  supported on Android. sound (optional) String. Name of the sound file
  in the system.ResourceDirectory to be played when the scheduled
  notification triggers. This sound is only played if the app is not
  currently in the foreground. On iOS, there are limitations on the
  kinds of sound that can be played (consult Apple's documentation for
  more details). custom (optional) Table. A table that will be delivered
  with the notification event. This allows you to pass custom
  information with the notification.

In conclusion, there is no proper way to do it nowadays.


text:
Q: Is any alternative way to implement custom webpart(coding) in sharepoint online? Microsoft has Removing Code-Based Sandbox Solutions in SharePoint Online then how to deploy custom webpart Is any alternative way?

A: Now, you can't deploy any Code-Based Sandbox Solutions/custom webparts directly in SharePoint online. But in SharePoint provider hosted app you can use server side code/C#.
Apart from this, You can use JSOM, REST API based solutions, SharePoint hosted apps in SharePoint online.

A: In addition to Vishal's answer, there is also the new client-side development framework called 'SharePoint Framework' (spfx) which is currently in the preview phase.
https://blogs.office.com/2016/05/04/the-sharepoint-framework-an-open-and-connected-platform/


text:
Q: Resty-GWT and HandlerExceptionResolver: How do I deal with special cases? I'm using GWT and Resty for my web app.
I need to treat two exceptions as special cases and pass additional information to the client. These previously were handled by the Resty calls onFailure() method, as follows:
    getClientFactory().getRequest().restyMethod(id,
        new MethodRecipient<DataDTO>() {
            @Override
            public void onSuccess(Method method, DataDTO response) {
                // do stuff
            }
            @Override
            public void onFailure(Method method, Throwable ex) {
                if (ex.getMessage().endsWith("exception message 1")) {
                    getClientFactory().getAppController().showRestFatalError("Message 1", "Title 1", errorMsg);
                } else if (ex.getMessage().endsWith("exception message 2")) {
                    getClientFactory().getAppController().showRestFatalError("Message 2", "Title 2", errorMsg);
                } else {
                    // else fall back to a friendly but vague "something else went wrong"
                    getClientFactory().getAppController().showRestFatalError("Unexpected error", "Unexpected Error", errorMsg);
            }
        }
    });

To catch and log all exceptions before they get to the client, I've implemented a custom Spring MVC HandlerExceptionResolver as follows:
I have a custom HandlerExceptionResolver for logging controller errors as below:
    @Component
    public class LoggingHandlerExceptionResolver extends AbstractHandlerExceptionResolver {

        private final Logger logger = LoggerFactory.getLogger(LoggingHandlerExceptionResolver.class);

        @Override
        public ModelAndView doResolveException(HttpServletRequest aReq, HttpServletResponse aRes, Object aHandler, Exception ex) {
            logger.error("Server exception thrown", ex);
            return null; // trigger other HandlerExceptionResolvers
        }
    }

When using the HandlerExceptionResolver, only status code 500 gets passed to the client. How do I get the two special cases to be recognized by the onFailure() method?


text:
Q: Differential Mode EMI Filter Position In the AC input power supplies; input EMI filters(common + differential) are connected between mains and the rectifier. In some low power power supplies; only differential mode filter is used and this filter is used after the rectifier. What's the reson behind that?
Examples:


text:
Q: Other criteria for a set to be an ordinal. I'm reading up on ordinals, and I've come across various definitions for what it means to be an ordinal. The main book that I'm following is Kunen's Set Theory book. He defines an ordinal as a set that is transitive and is well-ordered by $\in$.
I found a couple of exercises in his book that relates his definition of an ordinal to other definitions that I've seen. I'm trying to figure these out to make more sense of the definitions and concepts in Kunen's book and connect his definition with other definitions I've seen. The exercises both assume the Foundation Axiom and are as follows:

$z$ is an ordinal iff $z$ is a transitive set and $\in$ satisfies trichotomy on $z$.
  Hint: $z \cap ON$ is an ordinal by a previous lemma. Then, use trichotomy to derive a contradiction from an $\in$-minimal element of $z \backslash ON$, where $ON$ denotes the class of all ordinals.

Showing $(\Rightarrow)$ seemed to follow easily since being an ordinal implies transitivity and well-ordering $\in$ implies that $\in$ is well-founded on $z$, implying trichotomy. I'm having trouble setting up the contradiction in $(\Leftarrow)$ by using the hint.

$z$ is an ordinal iff $z$ is a transitive set and all elements of $z$ are transitive sets.

Again, $(\Rightarrow)$ seemed to follow easily since every element of a transitive set is also transitive. As for $(\Leftarrow)$, I'm stuck.
As always, I would really appreciate any help/hints for these exercises.

A: Suppose that $z$ is transitive, and $\in$ satisfies trichotomy on $z$. Suppose that $z\nsubseteq\mathbf{ON}$, and let $x$ be $\in$-minimal in $z\setminus\mathbf{ON}$. Then $x\subseteq z\cap\mathbf{ON}$ by transitivity of $z$ and $\in$-minimality of $x$. Let $\alpha=z\cap\mathbf{ON}\in\mathbf{ON}$; $x\subseteq\alpha$. Suppose that $\xi\in\alpha$; then $\xi\in z$, so either $\xi\in x$, $\xi=x$, or $x\in\xi$. The last two cases contradict the assumption that $x\notin\mathbf{ON}$, so $\xi\in x$. And $\xi\in\alpha$ was arbitrary, so $\alpha\subseteq x$, and hence $x=\alpha\in\mathbf{ON}$, a contradiction. It follows that $z\subseteq\mathbf{ON}$, so $z$ is well-ordered by $\in$ and therefore an ordinal.
For the second one, proceed in exactly the same fashion up to the point at which we observe that $x\subseteq\alpha$. Now $x$ is a transitive set of ordinals, so ... ?


text:
Q: Adding speaker 1 and 2 in a titlepage (I think it's simple but I don't know how to do it)
Hi everyone, how do I add two lines on the left and two on the right?
(name1 and name2 in \small, andspeaker in \footenotesize )
\documentclass[a4paper,12pt]{book}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english,italian]{babel}
\usepackage{url,amsfonts,epsfig}
\usepackage{amsmath}
\usepackage{caption}
\usepackage{subcaption}
\usepackage[backend=biber]{biblatex}
\addbibresource{capitoli/bibliografia/bibliografia.bib}
\usepackage{matlab-prettifier} %pacchetto per scrivere come Matlab

\usepackage{fancyhdr}
\pagestyle{fancy}
\renewcommand{\footrulewidth}{0.5pt}
\fancyhead[]{} %pulisce il fancyhead
\fancyhead[LO]{\nouppercase{\rightmark}} %sulle dispari la section
\fancyhead[RE]{\nouppercase{\leftmark}} %sulle pari il capitolo
\fancyfoot{}
\fancyfoot[LO,RE]{\thepage} %numeri di pagina, a sinistra sulle dipari, a destra sulle pari

%\usepackage{pdfpages}

%queste due righe servono per non far apparire i numeri dei capitoli e delle sezioni nei fancyhead
%\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markright{#1}}
\parindent 0ex %serve per l'indentadure dei paragrafi

%paccheetto per i grafici
\usepackage{tikz}
\usepgflibrary{arrows.meta}
\usetikzlibrary{calc,quotes,angles}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16} %l'ho messo a caso per il grouplot
\usepgfplotslibrary{groupplots} %l'ho messo a caso per il grouplot
\usetikzlibrary{calc} %ridondante ma per ora lo tengo
\usepackage{comment}

\usepackage{hyperref} %pacchetto Harvard che permette il collegamento da indice

\begin{document}

\begin{titlepage}
    \begin{center}
        \vspace*{0.2 cm}

        \Large
        \textbf{University}\\
        \vspace*{1 cm}
        \includegraphics[width=0.4\textwidth]{titlepage/logo_2}

        \vspace{1cm}
        \large
        Department\\
        \vspace{1cm}
        \small
        faculty\\
        \vspace{1cm}
        \large
        thesis

        \vspace{1 cm}
        \large
        \textbf{title}

        \vspace{2cm}
        \footnotesize
        candidate:\\
        \normalsize
        \textbf{name}\\

        \vspace{1cm}

        \vfill

    \end{center}
\end{titlepage}

A: \documentclass[a4paper,12pt]{book}
\usepackage[demo]{graphicx}

\begin{document}

\begin{titlepage}
\centering
\vspace*{0.2 cm}

\Large
\textbf{University}

\vspace*{1 cm}

\includegraphics[width=0.4\textwidth]{titlepage/logo_2}

\vspace{1cm}
\large
Department

\vspace{1cm}
\small
faculty

\vspace{1cm}
\large
thesis

\vspace{1 cm}
\large
\textbf{title}

\vspace{2cm}
\footnotesize
candidate:

\normalsize
\textbf{name}

\vspace{1cm}

\begin{minipage}{6cm}
\centering
 \footnotesize
 Speaker 1

 \small
 Name 1
\end{minipage}\hfill
\begin{minipage}{6cm}
\centering
 \footnotesize
  Speaker 2

 \small
 Name 2
\end{minipage}
\end{titlepage}

\end{document}


text:
Q: Cross-domain HTML source extraction using JavaScript Say I am in domain  abc.com. I want to be able to get the HTML source of a page on xyz.com and then parse it using JavaScript. I know there is restriction of same origin policy, and I tried CORSwhich the server at xyz.com does not support. Is it possible to achieve this using JSONP? Can you guys tell me with some code snippets how?

A: for using jsonp, server should bind the response with a function. But in your need, it is not possible. Better think serverside HttpGet() function

A: To be able to use JSONP or CORS, the server must be able to provide support for it. So if you're not in control of xyz.com, and it doesn't provide this already, you can't do it on the client side. Instead, you have to process it on the server side.


text:
Q: What's a good way to bundle and add a whole bunch of JARs into a maven project? ...without specifying each and every one as a separate dependency?
So I have to work with a whole bunch of java dependencies provided by a proprietary third party software in the form of a downloadable SDK. I really want to use maven for dependency and lifecycle management, but also can't be bothered to add several dozens of JARs as individual dependencies. What's the most elegant solution to work around this issue?

A: Each jar must be added as a <dependency> somewhere.
So if you have just one project that uses 100 JARs as dependencies, you need to add all those dependencies (each as a <dependency>) entry.
If you have several projects using the same JARs, I would follow Conffusion's advice to create a POM with the dependencies and then use that POM in all the projects.
Maven cannot add "a directory of JARs" to the dependencies.


text:
Q: Importing libraries from build.xml file in Eclipse I am developing a java app and I need to use jnativehook library. I have downloaded the .zip from https://code.google.com/p/jnativehook/downloads/list . There is a bin folder,src folder,build.xml,build.num and 3 .txt files when I extracted this folder.
I have included this library in my project by File ->  project -> Java project from existing Ant file
And I have tried an example https://code.google.com/p/jnativehook/wiki/examples
But I get the following error
Exception in thread "main" java.lang.ExceptionInInitializerError
    at GlobalKeyListenerExample.main(GlobalKeyListenerExample.java:25)
Caused by: java.lang.RuntimeException: Unable to locate the native library.
    at org.jnativehook.GlobalScreen.loadNativeLibrary(GlobalScreen.java:462)
    at org.jnativehook.GlobalScreen.<init>(GlobalScreen.java:71)
    at org.jnativehook.GlobalScreen.<clinit>(GlobalScreen.java:53)
    ... 1 more

What location should I give in native library path?

A: Looking through the source of GlobalScreen.loadNativeLibrary(), it seems that you get this exception when the library has failed to find the DLL on the java.library.path and instead tries to unpack it from the JAR, only to fail to find it.
Some options for fixing this include:

*

*Checking you are running a supported platform.

*Extract the right DLL from the JAR and place it on the java.library.path.

To use this library, you only need to include the JAR in your project. I don't like the sound of this part of your question:

I have included this library in my project by File -> project -> Java project from existing Ant file

Just download JNativeHook-1.1.4.zip, extract the ZIP and add the JNativeHook.jar JAR to your project.


text:
Q: drawRect not being called on a UIView I've added a UIView to my View Controller. I set its subclass to this newDrawingView.h file.
//
//  newDrawingView.m
//  slate
//
//  Created by Monica Kachlon on 12/2/17.
//  Copyright © 2017 ma. All rights reserved.
//

#import "newDrawingView.h"

@implementation newDrawingView
UIBezierPath *newPath;
CAShapeLayer * layerStyle;

- (void)startTouch:(CGPoint)point;
{
    [newPath moveToPoint:point];
}

- (void)drawRect:(CGRect)rect {
    NSLog(@"DRAWING");
}

- (void)drawShape:(CGPoint)point
{
    [newPath addLineToPoint: point]; // (4)
    [self setNeedsDisplay];
}

- (void)endTouch:(CGPoint)point {
    [newPath removeAllPoints];
}

@end

I manage to handle startTouch, drawShape and endTouch. But, when I do call self setNeedsDisplay - my drawRect doesn't get called..


text:
Q: Perform Login action using ASP.NET MVC 5 with DocumentDB Is there anyone who has managed to make an application that perform a login action and keep the session of a user from a DocumentDB in asp.net mvc 5.
I tried, but I didn't.
I created a model MyUser.cs
public class MyUser
  {

    [JsonProperty(PropertyName = "id")]
    public string id { get; set; }

    [JsonProperty(PropertyName = "mail")]
    public string mail { get; set; }

    [JsonProperty(PropertyName = "password")]
    public string password { get; set; }
  }

A controller MyUserController
public class MyUserController : Controller
  {
    public ActionResult Index()
    {
      var client = DocumentDBRepository.InstantiatesClient();
      var database = DocumentDBRepository.ReadOrCreateDatabase("myDB");
      var collection = DocumentDBRepository.ReadOrCreateCollection(database.SelfLink, "myUsers");
      List<Server_MVC5.Models.MyUser> users = DocumentDBRepository.getMyUsers(collection);
      return View(users);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login([Bind(Include = "email,password")] Models.MyUser myuser)
    {
      if (ModelState.IsValid)
      {
        DocumentDBRepository.Login(myuser.mail, myuser.password);
        return RedirectToAction("Index");
      }

      return View(myuser);
    }

    public ActionResult Login(string email, string password)
    {
      if (email == null)
      {
        return HttpNotFound();
      }

      Models.MyUser myuser = DocumentDBRepository.Login(email, password);
      if (myuser == null)
      {
        return HttpNotFound();
      }

      return View("Index");
    }
  }

A view for login Login.cshtml
@using Server_MVC5.Models
@model LoginViewModel
@{
    ViewBag.Title = "Log in";
}

@ViewBag.Title.

            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()

Use a local account to log in.

                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })

                        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })

                    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })

                        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)

                        <input type="submit" value="Log in" class="btn btn-default" />

                    @Html.ActionLink("Register as a new user", "Register")

                @* Enable this once you have account confirmation enabled for password reset functionality

                        @Html.ActionLink("Forgot your password?", "ForgotPassword")

*@
            }

            @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

I state that DocumentDBRepository is a repo that retrieve info from my DocumentDB Azure Db (it works properly).
When I perform login, it returns ever failure despite the credentials are correct.
Does anyone know how to help me ?

A: I have managed to get asp.net Authentication working using this DocumentDB provider for the new ASP.NET Identity framework Link on git, but haven't heavily tested it yet,but seems to be working fine from what I have done so far.


text:
Q: Need help with refreshing UIView in iPhone SDK I have a simple drill down navigation app. On the detail view, I am drawing a few 20x20 sized UIImages, depending upon the row selected in the navigation items. These images are drawn as subviews over the detail view when a row is selected.Now when I get to the "detail view" I have set up a couple of buttons, which when pressed, will rearrange the small images. For this I need to clear the previous images and redraw them at different places in the view.  I have a method like:
[MyView changeImagePositionwithPosnumber:"number selected by buttons"]
I cannot pass this method when the button is pressed since it draws over the existing images.
How do I refresh the view to pass this method ? Do I need to implement draw rect for this?
I do not quite understand drawrect and am not sure how to implement it.
In short whatever the navigation controller does when you go away from detail view, I want to do, so I can refresh my view and draw new images on it.
Any help on this is greatly appreciated. I am still a newbie.

A: This worked for me:
UIView *view:
for(UIView *subview in [view subviews]) {
    [subview removeFromSuperview];
}
Thanks


text:
Q: skip 2 element in xml code with php I have this XML data:
<root>
 <child>child1</child>
 <child>child2</child>
 <child>child3</child>
</root>

I can parse it with PHP:
$xml = simplexml_load_string($string);

I want to skip the first 2 children and get this result:
<root>
 <child>child3</child>
</root>

Thank you

A: You can query the element you're interested in with an Xpath query:
$xml  = new SimpleXMLElement($string);

$last = $xml->xpath("child[last()]")[0];

Inspired by PHP: How to access the last element in a XML file.

A: If you ask in your question about removing all <child> elements until there is only one left, you can do that with a simple while-loop:
<?php
/**
 * skip 2 element in xml code with php
 *
 * @link https://stackoverflow.com/q/31879798/367456
 */
$string = <<<XML
<root>
 <child>child1</child>
 <child>child2</child>
 <child>child3</child>
</root>
XML;

$xml   = simplexml_load_string($string);

$child = $xml->child;

while ($child->count() > 1) {
    unset($child[0]);
}

$xml->asXML('php://output');

The output is (also: online-demo):
<?xml version="1.0"?>
<root>

 <child>child3</child>
</root>

if you're only concerned to get the last element, use an xpath query as it has been suggested in the other answer. Do not even consider to use the array mish-mash of json encode decode - will only break the data you need to retain in the end.


text:
Q: How do I get the MIME Type from a URI with scheme == "android.resource" I know how to get the MIME Type from an URI when the scheme is "content" or "file". However, I cannot find any solution when the scheme is "android.resource". For example, I have res/raw/video.mp4.
val uri = Uri.parse("android.resource://$packageName/${R.raw.video}")

The uri is good because I can do the following
videoView.setVideoURI(uri)
videoView.start()

Given such an URI, how can I get its mime type (should be "video/mp4" in this case)?

A: You can use MediaMetadataRetriever for media file:
val uri = Uri.parse("android.resource://$context.packageName/${R.raw.video}")
val retriever = MediaMetadataRetriever()
val mimeType = try {
            retriever.setDataSource(context, uri)
            retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)
        } catch (e: Exception) {
            null
        }
Log.d(TAG, "MIME type: $mimeType")

For any other type:
val resId = R.raw.video
val resUri = Uri.parse("android.resource://${context.packageName}/$resId")

val mimeType = tryGetMediaMimetype(context, resUri)
        ?: tryGetImageMimetype(context.resources, resId)
        ?: tryGetMimeTypeFromExtension(context.resources, resId)
Log.d(TAG, "MIME type: $mimeType")

...

fun tryGetMediaMimetype(context: Context, uri: Uri): String? {
    val retriever = MediaMetadataRetriever()
    return try {
        retriever.setDataSource(context, uri)
        retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)
    } catch (e: Exception) {
        null
    }
}

fun tryGetImageMimetype(resource: Resources, resId: Int): String? {
    val options = BitmapFactory.Options()
    options.inJustDecodeBounds = true
    return try {
        BitmapFactory.decodeResource(resource, resId, options)
        options.outMimeType
    } catch (e: OutOfMemoryError) {
        return null
    }
}

fun tryGetMimeTypeFromExtension(resource: Resources, resId: Int): String? {
    val value = TypedValue()
    resource.getValue(resId, value, true)
    val fileName = value.string.toString()

    val dotIndex = fileName.lastIndexOf(".")
    val extension = if (dotIndex >= 0) {
        fileName.substring(dotIndex + 1)
    } else null

    return if (extension != null) {
        MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
    } else null
}


text:
Q: Copula entropy: calculation is borked? I came across a pretty cool paper whose idea makes a lot of sense to me.
Ma, Jian, and Zengqi Sun. "Mutual information is copula entropy." Tsinghua Science & Technology 16.1 (2011): 51-54.
The gist is that the copula is the "rest" of the multivariate distribution after the marginal distributions are considered, so the relationship between the marginal variables, and mutual information also describes the relationship between the marginal variables; thus, the two must be related.
The author has an R package, copent, that implements this copula-based method for calculating mutual information. I am confused about the result of a simulation I did.
#install.packages("copent")
library(copent)
set.seed(2021)
B <- 25 # number of simulations to do
v <- rep(NA, B) # blank vector to hold simulated copula entropy values
for (i in 1:B){
  x <- runif(100) # marginal X variable
  y <- runif(100) # marginal Y variable (independent from X)
  v[i] <- copent::copent(data.frame(x, y)) # Save the copula entropy
}
summary(v)

    Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
-0.29278 -0.23628 -0.19173 -0.19102 -0.16434  0.03681

Positive and negative entropy values? WHAT!?
(Playing around more, these negative values of entropy appear only to happen when x and y are independent.)
What's going on in their method that allows for negative entropy?
(The claim in the paper that mutual information is negative copula entropy has me mystified, too, though perhaps that's a topic for a separate question. If both entropy and mutual information are supposed to be non-negative quantities, that claim means that both are equal to zero, which only can be true for independent variables.)


text:
Q: Article "the" in context Tell me please which sentence is correct.

1) I will vote for those with the characteristics that I like.
2) I will vote for those with characteristics that I like.

I am confused whether I need to use "the" or not. However, I favour the first one.

A: Both are correct with a very slight difference in meaning.
"The characteristics that I like" implies all of the characteristics that I like.
"Characteristics that I like" implies some of the characteristics that I like.


text:
Q: Is there any way to process a push notification when an iOS Device screen is locked? I am building an app for a delivery company where the vehicle drivers phones need to be notified when they are assigned new tasks(immediately), only if the task meets specific criteria.(so putting a long sound file in the push notification is not a solution)
I am able to process the task and generate a long(29s) notifying sound if the app is in the foreground or background by processing the push notification in application(application: UIApplication, didReceiveRemoteNotification userIno: [NSObject: AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
However, this method is not called if the phone's screen is locked. Is there any way of processing received tasks when the phone screen is locked, without the user unlocking the screen?


text:
Q: python exe runs fine manually, but in windows task scheduler it start and then it crashes I created an exe with auto-py-to-exe (onefile).
the exe works fine, but when I want to run this automatically in windows task manager the exe does start, but throw out an error on the location of my file.
data.json
data.json file is in the same folder as my exe file (I do not use a relative path )
Path
So i wanted to solve this by setting in the windows task scheduler 'start in (optional)' and the path of my folder
Start in
then my problem with the path to data.json is solved, but my script crashes at the outlook api to read the mails.
If I run the program manually everything works fine.
Has anyone had the same experience and found a solution?


text:
Q: Flutter - How to display markdown text in sliver I'm trying to run Markdown widget (package: flutter_markdown 0.2.0) inside a SliverList but I have some issues.
Ideally I would like to execute a Markdown widget inside an ExpandTile widget inside a Sliver, but for now I just want to solve the problem of Markdown child of a Sliver.
The code I'm posting give me issues:

*

*I see correctly the markdown text but the app is freezed (I can't scroll, I can't do nothing). I have this behaviour when I use the widget MarkdownBody

*I see an error message when I use the widget Markdown:
I/flutter (31761): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (31761): The following assertion was thrown during performResize():
I/flutter (31761): Vertical viewport was given unbounded height.
I/flutter (31761): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter (31761): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter (31761): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter (31761): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter (31761): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter (31761): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter (31761): the height of the viewport to the sum of the heights of its children.
I/flutter (31761):
...

This is the full code of my example:

import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';

const String _markdownData = """# Markdown Example
Markdown allows you to easily include formatted text, images, and even formatted Dart code in your app.

## Styling
Style text as _italic_, __bold__, or `inline code`.

- Use bulleted lists
- To better clarify
- Your points

## Links
You can use [hyperlinks](hyperlink) in markdown

## Images

You can include images:

![Flutter logo](https://flutter.io/images/flutter-mark-square-100.png#100x100)

## Markdown widget

This is an example of how to create your own Markdown widget:

    new Markdown(data: 'Hello _world_!');

## Code blocks
Formatted Dart code looks really pretty too:

void main() {
  runApp(new MaterialApp(
    home: new Scaffold(
      body: new Markdown(data: markdownData)
    )
  ));
}

Enjoy!
""";

void main() {
  runApp(MaterialApp(
      title: "Markdown Demo",
      home: Scaffold(
          appBar: AppBar(title: const Text('Markdown Demo')),
          body: Container(
              child: CustomScrollView(slivers: <Widget>[
            SliverList(
              delegate:
                  SliverChildListDelegate([Markdown(data: _markdownData)]),
            )
          ])))));
}

EDIT: I solved the issue
The problem was in this line of code:
![Flutter logo](https://flutter.io/images/flutter-mark-square-100.png#100x100)

The image don't exist and this freeze the app.

A: Use SliverToBoxAdapter instead of SliverList


text:
Q: Execute Final script only on build failure I want to execute an arbitrary shell script, but I only want it to run on build failure.  Is there some way to either:

*

*Set up Bamboo to run this script only on build failure

*Or check from within the script whether the build was successful.  Perhaps an environment/build variable?

Thoughts and ideas appreciated!

A: bamboo unfortunately lacks a way to trigger something on failure. You can not launch other plan, other stage and so on - you can only send basic notification.
As some workaround, you can move all the jobs to one stage, and have the script in the Final section. You can pass ${bamboo.buildNumber} to your script, and based on that number request status data from https://user:password@yourproject.atlassian.net/builds/rest/api/latest/result/PROJECT/BUILD_NUMBER.json?expand=stages.stage.results - then you only have to parse the json and get your build state from json['stages']['stage'][0]['state']

A: My solution to this issue is more rudimentary and consists of 3 custom tasks:

*

*one at the end of the tasks list which creates a status file, name is arbitrary but consistent, e.g. build.success

*one at the beginning of the tasks list that deletes the status file (in case workdir directory cleanup is not enabled)

*one task in the beginning of the final tasks list which checks on the existence of build.success file and acts accordingly

My use case for the above is sending notifications to IM system not supported by Bamboo plugins (RocketChat). Current limitations:

*

*final tasks which run after the first one (that consumes the build.success file) and fail are not detected

*no detection of stopped runs: the final task is always executed

*complex logic when there are multiple stages, e.g. I add an extra initial stage for sending notifications at build start and an extra stage at the end for sending a "successful build" notification

It's ridiculous that a CI/CD system would not implement some kind of env var like "bamboo.build.result".


text:
Q: How to run a function after another function in Swift 3 I am new to swift 3, and I got stuck to this problem. I have two functions, the first function gets the value of a key in my FirebaseDatabase. The second function displays a the variable retrieved from the FirebaseDatase inside a TableView. The problem is that the second function launches before the first one. This makes the value return nil.
First function:
        self.shopItems = [String]()

        databaseRef.observe(FIRDataEventType.value, with: { (snapshot) in
                for child in snapshot.children {
                    let snap = child as! FIRDataSnapshot
                    let dictionary = snap.value as! [String: AnyObject]
                    self.shopItems.append(dictionary["Name"] as! String)

                    print(self.shopItems)
            }

        })

The second function:
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: self.cellReuseIdentifier, for: indexPath) as UITableViewCell

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
        cell.textLabel?.text = self.shopItems[indexPath.row]
    })
    return cell
}

I know i can use the Dispatch-Wait method, but I want the second function to wait until the first one is done. How would i do so?

A: Try with this, as I said in my first comment I think you only need call self.tableView.reloadData after print(self.shopItems)
self.shopItems = [String]()
databaseRef.observe(FIRDataEventType.value, with: { (snapshot) in
    for child in snapshot.children {
        let snap = child as! FIRDataSnapshot
        let dictionary = snap.value as! [String: AnyObject]
        self.shopItems.append(dictionary["Name"] as! String)

        print(self.shopItems)
    }
    self.tableView.reloadData()
})

And correctly implement this method
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.shopItems.count
}

Also update your cellForRow to this
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier:
    self.cellReuseIdentifier, for: indexPath) as UITableViewCell

    cell.textLabel?.text = self.shopItems[indexPath.row]
    return cell
}

Hope this helps

A: You are badly confused. You don't call tableView(_:cellForRowAt:). The system calls it.
If you want to wait and reload your table once the data has finished loading, you should put a call to reloadData inside your databaseRef.observe method's closure:
    databaseRef.observe(FIRDataEventType.value, with: { (snapshot) in
            for child in snapshot.children {
                let snap = child as! FIRDataSnapshot
                let dictionary = snap.value as! [String: AnyObject]
                self.shopItems.append(dictionary["Name"] as! String)

                print(self.shopItems)

                //Add the line below.
                //Note that if the closure is called from the background, you'll
                //need to use GCD to call this method on the main thread.
        }
        self.tableView.reloadData()
    }

And, if the completion code in your databaseRef.observe method gets called on a background thread then you'll need to wrap that in a call to Dispatch.main.async() (or a similar method to invoke the code on the main thread.)
DispatchQueue.main.async() {
    self.tableView.reloadData()
}

A: The second function runs when data in the tableview is loaded. When the tableview is created it loads the data from shopitems array into the view. If there are no objects in the array the tableview will appear empty. In order to reflect changes to the shopitems array, in other words reflect that in item has been appended to the array you have to call the appropriate tableview function .
The correct way to do this is to use:
    databaseRef.observe(FIRDataEventType.value, with: { (snapshot) in
            for child in snapshot.children {
                let snap = child as! FIRDataSnapshot
                let dictionary = snap.value as! [String: AnyObject]
                self.shopItems.append(dictionary["Name"] as! String)

                let row = self.shopItems.index(of:self.shopItems.last!)
                let indexPath = IndexPath(row:row, section:0)
                tableView.insertItemsAtIndexPaths([indexPath])

                print(self.shopItems)
        }

    })

.You will have to create an indexPath using the index of the object in the shopitems array.
The other method is to reload all the data in the tableview after append.
    databaseRef.observe(FIRDataEventType.value, with: { (snapshot) in
            for child in snapshot.children {
                let snap = child as! FIRDataSnapshot
                let dictionary = snap.value as! [String: AnyObject]
                self.shopItems.append(dictionary["Name"] as! String)

                print(self.shopItems)
        }

              DispatchQueue.main.async {
            self.tableView.reloadData()
           }

    })


text:
Q: How does Multitenancy work in App Engine with Objectify? How does multi-tenancy with namespaces in app engine works?
My application has multiple users and each users are sort of like tenants in multi-tenancy.
Their URL starts with domain/customer/companyToken#pageName?param1&param2.
So from the Google docs if I want to apply a multi-tenancy with namespace with each customers
you need to assign a unique ids for NamespaceManager to each customers
So something like below:
NamespaceManager.set(request.getServerName());

Now I have a few questions.

*

*How does the multi-tenancy with Namespace for the App Engine really work?

*How does it change the way we access data in general?

*How does it change the way we access data using Objectify?

*First my understanding of applying above to the application is that when retrieving the data all the data related to above customers(tenants) are gathered together in the same namespace, so how does the way we access data change using the Objectify? Currently Company obj serves as parent of all the obj related to customers. (So in case of my application?)
Thank you so much in advance.

A: *

*Google AppEngine is not open-source so only Google really know how this works internally. But there is some publicly-available data about how datastore is built internally: http://www.youtube.com/watch?v=tx5gdoNpcZM. Basically all AppEngine data is in one table (yes one table for ALL AppEngine applications) distributed across multiple computers. Every entity has Key by which it is uniquely identified (id, parent, which you can see in your app), but there is also a data that tells to which app an Entity belongs. This data is AppEngine internal and user does not see it. My guess is that this part is also extended to include namespace data.

*It doesn't. Datastore API is namespace-aware so all you code stays the same. It internally knows to which namespace an Entity belongs.

*Objectify is built on top of low-level Datastore API, so answer is the same as 2.

*Namespaces compartmentalizes data: once you set a namespace, Datastore API will only see Entities that were added under this namespace.

A: *

*At the storage levels of datastore, namespace is just like an app-id.  Each namespace essentially looks to the datastore as another view into the app's data.  This is why operations like query cannot span namespaces (at least for now). Even id ranges are different per namespace.

*You need to be aware of which namespace you're really using.  e.g. Once an entity is created, it's namespace does not change, so doing a NamespaceManager.set(...) will have no effect on its key.  Similarly with a Query object. Once a query is created, its namespace is set. Same with MemcacheService. Hence it's important to know which objects have which namespaces if you're in the habbit of calling NamespaceManager.set more than from the beginning of the request.

*It's hard to know how Obectify uses the datastore API, so changing the current namespace multiple times in one request needs to be done with the knowledge of how Objectify uses the datastore API to ensure you don't inadvertently create entities in unintended namespaces.

*In general, you meed to know when Objectify creates the low level Key, Entity and Query objects and make sure that the current namespace is set to the namespace you intend.  It's easy if there is ever only one namespace per request.


text:
Q: How Prolog's logical update view works for assert and retract? Can someone please explain the Prolog logical view about assert and retract in details?
For example in code below, in the first run Prolog returns true and in subsequent runs returns false. I don't know why because of Prolog logical view when  asserta(nextBound(100)) satisfies, nice(X) is still frozen with values when it started so this change should be ignore  and nextbound(100) must be false.
nextBound(10000).

nice(X) :-
   asserta(nextBound(100)),
   retract(nextBound(10000)),
   nextBound(100).

A: You can do a trace to determine what happens:
| ?- nice(_).
      1    1  Call: nice(_17) ?
      2    2  Call: asserta(nextBound(100)) ?
      2    2  Exit: asserta(nextBound(100)) ?   <-- 1st assert of netBound(100) succeeds
      3    2  Call: retract(nextBound(10000)) ?
      3    2  Exit: retract(nextBound(10000)) ? <-- retract nextBound(10000) succeeds
      4    2  Call: nextBound(100) ?
      4    2  Exit: nextBound(100) ? <-- Succeeds because netBound(100) now a fact
      1    1  Exit: nice(_17) ?

(1 ms) yes
{trace}
| ?- nice(_).
      1    1  Call: nice(_17) ?
      2    2  Call: asserta(nextBound(100)) ?
      2    2  Exit: asserta(nextBound(100)) ?   <-- 2nd assert of netBound(100) succeeds
      3    2  Call: retract(nextBound(10000)) ?
      3    2  Fail: retract(nextBound(10000)) ? <-- retract nextBound(10000) fails
      1    1  Fail: nice(_17) ?

(3 ms) no
{trace}
| ?-

You can see that, in the first case, first the nextBound(100) fact is successfully asserted (for the 1st time). Then, the retract(nextBound(10000)) succeeds because nextBound(10000). is a fact which exists in the data. Following that, the query nextBound(100) succeeds because two steps before this fact was asserted into the data.
On the second execution of nice(_), nextBound(10000) doesn't exist because it was retracted in the first execution, and the code doesn't re-assert it. So, in the second execution of nice(_), retract(nextBound(10000)) fails because the fact nextBound(10000) doesn't exist and the entire second execution of nice(_) fails at that point since backtracking over asserta and retract do not re-execute and produce additional results.
A listing shows that now there are two nextBound(100) facts, since we've asserted one in each of the two runs of nice(_), and no nextBound(10000) since it was retracted in the first run of nice(_):
| ?- listing.

% file: user

nice(_) :-
        asserta(nextBound(100)),
        retract(nextBound(10000)),
        nextBound(100).

% file: user_input

nextBound(100).
nextBound(100).

(1 ms) yes
| ?-

The logical update view, as stated in the SWI documentation, says, Starting with SWI-Prolog 3.3.0 we adhere to the logical update view, where backtrackable predicates that enter the definition of a predicate will not see any changes (either caused by assert/1 or retract/1) to the predicate.
In other words, the logical update view prevents the predicate from dynamically changing itself while it's executing. That's not the scenario here.
In fact, it's critical in Prolog that, during the execution of a predicate, if you assert a fact at one point in the predicate, that result must be visible in it immediately, or the predicate may not be able to function properly. There are many many common library predicates that rely on this behavior.

A: To start from a historical view, the logical update view has been first implemented in Quintus 2.0 (whose current successor is SICStus) and described in the literature in 1987. It has been adopted in ISO Prolog ISO/IEC 13211-1:1995. The principal idea is that any goal of a dynamic predicate will take exactly those clauses into account that are present at the point in time when the goal is executed. Any further changes — be they additions or deletions — are not taken into account for the execution of that very goal.
Prior to the logical update view, there have been various more or less consistent implementations, most were incompatible with various optimizations for Prolog systems. Note that the difference only shows if you have goals  that may have more than one answer. Either as a simple goal, or when using retract and you are using retract/1 or assertz/1. The difference does not show when using asserta/1 only. So your example cannot clarify the differences.
Consider a dynamic predicate p/1. Since the following interaction is using the toplevel only, I will make p/1 known to the system by asserting a fact and immediately retracting all facts of p/1.  Also, I will remove all facts with retractall(p(_)) before starting the next query.
?- asserta(p(1)).
   true.  % now p/1 is known to the system.
?- retractall(p(_)), assertz(p(1)), p(X), assertz(p(2)).
   X = 1.  % only one answer!
?- retractall(p(_)), assertz(p(1)), p(X), assertz(p(2)), p(Y).
   X = 1, Y = X
;  X = 1, Y = 2.

So the first goal p(X) sees only p(1), whereas the second goal p(Y) sees both. This applies for any active goal:
?- retractall(p(_)), assertz(p(1)), assertz(p(2)), p(X), assertz(p(3)), p(Y).
   X = 1, Y = X
;  X = 1, Y = 2
;  X = 1, Y = 3
;  X = 2, Y = 1
;  X = 2, Y = X
;  X = 2, Y = 3
;  X = 2, Y = 3
;  false.

Again, note that X is only 1 or 2 but not 3.
Alternatively, you can imagine that each goal p(X) is replaced by:
... findall(Xi, p(Xi), Xis), member(X, Xis) ...

This shows you a bit the idea behind: Conceptually, all answers are stored temporally, and only then each answer is shown.
Er, above is not quite true, for only the clauses of p/1 are handled this way. That is, as long as you are storing only facts, above explanation is perfect, but should you also store rules, you would need a more complex explanation, roughly:
 ... findall(Xi-Bi, clause(p(Xi),Bi), XiBis), member(X-B,XiBis), B ...

And, again, this is not the plain truth, for some more exotic issues like cuts might intervene. I will leave it that way for the moment1.
Similarly, retract/1 will also see and delete the clauses it sees at the point in time of executing it. For most situations this is quite intuitive and agrees with our expectations. Nevertheless, there are quite absurd situations as the following:
?- retractall(p(_)),
   assertz(p(1)), assertz(p(2)),
   retract(p(X)), ( X = 1, retract(p(Y)) ; X = 2, Y = none ).
   X = 1, Y = 2
;  X = 2, Y = none.

Here, the fact p(2) was deleted twice, although the data base contained only a single fact p(2).

Footnotes
1 Actually, replace
... p(X) ...

by
... findall(Xi-Bi, clause(p(Xi),Bi), XiBis), answs_goal_x(XiBis,X, G), G ...

with
answs_goal_x([], _, true).
answs_goal_x([Xi-Bi|XiBis], X, ( X = Xi, Bi ; G) ) :-
   answs_goal_x(XiBis, X, G).


text:
Q: Find the row and append to the bottom of the file I have a big file with some record which will be having different values than others.
Actual data file:
000000106500000000000129201300000U1E4600000060000+00000020400+00000002532+000000
0000001065000000000001182013000010144700002090000+00000335156+00000006776+000000
0000001065000000000003012014999999999924835390500+07164327872+00447479302+000000
0000001065000000000001102013000004QE8200000150000+00000056450+000000021

$ grep -n "9999999999" BADINS0000001065_000000000020140301.dat

I wanted to append this record into bottom of the file, simply if I have ~100 records in file if my record position is somewhere in the file, I have to find, remove from that location (completely) and need to be appended to end of the file (Bottom of the file).
There are many files in directory I want to make it automate this process for every run. File name is BADINS0000001065_0000000000*  always same.
Would you please help me to achieve this?

A: With awk you can do:
awk '
  /PATTERN/ { save = $0 ; next }
  { print }
  END { print save }
' infile > outfile

where you have to replace PATTERN by the actual pattern and infile is your data file; rename those appropriately.
The code works as follows:
/PATTERN/ { save = $0 ; next } - if the pattern is found save this line for later use and skip printing (so it's removed from this place)
{ print } - prints those lines in the file that have not been skipped by the previous command
END { print save } - finally, when all lines are processed, append the saved line, the one where the pattern matched

If you want to overwrite the  original file by the new file add a mv command after the awk script:
mv outfile infile

again with appropriately chosen filenames.

A: Other sed solution
sed -i '
        /9999999999/{h;d};           # move match string in hold space
        $G;                          # append string from hold space to end
        s/\n$//                      # avoid empty line if pattern have not met
       ' BADINS0000001065_0000000000*

A: The question is not clear on whether or not the 9999999999 is always present, or whether there can be more than one such instance in the input file. So here is a sed version which caters for all of these situations.
See man sed (option -i) for in-place update of the input file.
sed -n '/9999999999/{H;b n}; p; :n; ${g;s/\n//p}' file


text:
Q: How to use Storyboard after selecting SwiftUI during project creation? I created a project to try out SwiftUI and have been working on the same for a few days. I don't feel very comfortable with SwiftUI as of now and wish to use Storyboard instead in the project.
Trying out for some time but it is always giving me black screen on application launch.
Added Main Storyboard and set the same in settings.
What am I doing wrong?

A:
We need to manually set the Storyboard name in Project Info Scene Configuration.


text:
Q: Background effect with CSS only Anyhow know how I can go about creating a background animation like this with CSS?

A: You can create two absolute html elements and align them left and right accordingly. Then you can apply CSS radial gradient on these elements for example:   background: radial-gradient(45% 45% at 50% 50%, rgba(77, 230, 219, 0.2) 0%, rgba(77, 230, 219, 0) 100%); Otherwise, you can use pseudo-elements (:after, :before) instead of HTML tags.
Here is a quick sketch of what you can do:

.hero {
  height: 100vh;
  width: 100vw;
  background-color: #000;
  position: relative;
}
.hero:after,
.hero:before {
  content: '';
  background: radial-gradient(45% 45% at 50% 50%, rgba(77, 230, 219, 0.2) 0%, rgba(77, 230, 219, 0) 100%);
  display: block;
  position: absolute;
}
.hero:before {
  left: -100px;
  bottom: 0;
  width: 300px;
  height: 300px;
}
.hero:after{
  right: -100px;
  top: 0;
  width: 300px;
  height: 300px;
}

To make life easier, you can use CSS Gradient Generators, such as: https://cssgradient.io/


text:
Q: How to add Manager attribute on active directory by PrincipalContext using ASP.net,C# I am creating user by PrincipalContext on active directory. I want to add some extra attributes like Location, Initials,EmployeeId and Manager.
I can able to add Location, Initials and EmployeeId successfully by using UserPrincipalEx class. but i am not able assign value for Manager attribute.
When I am trying to assign some values on Manager attribute, it will show an error message as A constraint violation occurred."
Here My Code is:
 PrincipalContext ouContext = new PrincipalContext(ContextType.Domain, AD.ServerDomain, container, AD.LDAPUser, AD.LDAPPasswoprd);
 UserPrincipalEx user = new UserPrincipalEx(ouContext);
 user.GivenName = txtGivenName.Text;
 user.Surname = txtSurName.Text;
 user.DisplayName = Convert.ToString(txtDisplayName.Text);
 user.Manager = txtSupervisor.Text; // What should I assign in this field
 user.SetPassword("welcome1*");
 user.Enabled = true;
 user.ExpirePasswordNow();
 user.Save();    // Here I am getting the error

My extension class:
 [DirectoryObjectClass("user")]

 [DirectoryRdnPrefix("CN")]

  public class UserPrincipalEx : UserPrincipal

 {
public UserPrincipalEx(PrincipalContext context) : base(context) { }
public UserPrincipalEx(PrincipalContext context, string samAccountName, string password, bool enabled) : base(context, samAccountName, password, enabled) { }

public static new UserPrincipalEx FindByIdentity(PrincipalContext context,
                                               string identityValue)
{
    return (UserPrincipalEx)FindByIdentityWithType(context,
                                                 typeof(UserPrincipalEx),
                                                 identityValue);
}
public static new UserPrincipalEx FindByIdentity(PrincipalContext context,
                                               IdentityType identityType,
                                               string identityValue)
{
    return (UserPrincipalEx)FindByIdentityWithType(context,
                                                 typeof(UserPrincipalEx),
                                                 identityType,
                                                 identityValue);
}
   [DirectoryProperty("distinguishedName")]
public string DistinguishedName
{

    get
    {
        if (ExtensionGet("distinguishedName").Length != 1)
            return null;

        return (string)ExtensionGet("distinguishedName")[0];

    }
    set
    {
        ExtensionSet("distinguishedName", value);
    }
}

[DirectoryProperty("manager")]
public string Manager
{

    get
    {
        if (ExtensionGet("manager").Length != 1)
            return null;

        return (string)ExtensionGet("manager")[0];

    }
    set
    {
        ExtensionSet("manager", value);
    }
}

Please help me to resolve this problem and How to assign values on Manager field?

A: The manager attribute is not free text, it is a link to another Active Directory user. In this field you should specify the Distinguished Name of the manager's user account.
For Example:
PrincipalContext ouContext = new PrincipalContext(ContextType.Domain, AD.ServerDomain, container, AD.LDAPUser, AD.LDAPPasswoprd);
UserPrincipalEx user = new UserPrincipalEx(ouContext);
user.Manager = "CN=Managing Person,OU=Users,OU=Organisation,DC=domain,DC=local";
user.Save();


text:
Q: Why is break statement not working in this situation (python)? I have two lists:
list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]

and I want to add List2 to List1 until we find the first sum that is larger than 10, print out the summation, and stops.
My code is:
for val1 in list1:
   for val2 in list2:
      if val1+val2 > 10 :
        print (val1, val2, val1 + val2)
        break
      else:
        continue

But the result is:
0 11 11
1 10 11
2 9 11
3 8 11
4 7 11
5 6 11

How to make the loop stops at the first sum?
many thanks.
Note: I want to maintain the for...if loop structure.

A: Your 'break' statement only breaks out of the first (EDIT: innermost) loop. Put it into a function and return a value like so:
def foo(list1, list2):
    for val1 in list1:
        for val2 in list2:
            if val1+val2 > 10 :
                print (val1, val2, val1 + val2)
                return (val1 + val2) # or whatever you are interested in
            else:
                continue

A: break keyword is used to break out of only one loop to break out of multiple loop use _break boolean variable initially which is False
list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]

_break = False

for val1 in list1:
   for val2 in list2:
      if val1+val2 > 10 :
        print (val1, val2, val1 + val2)
        _break = True
        if _break:
         break
   if _break:
       break

Output:
0 11 11

A: Just maintain a flag variable to break out of the outer loop.
list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]
flag=0
for val1 in list1:
    for val2 in list2:
        if val1+val2 > 10 :
            print (val1, val2, val1 + val2)
            flag=1
            break
        else:
            continue
    if(flag):
        break

If you don't have anything to execute after this, you can use exit() method to terminate the code.
list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]
for val1 in list1:
    for val2 in list2:
        if val1+val2 > 10 :
            print (val1, val2, val1 + val2)
            exit()
        else:
            continue

A: It's just breaking the inner loop.
If you want break both for loop then, You can use flag.
list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]
flag = 0
for val1 in list1:
    for val2 in list2:
        if val1+val2 > 10 :
            print(val1, val2, val1 + val2)
            flag = 1
            break
        else:
            continue
     if flag:
         break


text:
Q: Unable to create ButtonField event handler nested in gridview The problem: I got a gridview which is populated with product data stemming from a database. Within that gridview is nested a "ButtonField" (in the last column) to be able to add the entire row content as an object to a List if the user clicks on the ButtonField (Add to cart). In "Design View" when using double-click on that button I always end up in...
protected void gview_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Response.Write("This WORKS!");
        }

...instead of that the correct event handler for the button is generated (which I assume would be looking somewhat like this).
protected void gview_RowCommand(Object sender, GridViewCommandEventArgs e)
        {

            List<GridViewRow> gvrowobjlist = new List<GridViewRow>();

            if (e.CommandName == "Add to cart")
            {
                GridViewRow gvrow = gview.SelectedRow;
                gvrowobjlist.Add(gvrow);

                //Response.Write("This WORKS as well!!!!!!");
            }

        }

Thus the issue here seems to be that it isn't possible to actually access an element (BoundField) in an element (GridView) so the above code is created. Doing so manually in the code behind results in a non-working event handler (tried and failed).
The question: What am i doing wrong and how can the event handler be created correctly so it's possible to add objects to the list? Could the problem be related to the combination of BoundFields with a ButtonField? PS. I have looked for a possible duplicate here but there was nothing that fit the issue at hand.
<asp:GridView ID="gview" runat="server" CellPadding="15" ForeColor="#333333" GridLines="None" AutoGenerateColumns="false" HorizontalAlign="Center" OnSelectedIndexChanged="gvVbResult_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
 <asp:BoundField DataField="prodId" HeaderText="Product ID" >
                    <ItemStyle HorizontalAlign="Center" Width="160px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="prodName" HeaderText="Product Name" >
                    <ItemStyle HorizontalAlign="Left" Width="150px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="packNo" HeaderText="Package amount" >
                    <ItemStyle HorizontalAlign="Center" Width="100px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="bxCont" HeaderText="Box Content" >
                    <ItemStyle HorizontalAlign="Center" Width="100px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="price" HeaderText="Price" ItemStyle-Width="100" >
                    <ItemStyle Width="100px"></ItemStyle>
                </asp:BoundField>
             <asp:ButtonField Text="addToCart" ButtonType="Button" CommandName="Add to cart" />
            </Columns>
        </asp:GridView>

A: Let's have a second look at the GridView declaration, removing unnecessary parts.
<asp:GridView ID="gview" runat="server"
              ...
              OnSelectedIndexChanged="gvVbResult_SelectedIndexChanged">

So there is a handler declared for the index changed event, however none is declared for row command. Existence of the handler does not mean anything, from ASP.NET standpoint this is just another method of the page class, it does connect the handler with the control's event. Even though this handler follows standard naming convention.
To resolve this, simply sing up for the row command event:
OnRowCommand="gview_RowCommand"

On a side note. You are probably misled here by the wiring mechanism of standard page events in ASP.NET. It is exposed by AutoEventWireup attribute of the Page directive, and is by default set to true for every new page. Say if you have a handler
protected void Page_Load(object source, EventArgs e)

wire-up mechanism will identify it and bind to a Load event of the page. This mechanism is specific to pages only, and does not spread on controls inside those pages.


text:
Q: Unable to display image in PHP generated emails linked from Mad File Manager I have this option whereby the admin can upload files, eg. pictures to the server using Mad File Manager. The "installation" of the File Manager works.
The problem occurs when I want to send an email using PHP, composed the email using TinyMCE, included the picture using the full URL, it shows... but then, when the email arrives at the other end, the image doesn't show.
What I found out is that, eg.
my domain: www.emailtest.com
upload folder: uploads
The url reflected from the image at the recipient's end only shows: uploads/image.jpg when it should be www.emailtest.com/uploads/image.jpg right?
The domain's name has been truncated.
Can anyone give me a lead on how to go about this? Thanks!

A: Looks like you will need to tweak the tinymce configuration settings a bit.
Have a look at the relative_urls param.


text:
Q: Rewrite function from getElementById to getElementsByClassName or getElementsByTagName I'm using this code by RobG from this answer to fit text inside an dynamic width container by id. But ideally I would like to use it on several elements at the same time. How could I rewrite this to work with getElementsByClassName or getElementsByTagName?

Some text

A: Get the elements and call the function in an iteration
function resize(el, factor) {
  // Get element width
  var width = el.offsetWidth;

  // set default for factor
  if (typeof factor == 'undefined') {
    factor = 5;
  }

  // Set fontsize to new size
  el.style.fontSize = (width / factor | 0) + 'px';
}

window.onload = function() {
  function doResize() {
      /* get a nodelist */
      var elems = document.getElementsByClassName('myClass');

      /* iterate over nodelist */
      for (var i=elems.length; i--;) {
          resize(elems[i], 6); // call function for each element
      }
  }
  window.onresize = doResize;
  doResize();
}

You're better off using querySelectorAll('.myClass') than getElementsByClassName. It's supported in IE8, where getElementsByClassName isn't.


text:
Q: How to refer to other ec2 instances? Is Elastic IP the only feasible solution? Initially my issue was "How do I RDP into an EC2 instance without having to first find its ip address". To solve that I wrote a script that executes periodically on each instance. The script reads a particular tag value and updates the corresponding entry in Route53 with the public dns name of the instance.
This way I can always rdp into web-01.ec2.mydomain.com and be connected to the right instance.
As I continued with setting up my instances, I realized to setup mongodb replication, I will need to somehow refer to three separated instances. I cannot use the internal private ip addresses as they keep changing (or are prone to change on instance stop/start & when the dhcp lease expires).
Trying to access web-01.ec2.mydomain.com from within my EC2 instance returns the internal ip address of the instance. Which seems to be standard behaviour. Thus by mentioning the route53 cnames for my three instances, I can ensure that they can always be discovered by each other. I wouldn't be paying any extra data transfer charges, as the cnames will always resolve to internal ip. I would however be paying for all those route53 queries.
I can run my script every 30 secs or even lesser to ensure that the dns entries are as uptodate as possible.
At this point, I realized that what I have in place is very much an Elastic IP alternative. Maybe not completely, but surely for all my use cases. So I am wondering, whether to use Elastic IP or not. There is no charge involved as long as my instances are running. It does seem an easier option.
What do most people do?  If someone with experience with this could reply, I would appreciate that.
Secondly, what happens in those few seconds/minutes during which the instance loses its current private ip and gets a new internal ip. Am assuming all existing connections get dropped. Does that affect the ELB health checks (A ping every 30 secs)? Am assuming if I were using an Elastic IP, the dns name would immediately resolve to the new ip, as opposed to say after my script executes. Assuming my script runs every 30 secs, will there be only 30secs of downtime, or can there possibly be more? Will an Elastic ip always perform better than my scripted solution?

A: According to the official AWS documentation a "private IP address is associated exclusively with the instance for its lifetime and is only returned to Amazon EC2 when the instance is stopped or terminated. In Amazon VPC, an instance retains its private IP addresses when the instance is stopped.". Therefore checking nevertheless every 30s if something changed seems inherently wrong. This leaves you with two obvious options:

*

*Update the DNS once at/after boot time

*Use an elastic IP and static DNS

Used elastic IPs don't cost you anything, and even parked ones cost only little. If your instances are mostly up, use an elastic IP. If they are mostly down, go the boot time update route. If your instance sits in a VPC, not even the boot time update is strictly needed (but in a VPC you probably have different needs and a more complex network setup anyways).

A: Another option that you could consider is to use a software defined datacenter solution such as Amazon VPC or Ravello Systems (disclaimer: our company).
Using such a solution will allow you to create a walled off private environment in the public cloud. Inside the environment you have full control, including your own private L2 network on which you manage IP addressing and can use e.g. statically allocated IPs. Communications with the outside (e.g. your app servers)  happens via the IPs and ports that you configure.


text:
Q: Ubuntu 18.04 intel vga hdmi not listed I have a Lenovo Y530 laptop running Ubuntu 18.04 with Intel graphics and nvidia.
When I use nvidia everything is just fine. I can use external monitor and xrandr detects it.
When I use Intel I can't use external monitor, xrandr output looks like I do not have any HDMI ports:
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 8192 x 8192
eDP-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 344mm x 194mm
   1920x1080    144.00*+  60.01    59.97    59.96    59.93
   1680x1050     84.94    74.89    69.88    59.95    59.88
   1600x1024     60.17
   1400x1050     85.00    74.76    70.00    59.98
   1600x900      59.99    59.94    59.95    59.82
   1280x1024     85.02    75.02    60.02
   1440x900      59.89
   1400x900      59.96    59.88
   1280x960      85.00    60.00
   1440x810      60.00    59.97
   1368x768      59.88    59.85
   1360x768      59.80    59.96
   1280x800      59.99    59.97    59.81    59.91
   1152x864     100.00    85.06    85.00    75.00    75.00    70.00    60.00
   1280x720      60.00    59.99    59.86    59.74
   1024x768      85.00    75.05    60.04    85.00    75.03    70.07    60.00
   1024x768i     86.96
   960x720       85.00    75.00    60.00
   928x696       75.00    60.05
   896x672       75.05    60.01
   1024x576      59.95    59.96    59.90    59.82
   960x600       59.93    60.00
   832x624       74.55
   960x540       59.96    59.99    59.63    59.82
   800x600       85.00    75.00    70.00    65.00    60.00    85.14    72.19    75.00    60.32    56.25
   840x525       85.02    74.96    69.88    60.01    59.88
   864x486       59.92    59.57
   800x512       60.17
   700x525       85.08    74.76    70.06    59.98
   800x450       59.95    59.82
   640x512       85.02    75.02    60.02
   720x450       59.89
   700x450       59.96    59.88
   640x480       85.09    60.00    85.01    72.81    75.00    59.94
   720x405       59.51    58.99
   720x400       85.04
   684x384       59.88    59.85
   680x384       59.80    59.96
   640x400       59.88    59.98    85.08
   576x432      100.11    85.15    85.09    75.00    75.00    70.00    60.06
   640x360       59.86    59.83    59.84    59.32
   640x350       85.08
   512x384       85.00    75.03    70.07    60.00
   512x384i      87.06
   512x288       60.00    59.92
   416x312       74.66
   480x270       59.63    59.82
   400x300       85.27    72.19    75.12    60.32    56.34
   432x243       59.92    59.57
   320x240       85.18    72.81    75.00    60.05
   360x202       59.51    59.13
   360x200       85.04
   320x200       85.27
   320x180       59.84    59.32
   320x175       85.27

$ lspci | grep VGA
00:02.0 VGA compatible controller: Intel Corporation Device 3e9b
01:00.0 VGA compatible controller: NVIDIA Corporation GP107M [GeForce GTX 1050 Ti Mobile] (rev a1)

Anyone else has similar problem or an insight on how to fix it??