text:
Q: How to efficiently extract data in bulk from an RDBMS for parent entities that have multiple child entities In my application I have an IncidentReport.  The IncidentReport has a few scalar fields and also several collections of other entities.  I need to make extracts available of many thousands of these IncidentReports with complete details in some format such as JSON or XML.  The amount of data is so large that I want to be able to stream the results so that I don't have to read them all into memory before sending them out via the API.
The IncidentReports have the following fields:
id
startTime
endTime
leadAgent
camerasUsed (Collection)
notes (Collection)
groupsAssigned (Collection)
widgetsUsed (Collection)

A set of fully populated IncidentReports might look like this:
IncidentReport1
    id=1
    startTime=12121212
    endTime=12121214
    leadAgent="Joe"
    camerasUsed
        Camera1
            camId=1
            camName="Camera1"
            camLocation="Office #123"
        Camera2
            camId=2
            camName="Fred"
            camLocation="Outer space"
    notes
        Note1
            operatorName="Sam"
            operatorId=1234
            noteText="I said hello to the customer"
        Note2
            operatorName="Joe"
            operatorId=322
            noteText="Good job"
    groupsAssigned
        Group1
            groupId=222
            groupName="Red Team"
        Group2
            groupId=223
            groupName="Blue Team"
        Group3
            groupId=224
            groupName="Yellow Team"
    widgetsUsed
        Widget1
            widgetId=123
            widgetName="A widget"
            widgetUse="Tightened"
        Widget2
            widgetId=124
            widgetName="Another widget"
            widgetUse="Loosened"
IncidentReport2
    id=2
    startTime=12123445
    endTime=12123999
    leadAgent="Karen"
    camerasUsed
        Camera3
            camId=345
            camName="Camera3"
            camLocation="Office #2323"
        Camera12
            camId=12
            camName="Jane's Cam"
            camLocation="Inner space"
    notes
        Note1
            operatorName="Jeff"
            operatorId=32323
            noteText="How is the case going?"
    groupsAssigned
        Group1
            groupId=223
            groupName="Red Team"
    widgetsUsed
        Widget1
            widgetId=223
            widgetName="Super widget"
            widgetUse="Unknown"

The  IncidentReport is stored in an RDMS along with its child entities in a normalized form.  So there are the following tables:
IncidentReport(id [PK], startTime, endTime, leadAgent)
IRCameras(incidentId [FK], camId, camName, camLocation)
IRNotes(incidentId [FK], operatorName, operatorId, noteText)
IRGroupsAssigned(incidentId [FK], groupId, groupName)
IRWidgetsUsed(incidentId [FK], widgetId, widgetName, widgetUse)

I have found that it is very inefficient to iterate through all of the IncidentReports and select the associated cameras, notes groups, and widgets.  This leads to the N+1 selects problem where I get an enormous number of select statements executed.  (I was using Hibernate for this.)
I don't think I can use a single select statement with a bunch of outer joins because the number of columns would be enormous to accomodate all of the fields of all of the child entities (camera, notes, groups, and widgets) and there would be a lot of redundant data returned.
The only thing I can think to do for efficiency sake is to query each table separately and stream the data in a "normalized" form so that the IncidentReports with only the scalar values would appear first, followed by all of the cameras, then all of the notes, then all of the groups, and then all of the widgets.  The caller would be required to reconstruct the fully populated IncidentReports by interleaving the various collections by the parent IncidentReport id.
Is there a way to accomplish this efficiently while still streaming the results as fully populated IncidentReports as in my first example above?

A: Have you considered outputing the query as XML? I am not sure what RDBMS you are using, but a SQL-Server example would be:
CREATE TABLE #IncidentReport(id INT, startTime DATETIME, endTime DATETIME, leadAgent VARCHAR(20))
CREATE TABLE #IRCameras(incidentId INT, camId INT, camName VARCHAR(50), camLocation VARCHAR(50))
CREATE TABLE #IRNotes(incidentId INT, operatorName VARCHAR(50), operatorId INT, noteText VARCHAR(50))
CREATE TABLE #IRGroupsAssigned(incidentId INT, groupId INT, groupName VARCHAR(50))
CREATE TABLE #IRWidgetsUsed(incidentId INT, widgetId INT, widgetName VARCHAR(50), widgetUse VARCHAR(50))

INSERT #IncidentReport VALUES (1, GETDATE()-2, GETDATE()-1, 'Joe'), (2, GETDATE(), GETDATE()+1, 'Karen')
INSERT #IRCameras VALUES (1, 1, 'Camera1', 'Office #123'), (1, 2, 'Camera2', 'Outer Space'), (2, 345, 'Camera3', 'Office #2323'), (2, 12, 'Jane''s Cam', 'Inner Space')
INSERT #IRNotes VALUES (1, 'Sam', 1234, 'I said Hello to the Customer'), (1, 'Joe', 322, 'Good Job'), (2, 'Jeff', 32323, 'How is the case going')
INSERT #IRGroupsAssigned VALUES (1, 222, 'Red Team'), (1, 223, 'Blue Team'), (1, 224, 'Yellow Team'), (2, 222, 'Red Team')
INSERT #IRWidgetsUsed VALUES (1, 123, 'A widget', 'Tightened'), (1, 122, 'Another widget', 'Loosened'), (2, 223, 'Super widget', 'Unknown')

SELECT  ID,
        StartTime,
        EndTime,
        LeadAgent,
        (   SELECT  CamID, CamName, CamLocation
            FROM    #IRCameras c
            WHERE   ir.ID = c.IncidentID
            FOR XML PATH('Cameras'), TYPE
        ),
        (   SELECT  OperatorName, OperatorID, NoteText
            FROM    #IRNotes n
            WHERE   ir.ID = n.IncidentID
            FOR XML PATH('Notes'), TYPE
        ),
        (   SELECT  GroupID, GroupName
            FROM    #IRGroupsAssigned g
            WHERE   ir.ID = g.IncidentID
            FOR XML PATH('GroupsAssigned'), TYPE
        ),
        (   SELECT  WidgetID, WidgetName, WidgetUse
            FROM    #IRWidgetsUsed w
            WHERE   ir.ID = w.IncidentID
            FOR XML PATH('WidgetsUsed'), TYPE
        )
FROM    #IncidentReport IR
FOR XML PATH ('IncidentReport'), ROOT

DROP TABLE #IncidentReport
DROP TABLE #IRCameras
DROP TABLE #IRNotes
DROP TABLE #IRGroupsAssigned
DROP TABLE #IRWidgetsUsed

Not sure if you can apply any of this logic to your situation but it has been 7 hours and nobody has posted any other ideas so thought I would throw this out there.

A: I am going to propose a possible answer that I am not sure I like.  What if I open multiple cursors on the database simultaneously.  So I would have the following cursors:
IncidentReportCursor
IRCamerasCursor
IRNotesCursor
IRGroupsAssignedCursor
IRWidgetsUsedCursor

Then I could iterate the cursors at the same time and build my result set as I go by interleaving the collections into each IncidentReport entity as in the sample code below.  Is this a crazy idea, to have multiple cursors, or is it reasonable?
Statement irStat = conn.createStatement();
Statement irCamStat = conn.createStatement();
Statement irNoteStat = conn.createStatement();
irStat.setFetchSize(100);
irCamStat.setFetchSize(100);
irNoteStat.setFetchSize(100);

ResultSet irRS = irStat.executeQuery("select * from IncidentReport order by id");
ResultSet irCamRS = irCamStat.executeQuery("select * from IRCameras order by incidentId");
ResultSet irNotesRS = irNoteStat.executeQuery("select * from IRNotes order by incidentId");

int lastCamIncidentId = -1;
int lastNotesIncidentId = -1;

while(irRS.next()) {
    IncidentReport ir = new IncidentReport();
    populateIR(irRS, ir);

    // iterate the notes results until we catch up to the current id
    while(!irCamsRS.isClosed() && lastCamIncidentId <= ir.getId()) {
       if(irCamsRS.next()) {
           IRCam irCam = new IRCam();
           populateCam(irCamsRS, itrCam);
           lastCamIncidentId = irCam.getIncidentReportId();
           if(lastCamIncidentId == ir.getId()) {
              ir.addCam(irCam);
           }
        }
    }

    // iterate the notes results until we catch up to the current id
    while(!irNotesRS.isClosed() && lastNotesIncidentId <= ir.getId()) {
       if(irNotesRS.next()) {
           IRNote irNote = new IRNote();
           populateNote(irNotesRS, itrNote);
           lastNotesIncidentId = irNote.getIncidentReportId();
           if(lastNotesIncidentId == ir.getId()) {
              ir.addNote(irNote);
           }
        }
    }

    serializeIncidentReport(ir);
}


text:
Q: MMX Instructions and the x87 FPU Tag Word section .data
    qVar1: dq 1

section .bss
    var28: resb  28

section .text
    _main:

        ; Use an MMX instruction

            movq mm0, [qVar1] ; Move quadword from r/m64 to mm.

        ; Read Tag Word

            fstenv [var28]
            mov    ax, [var28 + 8] ; move the Tag Word to ax

At this moment ax is 0101 0101 0101 0110
But from Intel manual, section 9.5.1 MMX Instructions and the x87 FPU Tag Word, I quote:

After each MMX instruction, the entire x87 FPU tag word is set to valid (00B).

So why ax is not all zeros?

A: The section you quoted goes on saying:

Chapter 12, "Intel® MMX™ Technology System Programming," in the Intel® 64 and IA-32 Architectures Software
  Developer's Manual, Volume 3A, provides additional information about the effects of x87 FPU and MMX instructions on the x87 FPU tag word.

In fact section 12.2 of the third manual clarifies:

When an MMX instruction writes a value into an MMX register, at the same time, bits 64 through 79 of the corresponding floating-point register are set to all 1s.

The instruction movq mm0, [qVar1] then set the register R0 to 0xffff_00000000_00000000 that is an invalid double extended precision floating point value starting from the 80387 (previously was a positive infinity).
This will be important later.
The fstenv instruction doesn't save the actual tag word, instead it interprets the registers and the actual tag word to compute the tag word that will be stored in memory.
The tag word register is then reset to empty for all registers.
The effect of fstenv on the x87 FPU tag word is:

Tags and register values are read and
  interpreted; then all tags are set to 11B.

and the image of the x87 FPU tag word stored in memory is:

Tags are set according to the actual
  values in the floating-point registers;
  that is, empty registers are marked 11B
  and valid registers are marked 00B
  (nonzero), 01B (zero), or 10B (special).

If you used emms before any XMM code the tags will all be 11b (Empty).
As soon as movq mm0, [qVar1] is executed all tags are set to 00b (Valid).
When fstenv is executed, the registers are tagged as not empty and their content is analyzed: all the registers R1-R7 appears to be zero while R0, as previously seen, contains a special value and its tag in the image stored in memory is thus 10b (special).
The entry for fstenv in the second manual is admittedly deceiving with its pseudo-code written down as

Operation
  DEST[FPUControlWord] ← FPUControlWord;
  DEST[FPUStatusWord] ← FPUStatusWord;
  DEST[FPUTagWord] ← FPUTagWord;
  DEST[FPUDataPointer] ← FPUDataPointer;
  DEST[FPUInstructionPointer] ← FPUInstructionPointer;
  DEST[FPULastInstructionOpcode] ← FPULastInstructionOpcode;

which is simply not true.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implement deep linking in my Android App i want to create a deep link when user press a share button i share a link like this--(example url) https://www.myapp.com/Home_page
(I had purchased a domain and my app is also available on play store)
and want  when user click on this link they should be redirected to the Home_page activity of my app but as i click page not found is displayed.
my code for manifest is:-
  <activity
        android:name="com.rakuso.earningadds.Activities.Home_page"
        android:configChanges="orientation|screenSize|keyboardHidden">
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="http://"
            android:host="www.myapp.com"
            android:pathPrefix="/Home_page"></data>

    </intent-filter>
 </activity>

now i cant understand what should i do

A: Use this as IntentFilter.
<intent-filter android:autoVerify="true">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="http"
                android:host="www.myapp.com"
                android:pathPrefix="/Home_page"></data>

            <data android:scheme="https"
                android:host="www.myapp.com"
                android:pathPrefix="/Home_page"></data>
        </intent-filter>

Also read AutoVerify property if you are not using it intentionally.
To handle deep link in Activity
  @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Intent intent = getIntent();
    String action = intent.getAction();
    Uri data = intent.getData();
}

Or if your Activity is android:launchMode="singleTask" then you have also check in onNewIntent()
 @Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String action = intent.getAction();
    Uri data = intent.getData();
}

Read Deep linking.


text:
Q: Inconsistent Local Transitivity Output in igraph I need to determine the transitivity for each node in a network, but am getting inconsistent results.
set.seed(123)
a <- rbinom(144, 1, .5)
b <- graph.adjacency(matrix(a, nrow = 12, ncol = 12), mode = "undirected")

transitivity(b, type = "local")

This provides the output:
 [1] 0.6888889 0.4909091 0.4444444 0.9333333 0.4909091 0.7500000 0.7333333 0.4666667 0.7333333 0.4222222 0.5000000
[12] 0.6944444

But when I try to specify a single node, some values in the output do not match:
transitivity(b, vids = 2, type = "local")

[1] 0.75

In fact, when I try to calculate the local transitivity for all vertices, many are different than if I leave the vids argument out. In some instances when I've tried this, all have been different.
transitivity(b, vids = V(b), type = "local")

  [1] 0.6888889 0.7500000 0.7142857 0.9333333 0.7500000 0.7500000 0.7333333 0.7500000 0.7333333 0.6785714 0.8571429
[12] 0.6944444

If I set vids as NULL it matches the first output, without the vids argument included at all.
The results are slightly different, but still don't match if I create a directed network.
Any thoughts on what might be causing this or which set of results should I use?
Thank you for your help.

A: You should be aware of that your graph b is NOT a simple graph, since it contains self loops

When running transitivity over such kind of graph, you will see a warning/error message

Transitivity works on simple graphs only. The result might be incorrect. igraph 1.3.0 and later will treat this as an error.

Thus, if you would like to use transitivity in a correct manner, you should exclude self loops first, e.g.,
b <- simplify(graph.adjacency(matrix(a, nrow = 12, ncol = 12), mode = "undirected"))

and then you will see
> transitivity(b, type = "local")
 [1] 0.6888889 0.7500000 0.7142857 0.9333333 0.7500000 0.7500000 0.7333333
 [8] 0.7500000 0.7333333 0.6785714 0.8571429 0.6944444

> transitivity(b, vids = V(b), type = "local")
 [1] 0.6888889 0.7500000 0.7142857 0.9333333 0.7500000 0.7500000 0.7333333
 [8] 0.7500000 0.7333333 0.6785714 0.8571429 0.6944444

A: As Thomas said, the result you get from transitivity(b, type = "local") is incorrect because b is not simple, and local transitivity calculations are not supported for non-simple graphs in R/igraph 1.2.x. If you use the latest version, there will be a clear warning:
> transitivity(b, type = "local")
Transitivity works on simple graphs only. The result might be incorrect. igraph 1.3.0 and later will treat this as an error.
 [1] 0.6888889 0.4909091 0.4444444 0.9333333 0.4909091 0.7500000 0.7333333 0.4666667
 [9] 0.7333333 0.4222222 0.5000000 0.6944444

If you don't see this warning, then please updgrade to igraph 1.2.11.
How come that transitivity(b, type='local") and transitivity(b, vids=V(b), type='local") give different results? This is because internally different code paths are used when calculating the result for all vertices vs a specific subset of vertices, in an attempt to improve performance.
The warning message says that "igraph 1.3.0 and later will treat this as an error." but in fact a tremendous amount of improvements have gone into version 1.3 since then and support for multigraphs has already been added (more precisely, this has been added to C/igraph 0.9, which R/igraph 1.3 will be based on).
I encourage you to try the development version of R/igraph, which will become version 1.3.0. Installation instructions are here; note that you need to have the R development tools installed (on Windows/Mac), as the package compiles from source. This version has a large number of fixes compared to the 1.2.x series, and at this point, should be considered more reliable than the "stable" 1.2.11.


text:
Q: sending message to printk buffer from user space -- not working Actually i want my driver messages to reach my terminal for debugging purpose. So i just try to check by following below link.
I refred following link :--
http://elinux.org/Debugging_by_printing
I am using a ubuntu in side vmplayer virtual machine. Ubuntu is running in terminal mode inside virtual machine.
I am trying to send some message to kernel printk buffer, buts echo command fails.
klog demon is also running i confirmed with following command .
ps aux | grep klogd

Cat command on proc printk entry :---
# cat /proc/sys/kernel/printk
4 4 1 7

run echo command :---
#sudo echo "<1>Writing critical printk messages from userspace" >/dev/kmsg

But i am not able to get the message on the terminal. I am getting following error when runs above command :--
-bash: /dev/kmsg: Permission denied

Please suggest how to print on console ?
my actual requirement is to ... send messages of printk() in my driver ... directly to my console.  I  am just testing here from my console that messages of low priority reaches console or not .

A: Use:
echo "<1>Writing critical printk messages from userspace" | sudo tee /dev/kmsg

See this answer to understand why.


text:
Q: Need to retrieve hashed password without usage of LoginProperty I need to retrieve the hashed password on a linked server, since its a linked server I cant seem to just use LoginProperty in the query.  At the moment I go after the sys.syslogins but the password is stored in there as what appears to be Chinese lettering and what I need is something that is the varbinary form like:
0x0200DF5602211E3AEC954FDD54A114C59B6B07C72BAB3E6DFC7A2CE0046B0B7A6037EB9F5AE6E04005FF

What is the best way to accomplish this?  If I am missing a way to just use LoginProperty when going after a linked server that is fine as well.
If possible I would like to stick with querying the syslogins and convert what is stored there into something usable.

A: Just run a passthrough query on the linked server.  EG
select * from openquery(LinkedServer,'select loginproperty(''SomeLogin'',''PasswordHash'') hash')


text:
Q: Override datatype of inherited variable (type mixed) to specific type (String) In my code there's an inherited variable that is of mixed type. The variable can be either declared as an Array or as a String. The current implementation looks like this:
abstract class Zend_Db_Table_Abstract {
    /**
     * The primary key column or columns.
     * A compound key should be declared as an array.
     * You may declare a single-column primary key
     * as a string.
     *
     * @var mixed
     */
    protected $_primary = null;

    // ...
}

class MyClass extends Zend_Db_Table_Abstract {
    /** @var string */
    protected $_primary = 'PeriodID';

    // ...
}

If I now try to access the $_primary variable I receive something like this:
// var_dump($this->$_primary);
array(1) {
  [0]=> string(8) "PeriodID"
}

However, I would like to just have a String and not an Array with only one single element?
Can someone tell me, how I can explicitly tell that in MyClass $_primary is a String and not an Array?


text:
Q: Trying to implement RapidApi on Android Studio I am trying to implement twinword word dictionary API on Android Studio.
The error message I got is:
I/OkHttpClient: Callback failure for call to https://twinword-twinword-bundle-v1.p.rapidapi.com/...
    java.io.IOException: Unexpected code Response{protocol=http/1.1, code=403, message=Forbidden, url=https://twinword-twinword-bundle-v1.p.rapidapi.com/word_example/?entry=mask}
        at com.example.anew.SentenceFramer$1.onResponse(SentenceFramer.java:58)
        at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:177)
        at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:760)

I believe the message is forbidden because it cannot access the rapidAPI and I think the problem is I couldn't figure out what is the Project Key as I couldn't find it anywhere in RapidAPI website. Or does the problem actually lies in my codes?
RapidApiConnect connect = new RapidApiConnect("I put my project name here", "I dont know where to find project key");
String object_1;

String host = "twinword-twinword-bundle-v1.p.rapidapi.com";
String API_KEY = "this is the api key";

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

    object_1 = getIntent().getStringExtra("First Object");
    Log.d("EDMTERROR", object_1);
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url("https://twinword-twinword-bundle-v1.p.rapidapi.com/word_example/?entry=mask")
            .get()
            .addHeader("x-rapidapi-host", host)
            .addHeader("x-rapidapi-key", API_KEY)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            Log.d("EDMTERROR", "onfailure");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            Log.d("EDMTERROR", "masalah");

            try (ResponseBody responseBody = response.body()) {
                if (!response.isSuccessful()) {
                    Log.d("EDMTERROR", "unexpected code");
                    throw new IOException("Unexpected code " + response);
                }

                Headers responseHeaders = response.headers();
                Log.d("EDMTERROR", "headers");
                for (int i = 0, size = responseHeaders.size(); i < size; i++) {

                    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                }

                System.out.println(responseBody.string());
            }

This is my first time doing this, so I haven't got the slightest clue on how to fix this. The website Im trying to reach is https://rapidapi.com/twinword/api/word-dictionary?endpoint=53aa5089e4b0a798dbd1a61d.
Please help, I need this for my final year project...

A: It's looks like you haven't subscribed to the API on rapidapi.com (https://rapidapi.com/twinword/api/word-dictionary/pricing)
also, I couldn't find the endpoint you are trying to use (/word_example), looks like the right endpoint is /example.
You can always contact them at support@rapidapi.com


text:
Q: Nesting Lambda functions - Performance implications I have a top level lambda function and then there are couple of nested lambda functions inside this lambda.
Is it a good idea to nest lambdas inside other lambdas? Are there any performance implications?
For e.g.
auto Multiplier1 = []() -> int
{
    auto Multiplier2 = [](int i) -> int
    {
        auto Multiplier3 = [](int i) -> int
        {
            return i * 2;
        };
        std::cout << "Calling another lambda 2\n";
        return Multiplier3(i * 100);
    };

    int i = 10;
    std::cout << "Calling another lambda 1\n";
    int ret = Multiplier2(i);
    return ret;
};

int ret = Multiplier1();
std::cout << ret << "\n";

In the example above, I can re-factor Multiplier2 and Multiplier3 into separate functions. Is that a better approach compared to this?
I am modifying a code which is already in production and hence, I was in a dilemma whether to re-factor it into separate functions or manage using lambda functions.

A: Asking about performance implications as a result of expression of coding style is always the wrong question.
The compiler, when optimising, considers expressed intent, not the layout of your code.
This example is extreme but it's worth showing you the code produced by gcc with compiler option -O2.
Refactoring the code above to remove the noise that will be produced by the use of cout:
auto Multiplier1 = []() -> int
{
    auto Multiplier2 = [](int i) -> int
    {
        auto Multiplier3 = [](int i) -> int
        {
            return i * 2;
        };
        return Multiplier3(i * 100);
    };

    int i = 10;
    int ret = Multiplier2(i);
    return ret;
};

extern void emit(int);

int main()
{
    int ret = Multiplier1();
    emit(ret);
}

compiling with gcc -S -O2 -std=c++14 yields:
main:
        subq    $8, %rsp
        movl    $2000, %edi
        call    emit(int)
        xorl    %eax, %eax
        addq    $8, %rsp
        ret

Notice that the optimiser has seen through all the code and realised that the only course of action this code could ever take (that matters) is to call the function emit with the argument value of 2000.
The lesson is always that one should express intent elegantly (i.e. in a way that can be understood and maintained easily) and allow the compiler to do its job of emitting code that implements that intent in the least time and/or code size.


text:
Q: Simple REGEX Question in PHP I want to take data entered in this format:
John Smith
123 Fake Street
Fake City, 55555
http://website.com

and store the values in variables like so:
$name = 'John Smith';
$address = '123 Fake Street';
$city = 'Fake City';
$zip = '55555';
$website = 'http://website.com';

So first name will be whatever is entered on the first line
address is whatever is on the second line
city is whatever is entered on the third line before the comma seperator
zip is whatever is on the third line after the comma
and website is whatever is on the fifth line
I don't want the pattern rules to be stricter than that. Can someone please show how this can be done?

A: Well, the regex would probably be something like:
([^\r]+)\r([^\r]+)\r([^,]+),\s+?([^\r]+)\r(.+)

Assuming that \r is your newline separator.  Of course, it'd be even easier to use something like explode() to split things in to lines...

A: $data = explode("\n", $input);

$name    = $data[0];
$address = $data[1];
$website = $data[3];

$place   = explode(',', $data[2]);

$city    = $place[0];
$zip     = $place[1];

A: If you want something more precise, you could use this:
$matches = array();

if (preg_match('/(?P<firstName>.*?)\\r(?P<streetAddress>.*?)\\r(?P<city>.*?)\\,\\s?(?P<zipCode>.*?)\\r(?P<website>.*)\\r/s', $subject, $matches)) {
   var_dump( $matches ); // will print an array with the parts
} else {
   throw new Exception( 'unable to parse data' );
}

cheers


text:
Q: await change jQuery event that has async function I need to wait my dropdown1 change event to finish. Which my change event handler has async/await function.
$('#dropdown1').on('change', async function() {
      // await Part A;
}

How do I make
$("#dropdown1).val(1).change();
// Part B, execute something at here when `dropdown1` has totally finished.

PS: I already tried
$.when($("#dropdown1).val(1).change()).then(function() {
// Part B, execute something at here when `dropdown1` has totally finished.
}

But still won't work. the Part B always executed first before my Part A finished.


text:
Q: How can I disable Kerberos authentication for only the root of my site? I have Kerberos-based authentication and I want to disable it on only root url: http://mysite.com/. And I want it to continue to work fine on any other page like http://mysite.com/page1.
I have such things in my .htaccess:
AuthType Kerberos
AuthName "Domain login"
KrbAuthRealms DOMAIN.COM
KrbMethodK5Passwd on
Krb5KeyTab /etc/httpd/httpd.keytab
require valid-user

I want to turn it off only for root URL. As workaround it is possible to turn off using .htaccess in virtual host config. Unfortunately I don't know how to do it.
Part of my vhost.conf:
    <Directory /home/user/www/current/public/>
            Options -MultiViews +FollowSymLinks
            AllowOverride All
            Order allow,deny
            Allow from all
    </Directory>

UPD. I'm using Apache/2.2.3 (Linux/SUSE)
I tried to use such version of .htaccess:
SetEnvIf Request_URI ^/$ rootdir=1
Allow from env=rootdir
Satisfy Any
AuthType Kerberos
AuthName "Domain login"
KrbAuthRealms DOMAIN.COM
KrbMethodK5Passwd on
Krb5KeyTab /etc/httpd/httpd.keytab
require valid-user

Unfortunately such config turn Kerberos AuthType for all URLs. I tried to place first 3 lines
SetEnvIf Request_URI ^/$ rootdir=1
Allow from env=rootdir
Satisfy Any

after main block, but it didn't help me.

A: I moved mod_auth_kerb configuration to vhost.conf. And used Location directive to turn off authorisation on some URLs.
    # root_url
    <LocationMatch "(^\/$|^$)">
            Satisfy Any
    </LocationMatch>
    <Location /incidents/last>
            Satisfy Any
    </Location>

    <Directory /home/user/www/>
            Options -MultiViews +FollowSymLinks
            AllowOverride None
            Order allow,deny
            Allow from all
            AuthType Kerberos
            AuthName "Domain login"
            KrbAuthRealms DOMAIN.COM
            KrbMethodK5Passwd On
            Krb5KeyTab /etc/httpd/httpd.keytab
            require valid-user
    </Directory>

That solved my problem.

A: How you do this will depend on whether you are using Apache 2.2 or Apache 2.4.  I haven't actually tested these so it's entirely possible that it won't work at all or may need some tweaking.
For 2.2 we can use SetEnvIf to set a variable if they are requesting / and use Allow from and Satisfy any to control access.  All of your existing config should stay as it is:
SetEnvIf Request_URI ^/$ rootdir=1
Allow from env=rootdir
Satisfy Any

With 2.4 there are changes to authentication and authorisation.  We now have a set of <Require> blocks which you can wrap around any access control to fine-tune authorisation:
SetEnvIf Request_URI ^/$ rootdir=1

<RequireAny>
  AuthType Kerberos
  AuthName "Domain login"
  KrbAuthRealms DOMAIN.COM
  KrbMethodK5Passwd on
  Krb5KeyTab /etc/httpd/httpd.keytab
  Require valid-user
  Require env rootdir=1
</RequireAny>

The <RequireAny> block means that any one of the Require directives must match for authorisation to succeed.  There are also <RequireAll> and <RequireNone> blocks.

A: Try AllowOverride None
It will disable the .htacess


text:
Q: jQuery is not changing css color value...sometimes The problem I am having is that I am building a type of slideshow and after a specific behavior, the code to highlight (change the color of the slide number from green to red) the new slide doesn't work even though it works in all other circumstances.
My example is located at this link for you to look at. Let the slideshow play through the 5 slides. Everything works correctly (the numbers are highlighted when their slide is shown). When you click on a number, it still works and then after an 8 second pause will continue with the slideshow. Now, the problem happens when you click on the "fresh on the block" text and click back onto the "news and events" text. What is supposed to happen is that the slideshow should start at slide 1 (with the number one in red), but the number 1 stays green. When the slide changes, number 2 stays green. The slide changes again and 3 stays green. The slide changes again and 4 turns red. Same with slide 5.
I have tapped my knowledge and am ready to rip the remainder of my hair out. Please help!

A: Your example has some broken links, for starters, try fixing the URLs for jquery UI which you have as 10.2.24.111/js/jquery-ui-1.9.0.custom.min.js and 10.2.24.111/css/smoothness/jquery-ui-1.9.0.custom.css.
I figured out why the links aren't working for 1-3 and are for 4 and 5.
It is because your ID's are id="1", id="2", etc for each of your slides, once you load the second slide show (which has only 3 slides), now there are two slide shows on the page with the same ID's of 1,2,and 3.
So the fix is to change each link like this:
1

To have a prefix like this:
1

So you won't have duplicate ID's on the same page.


text:
Q: React render component after array finished rendering I am making an api call on componentDidMount the problem is that the api takes some seconds to responde in the meanwhile the user could choose to go to another page
doing so another request is made, if this happens the app crashes. How do fix this issue? for the fix I just need to render the pagination component only when all the array is rendered how do I do so?
import React, { Component, Fragment } from "react";
import Episode from "../components/Episode";

import "react-virtualized/styles.css"; // only needs to be imported once
import { withStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";
import ButtonBase from "@material-ui/core/ButtonBase";
import CircularProgress from "@material-ui/core/CircularProgress";
import Like from "@material-ui/icons/ThumbUp";
import IconButton from "@material-ui/core/IconButton";
import NextButton from "@material-ui/icons/NavigateNext";
import PreviousButton from "@material-ui/icons/NavigateBefore";

// This example assumes you have a way to know/load this information

const styles = theme => ({
 //styles
});

class SeriesPage extends Component {
  constructor(props) {
    super(props);

    this.state = {
      apiToken: "",
      serie: {
        image: "",
        description: "",
        title: "",
        likes: 0,
        type: "",
        apiName: ""
      },
      startEpisode: 1,
      endEpisode: 10,
      episodes: [],
      loaded: false,
      clicked: false,
      enabled: true
    };
  }

  componentDidMount() {
    this.initialize(this.state.startEpisode, this.state.endEpisode);
  }

  initialize = async (startIndex, stopIndex) => {
    await this.getTokenFromApi();
    await this.getSerieDetailsByApiName();
    await this.getEpisodeBySeriesApiNameWithRange(startIndex, stopIndex);
  };

  getTokenFromApi = async () => {
    const data = {
      name: "generateToken",
      param: {
        email: "*",
        pass: "*"
      }
    };
    return fetch("*", {
      method: "post",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(response => {
        if (!response.ok) {
          this.setState({
            episodes: "Network request failed"
          });
          throw Error("Network request failed");
        }
        return response;
      })
      .then(res => {
        return res.json();
      })
      .then(content => {
        if (content.response.status === 200) {
          this.setState({
            apiToken: content.response.result.token
          });
        }
      })
      .catch(error => {
        this.setState({
          episodes: "There was an internal error"
        });
        throw error;
      });
  };

  getSerieDetailsByApiName = async () => {
    const data = {
      name: "*",
      param: {
        serieApiName: this.props.match.params.series
      }
    };
    return fetch("*", {
      method: "post",
      headers: {
        Authorization: "Bearer " + this.state.apiToken,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(response => {
        if (!response.ok) {
          this.setState({
            episodes: "Network request failed"
          });
          throw Error("Network request failed");
        }
        return response;
      })
      .then(response => {
        return response.json(); //response.json() is resolving its promise. It waits for the body to load
      })
      .then(responseData => {
        if (responseData.response.status === 200) {
          this.setState(
            {
              serie: responseData.response.result,
              loaded: true
            },
            () => {
              console.log(this.state);
            }
          );
        }
      })
      .catch(error => {
        this.setState({
          episodes: "There was an internal error"
        });
        throw error;
      });
  };

  getEpisodeBySeriesApiNameWithRange = async (startIndex, stopIndex) => {
    const data = {
      name: "*",
      param: {
        serieApiName: this.props.match.params.series,
        startIndex: startIndex,
        stopIndex: stopIndex
      }
    };
    return fetch("*", {
      method: "post",
      headers: {
        Authorization: "Bearer " + this.state.apiToken,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(response => {
        if (!response.ok) {
          this.setState({
            episodes: "Network request failed"
          });
          throw Error("Network request failed");
        }
        return response;
      })
      .then(response => {
        return response.json(); //response.json() is resolving its promise. It waits for the body to load
      })
      .then(responseData => {
        if (responseData.response.status === 200) {
          this.setState(prevState => ({
            episodes: [...prevState.episodes, ...responseData.response.result]
          }));
        }
      })
      .catch(error => {
        this.setState({
          episodes: "There was an internal error"
        });
      });
  };

  handleLikeClick = () => {
    if (this.state.clicked) {
      this.setState(
        prevState => ({
          clicked: !prevState.clicked,
          serie: {
            ...prevState.serie,
            likes: Number(prevState.serie.likes) - 1
          }
        }),
        () => {
          const data = {
            name: "removeLikeSerie",
            param: {
              serieApiName: this.state.serie.apiName
            }
          };
          return fetch("*", {
            method: "post",
            headers: {
              Authorization: "Bearer " + this.state.apiToken,
              "Content-Type": "application/json"
            },
            body: JSON.stringify(data)
          })
            .then(response => {
              if (!response.ok) {
                this.setState({
                  episodes: "Network request failed"
                });
                throw Error("Network request failed");
              }
              return response;
            })
            .catch(error => {
              this.setState({
                episodes: "There was an internal error"
              });
            });
        }
      );
    } else {
      this.setState(
        prevState => ({
          clicked: !prevState.clicked,
          serie: {
            ...prevState.serie,
            likes: Number(prevState.serie.likes) + 1
          }
        }),
        () => {
          const data = {
            name: "likeSerie",
            param: {
              serieApiName: this.state.serie.apiName
            }
          };
          return fetch("*", {
            method: "post",
            headers: {
              Authorization: "Bearer " + this.state.apiToken,
              "Content-Type": "application/json"
            },
            body: JSON.stringify(data)
          })
            .then(response => {
              if (!response.ok) {
                this.setState({
                  episodes: "Network request failed"
                });
                throw Error("Network request failed");
              }
              return response;
            })
            .catch(error => {
              this.setState({
                episodes: "There was an internal error"
              });
            });
        }
      );
    }
  };

  previousPage = () => {
    if (this.state.startEpisode === 11) {
      this.setState(
        prevState => ({
          episodes: [],
          startEpisode: prevState.startEpisode - 10,
          endEpisode: prevState.endEpisode - 10,
          enabled: true
        }),
        () => {
          this.initialize(this.state.startEpisode, this.state.endEpisode);
        }
      );
    } else if (this.state.startEpisode > 10) {
      this.setState(
        prevState => ({
          episodes: [],
          startEpisode: prevState.startEpisode - 10,
          endEpisode: prevState.endEpisode - 10
        }),
        () => {
          this.initialize(this.state.startEpisode, this.state.endEpisode);
        }
      );
    }
  };

  nextPage = () => {
    this.setState(
      prevState => ({
        episodes: [],
        startEpisode: prevState.startEpisode + 10,
        endEpisode: prevState.endEpisode + 10,
        enabled: false
      }),
      () => {
        this.initialize(this.state.startEpisode, this.state.endEpisode);
      }
    );
  };

  renderRow = item => {
    const { classes, headerIsHidden, ...other } = this.props;
    return <Episode key={item.videoId} episode={item} {...other} />;
  };

  // Render your list
  render() {
    const { classes } = this.props;

    return (
      <Fragment>

          {this.state.loaded ? (
            <Paper className={classes.root}>
              <Grid container spacing={16}>
                <Grid item>
                  <ButtonBase className={classes.image}>

                  </ButtonBase>
                </Grid>
                <Grid item xs={12} sm container>
                  <Grid item xs container direction="column" spacing={16}>
                    <Grid item xs>
                      <Typography gutterBottom variant="subtitle1">
                        {this.state.serie.title}
                      </Typography>
                      <Typography gutterBottom>
                        {this.state.serie.description}
                      </Typography>
                      <Typography color="textSecondary">
                        <IconButton
                          className={classes.button}
                          className={this.state.clicked ? classes.liked : ""}
                          aria-label="Like this serie"
                          onClick={this.handleLikeClick}
                        >
                          <Like />
                        </IconButton>
                        {this.state.serie.likes}
                      </Typography>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </Paper>
          ) : (
            ""
          )}

            {this.state.episodes.constructor === String ? (
              this.state.episodes
            ) : (

                {this.state.episodes.map(this.renderRow)}

                  <IconButton
                    aria-label="Previous"
                    className={classes.button}
                    onClick={this.previousPage}
                    disabled={this.state.enabled}
                  >
                    <PreviousButton />
                  </IconButton>
                  <IconButton
                    aria-label="Next"
                    className={classes.button}
                    onClick={this.nextPage}
                  >
                    <NextButton />
                  </IconButton>

            )}

      </Fragment>
    );
  }
}
export default withStyles(styles, { withTheme: true })(SeriesPage);

The pagination component is the div with className={classes.pagination}
the array is stored in the state

A: Add to your state a variable called loading which is initially true:
state = {
      ...,
      loading: true
}

After the response return of getEpisodeBySeriesApiNameWithRange you can setState of loading to be false:
 getEpisodeBySeriesApiNameWithRange = async (startIndex, stopIndex) => {
    const data = {
      name: "*",
      param: {
        serieApiName: this.props.match.params.series,
        startIndex: startIndex,
        stopIndex: stopIndex
      }
    };
    return fetch("*", {
      method: "post",
      headers: {
        Authorization: "Bearer " + this.state.apiToken,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(response => {
        if (!response.ok) {
          this.setState({
            episodes: "Network request failed",
            loading: false
          });
          throw Error("Network request failed");
        }
        return response;
      })
      .then(response => {
        return response.json(); //response.json() is resolving its promise. It waits for the body to load
      })
      .then(responseData => {
        if (responseData.response.status === 200) {
          this.setState(prevState => ({
            episodes: [...prevState.episodes, ...responseData.response.result],
            loading: false
          }));
        }
      })
      .catch(error => {
        this.setState({
          episodes: "There was an internal error",
          loading: false
        });
      });
  };

When you click on nextPage or previousPage setState of loading to be true again:
 nextPage = () => {
this.setState(
     prevState => ({
        episodes: [],
        startEpisode: prevState.startEpisode + 10,
        endEpisode: prevState.endEpisode + 10,
        enabled: false,
        loading: true
      }),
      () => {
        this.initialize(this.state.startEpisode, this.state.endEpisode);
      }
    );
  };

the previousPage will be the same.
In render you will only render the component if the loading is false which mean the data is fetched:
{this.state.loading ? null :

        {this.state.episodes.constructor === String ? (
          this.state.episodes
        ) : (

            {this.state.episodes.map(this.renderRow)}

              <IconButton
                aria-label="Previous"
                className={classes.button}
                onClick={this.previousPage}
                disabled={this.state.enabled}
              >
                <PreviousButton />
              </IconButton>
              <IconButton
                aria-label="Next"
                className={classes.button}
                onClick={this.nextPage}
              >
                <NextButton />
              </IconButton>

        )}

   }


text:
Q: XXHDPI and XXXHDPI dimensions in dp for images and icons in android I have been able to get dimensions for the following :
A set of six generalized densities:

*

*ldpi (low) ~120dpi

*mdpi (medium) ~160dpi

*hdpi (high) ~240dpi

*xhdpi (extra-high) ~320dpi

*xxhdpi (extra-extra-high) ~480dpi

*xxxhdpi (extra-extra-extra-high) ~640dpi

These are the dimensions :

*

*xlarge screens are at least 960dp x 720dp

*large screens are at least 640dp x 480dp

*normal screens are at least 470dp x 320dp

*small screens are at least 426dp x 320dp

But what should be the ideal dimensions for images and icon sizes with device like XXLarge and XXXlarge screens.

A: try like this. hope it works
drawable-sw720dp-xxhdpi and values-sw720dp-xxhdpi

drawable-sw720dp-xxxhdpi and values-sw720dp-xxxhdpi

link might destroy so pasted ans
reference Android xxx-hdpi real devices
xxxhdpi was only introduced because of the way that launcher icons are scaled on the nexus 5's launcher Because the nexus 5's default launcher uses bigger icons, xxxhdpi was introduced so that icons would still look good on the nexus 5's launcher.
also check these links
Different resolution support android
Application Skeleton to support multiple screen
Is there a list of screen resolutions for all Android based phones and tablets?

A: it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.

A: You can use a vector. Instead of worry about different screen sizes you only need to create an .svg file and import it to your project using Vector Asset Studio.


text:
Q: "Restricted in" "Product has been restricted in: list of countries"
Does this mean the product is available only in the countries listed, or not available in them?
Thank you.

A: It means that in those countries (in the countries listed),
the products will be difficult to get hold of.
The sort of restrictions that are applied (or may happen) are:
shortages (the country may limit imports to encourage local production).
inaccessibility: a medical certificate may be needed, or a police licence.
cost:  the product may be heavily taxed with import duty or sales tax.
climate:  some goods do not survive extremes of heat, cold, damp.
Shortage, limited access, high cost, poor durability  can all be called restrictions.

A: Does this mean the product is available only in the countries listed, or not available in them?
A direct answer, specific to its availability is: "Yes, it's available, but not everywhere, to everyone, freely". That's what "restricted in" means.
That said, is this product available freely in all other countries? - Yes (or that's what the message implies).


text:
Q: Arbitrary Precision Numbers, Google App Engine, Python, NDB As an academic exercise, I am trying to achieve an arbitrary precision (call it AP) system in google app engine using python and the NDB storage. I know that there are AP libraries out there so we can skip that.
I am curious how one might store the numbers from an AP library in a way that they could be query-able with greater than, less than, and equal operators. Ideally, this could be done using a custom property class within the NDB model, but since the NDB model uses Python and Python does not support AP numbers natively, I am not sure this is possible. If you guys agree, then we can move on to talking about storage generally - SQL, MongoDB, NDB, etc.
As I understand them, AP systems often separate the AP number into coefficients (in an array?), an exponent, and a sign. If we stored these, is there a combination of filters on these fields that could achieve a greater than, less than, and equals operations? Is it even possible to store the coefficient if it is indeed stored as an array?
Thanks in advance!

A: Here is one possible solution. First off, I need to use the Decimal object, no AP library needed it sounds like. To store it, I could convert it to a string using one of the class's methods. For instance, get a tuple from it, and convert to a string. Then, I could store that string in a NDB TextProperty and use an additional ComputedProperty to convert that string to Decimal.
However, I am not really sure how that ComputedProperty would be stored in NDB and if it would really be AP and thus useful to query against. The docs say "The computed value is written to the Datastore so that it can be queried...". But is it stored as an actual decimal? Or an AP number?

A: You need to use a sub-classed property: https://cloud.google.com/appengine/docs/python/ndb/subclassprop
In your case, either as a string (then cast it back to a Decimal in your _from_base_type) or as two integers (an integer representing the whole number, and the dividing exponent to return the number (e.g. 0.123 as 123 and 3 as 123/10^3 == 0.123).
A ComputedProperty cannot store data types outside the normal ones.


text:
Q: Using a single store on multiple grids and dropdowns with extjs 4.1 I have a store "Contacts". In my application i'm using this in 2 grids and 1 combo box. In Each of these components have varying screen space so i need to define pageSize. What is the best practise for this scenario. Is it better do create 3 different stores. ( I'm using MVC ) . If so, are there naming conventions.
Edit
Currently i load the stores in the onLaunch method in my controller
 var partsStore = this.getPartsStore();
        partsStore.pageSize = 15;
        partsStore.load({
            scope: this
        });

and reference this store in my view
Ext.define('Mis.view.JobPartList', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.jobpartlist',
    store: 'Parts',

A: Yes, you should create multiple store instances. Not sure what you mean about naming conventions, the store name should stay the same whether you have 1 or multiple instances.
Based on the code you've posted above, it's not going to work, because by adding it to the class definition you're telling it to explicitly share the store.
Ext.define('Foo', {
    // ...
    initComponent: function(){
        this.store = new MyStoreType();
        // ...
        this.callParent();
    }
});


text:
Q: Uploading multiple image on php server from android Help for this specific server side php code I don't have any knowledge of php and I have to upload three images from android to this php page.
I have tried many methods and searched for it but no tutorial or anything didn't help me my android code is working properly. DNS also configured but images aren't shown at the server side. Please help me with java code.
PHP:
<?php
if ($_FILES["file1"]["error"] > 0)
{
    header("HTTP/1.1 400 Bad Request");
    echo "Error: " . $_FILES["file1"]["error"] . "
";
}
else if ($_FILES["file2"]["error"] > 0)
{
    header("HTTP/1.1 400 Bad Request");
    echo "Error: " . $_FILES["file1"]["error"] . "
";
}
else if ($_FILES["file3"]["error"] > 0)
{
    header("HTTP/1.1 400 Bad Request");
    echo "Error: " . $_FILES["file1"]["error"] . "
";
}
else
{
    if ($_FILES["file1"]["error"] > 0)
    {
        echo "Error: " . $_FILES["file1"]["error"] . "
";
    }
    else
    {
        echo "Upload: " . $_FILES["file1"]["name"] . "
";
        echo "Type: " . $_FILES["file1"]["type"] . "
";
        echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " Kb
";
        echo "Stored in: " . $_FILES["file1"]["tmp_name"]. "
";
    }

    //$target_path = "uploads/";
    $target_path = "elp/pendingimages/";

    $target_path = $target_path . basename( $_FILES['file1']['name']);

    if(move_uploaded_file($_FILES['file1']['tmp_name'], $target_path)) {
        echo "The file ".  basename( $_FILES['file1']['name']).
            " has been uploaded";
    }
    else{
        echo "There was an error uploading the file, please try again!";
    }

    if ($_FILES["file2"]["error"] > 0)
    {
        echo "Error: " . $_FILES["file2"]["error"] . "
";
    }
    else
    {
        echo "Upload: " . $_FILES["file2"]["name"] . "
";
        echo "Type: " . $_FILES["file2"]["type"] . "
";
        echo "Size: " . ($_FILES["file2"]["size"] / 1024) . " Kb
";
        echo "Stored in: " . $_FILES["file2"]["tmp_name"]. "
";
    }

    //$target_path = "uploads/";
    $target_path = "elp/pendingimages/";

    $target_path = $target_path . basename( $_FILES['file2']['name']);

    if(move_uploaded_file($_FILES['file2']['tmp_name'], $target_path)) {
        echo "The file ".  basename( $_FILES['file2']['name']).
        " has been uploaded";
    }
    else{
        echo "There was an error uploading the file, please try again!";
    }

    if ($_FILES["file3"]["error"] > 0)
    {
        echo "Error: " . $_FILES["file3"]["error"] . "
";
    }
    else
    {
        echo "Upload: " . $_FILES["file3"]["name"] . "
";
        echo "Type: " . $_FILES["file3"]["type"] . "
";
        echo "Size: " . ($_FILES["file3"]["size"] / 1024) . " Kb
";
        echo "Stored in: " . $_FILES["file3"]["tmp_name"]. "
";
    }

    //$target_path = "uploads/";
    $target_path = "elp/pendingimages/";

    $target_path = $target_path . basename( $_FILES['file3']['name']);

    if(move_uploaded_file($_FILES['file3']['tmp_name'], $target_path)) {
        echo "The file ".  basename( $_FILES['file3']['name']).
            " has been uploaded";
    }
    else{
        echo "There was an error uploading the file, please try again!";
    }
}

?>

Java:
public class TryprojectActivity extends Activity {
    InputStream is;
    int pic_count = 0;
    Bitmap bitmap=null;
    FileInputStream in1,in2,in3;
    BufferedInputStream buf;

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

        try {
            in1 = new FileInputStream("/sdcard/1.jpg");
        }
        catch (FileNotFoundException e2) {
        // TODO Auto-generated catch block
            e2.printStackTrace();
        }

        try {
            in2 = new FileInputStream("/sdcard/2.jpg");
        } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        in3 = new FileInputStream("/sdcard/3.jpg");
    }
    catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Bitmap bitmapOrg1 = BitmapFactory.decodeStream(in1);
    ByteArrayOutputStream bao1 = new ByteArrayOutputStream();
    bitmapOrg1.compress(Bitmap.CompressFormat.JPEG, 90, bao1);
    byte [] imagearray1 = bao1.toByteArray();
    String ba1=Base64.encode(imagearray1);

    Bitmap bitmapOrg2 = BitmapFactory.decodeStream(in2);
    ByteArrayOutputStream bao2 = new ByteArrayOutputStream();
    bitmapOrg2.compress(Bitmap.CompressFormat.JPEG, 90, bao2);
    byte [] imagearray2 = bao2.toByteArray();
    String ba2=Base64.encode(imagearray2);

    Bitmap bitmapOrg3 = BitmapFactory.decodeStream(in3);
    ByteArrayOutputStream bao3 = new ByteArrayOutputStream();
    bitmapOrg3.compress(Bitmap.CompressFormat.JPEG, 90, bao3);
    byte [] imagearray3 = bao3.toByteArray();
    String ba3=Base64.encode(imagearray3);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);

    nameValuePairs.add(new BasicNameValuePair("image1",ba1));
    nameValuePairs.add(new BasicNameValuePair("image2",ba2));
    nameValuePairs.add(new BasicNameValuePair("image3",ba3));

    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://helpdesk.cispl.com/upload_file.php");
        UrlEncodedFormEntity obj = new UrlEncodedFormEntity(nameValuePairs);
        obj.setChunked(true);
        httppost.setEntity(obj);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        //is = entity.getContent();
        httpclient.getConnectionManager().shutdown();
    }
    catch(Exception e){
        //CommonFunctions.writeLOG(ctx.getClass().toString(), e.toString());
        //CommonFunctions.showToast(ctx, "Unable to post captured image file: " +
        //e.toString());
    }
}

A: Looks like your PHP is correct.
On your device use HTTP POST request with MultipartEntity data type. Read more here
EDIT
Example from my link:
You will have to download additional libraries to get MultipartEntity running!
1) Download httpcomponents-client-4.1.zip from http://james.apache.org/download.cgi#Apache_Mime4J and add apache-mime4j-0.6.1.jar to your project.
2) Download httpcomponents-client-4.1-bin.zip from http://hc.apache.org/downloads.cgi and add httpclient-4.1.jar, httpcore-4.1.jar and httpmime-4.1.jar to your project.
3) Use the example code below.

    private DefaultHttpClient mHttpClient;

    public ServerCommunication() {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        mHttpClient = new DefaultHttpClient(params);
    }

    public void uploadUserPhoto(File image1, File image2, File image3) {

        try {

            HttpPost httppost = new HttpPost("some url");

            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntity.addPart("Title", new StringBody("Title"));
            multipartEntity.addPart("Nick", new StringBody("Nick"));
            multipartEntity.addPart("Email", new StringBody("Email"));
            multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT));
            multipartEntity.addPart("file1", new FileBody(image1));
            multipartEntity.addPart("file2", new FileBody(image2));
            multipartEntity.addPart("file3", new FileBody(image3));
            httppost.setEntity(multipartEntity);

            mHttpClient.execute(httppost, new PhotoUploadResponseHandler());

        } catch (Exception e) {
            Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
        }
    }

    private class PhotoUploadResponseHandler implements ResponseHandler {

        @Override
        public Object handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {

            HttpEntity r_entity = response.getEntity();
            String responseString = EntityUtils.toString(r_entity);
            Log.d("UPLOAD", responseString);

            return null;
        }

    }

A: First of all your code could be optimized to the following:
$files = array('file1', 'file2', 'file3');
$path = 'elp/pendingimages/';

foreach ($files as $file) {
    if ($_FILES[$file]['error'] > 0) {
        echo 'Error: '. $_FILES[$file]['error'] .'
';
    }
    else {
        echo 'Upload: '. $_FILES[$file]['name'] .'
';
        echo 'Type: '. $_FILES[$file]['type'] .'
';
        echo 'Size: '. ($_FILES[$file]['size'] / 1024) .' Kb
';
        echo 'Stored in: '. $_FILES[$file]['tmp_name'] .'
';
    }

    $basename = basename($_FILES[$file]['name']);

    if (move_uploaded_file($_FILES[$file]['tmp_name'], $path . $basename) {
        echo "The file {$basename} has been uploaded";
    }
    else {
        echo 'There was an error uploading the file, please try again!';
    }
}

If you're using different field for each file then it's fine.
Next you can see what $_FILES array store in itself when it's multiple upload:
$_FILES = array(
    ['files'] => array(
        ['name'] => array(
            [0] => 'WALL_video.jpg'
            [1] => 'WALLc.jpg'
        )
        ['type'] => array(
            [0] => 'image/jpeg'
            [1] => 'image/jpeg'
        )
        ['tmp_name'] => array(
            [0] => '/tmp/phpnbKcdM'
            [1] => '/tmp/phpnrHSN1'
        )
        ['error'] => array(
            [0] => 0
            [1] => 0
        )
        ['size'] => array(
            [0] => 885968
            [1] => 839713
        )
    )
)

The following code will work for you if you're using one field with name like files[] as array of files.
$target_path = 'elp/pendingimages/';

foreach ($_FILES['files']['name'] as $index => $name) {
    if ($_FILES['files']['error'][$index] > 0) {
        echo 'Error: ' . $_FILES['files']['error'][$index] . '
';
    }
    else {
        echo 'Upload: '. $_FILES['files']['name'][$index] .'
';
        echo 'Type: '. $_FILES['files']['type'][$index] .'
';
        echo 'Size: '. ($_FILES['files']['size'][$index] / 1024) .' Kb
';
        echo 'Stored in: '. $_FILES['files']['tmp_name'][$index] .'
';
    }

    $path = $target_path . basename($name);

    if (move_uploaded_file($_FILES['files']['tmp_name'][$index], $path) {
        echo "The file {$name} has been uploaded";
    }
    else {
        echo 'There was an error uploading the file, please try again!';
    }
}

A: Check my post on sending multiple images to server
Click here


text:
Q: mysql query referring three tables I have three tables which are destination,location and intention.
They are having the following relationship with eachother. I am trying to fetch the locations and their corresponding destinations for given intention.
But im currently failing to do this.
Any ideas?
database schema
Ex: Get the location names and their corresponding destination on 'hiking' intention
Failed query :
select destination.name,location.name from location,destination,intention where
intention.name='hiking' AND location.destination_id=destination.destination_id AND
intention.intention_id=location.intention_id

Example location data
Example destination data
Example intention data

A: The intention_id of 1 for hiking does not exist in the location table, thus no rows returned


text:
Q: How to use multiple postDelayed handlers Hi I am new to android delveloping and I am curently making a simple game that tests your reflection when a certain color changes, to test what I have learned so far but I cant solve a problem that came up.
Alright, first I will explain how the game works:
When you tap the screen there is a random delay and after that you need to tap the screen again as quick as possilbe to get the best score,  and if you tap earlier than when the delay is over the game stops and tells you to try again.
My problem is that when I tap for the second time no matter if that is after or erlier the delay it repeats a part of a code and I cant figure out why.I posted my code that is relevant to this below.Also if you need any decleration let me know!
P.S I thing that it has somenthing to do with the handlers but i'm not sure.
    final Random random = new Random();
    final int randomNumber = random.nextInt(10) + 1;

    bestScoreView.setText("best score " + bestTime + " ms");
    mainThing.setText("Tap to start");

    mainThing.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            randomTimeDelay = randomNumber * 1000;

            if (previousTapDetected){
                mainThing.setText("You taped too fast");
                mainThing.setBackgroundColor(ContextCompat
                .getColor(getApplicationContext(), R.color.red));

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mainThing.setText("Try again");
                    }
                }, 750);

            }else if (previousTapDetected = true){
                mainThing.setText("Wait for the color to change");

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        previousTapDetected=false;
                        mainThing.setText("Tap now");
                        startTime = System.currentTimeMillis();
                        mainThing.setBackgroundColor(ContextCompat
                                .getColor(getApplicationContext(), R.color.red));

                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mainThing.setText("You scored " + score + " ms");
                                mainThing.setEnabled(false);
                            }
                        }, 500);

                    }
                }, randomTimeDelay);

                endTime = System.currentTimeMillis();
                score = endTime - startTime;

                if (bestTime > score) {
                    bestScoreView.setText("Best score: " + score + " ms");
                    bestTime = score;

                } else if (bestTime  < score){
                    bestScoreView.setText("Best score " + bestTime + " ms");
                }
            }
        }

    });

A: As per the docs

When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

And, in your code, you are trying to manipulate the UI elements, so the Handler should be created on the UI Thread
    Handler handler = new Handler();

    mainThing.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            randomTimeDelay = randomNumber * 1000;

            if (previousTapDetected){
                mainThing.setText("You taped too fast");
                mainThing.setBackgroundColor(ContextCompat
                .getColor(getApplicationContext(), R.color.red));

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mainThing.setText("Try again");
                    }
                }, 750);


text:
Q: Capture Parameters option is disabled in the application settings form of New Relic I want to trace HTTP params with New Relic, in the documentation they talk about the Capture parameters? option located in the application settings form. But when I go to the page this option field is unchecked and in readonly mode.

So how can I enable this feature?

A: I'm using the newrelic.yml configuration file, that way New Relic will not permit me to change settings in the settings page, instead I have to change the capture_params to true in the newrelic.yml.


text:
Q: Is the region $\mathbb{C} \setminus \gamma $ simply connected, where $\gamma (t) = t + it^2$.
Let $ \gamma (t) = t + it^2$ be a curve in the complex plane, $0 \leq t \leq \infty$.
Is $ D = \mathbb{C} \setminus \gamma $ simply connected?

The curve separates the complex plane in two parts, one above the curve and one below. What I find difficult is the point at $t = \infty$. Does this make the curve closed? And how can one make an argument about that $D$ is simply connected (if it is)?
Thanks.

A: In complex analysis, we define a nonempty proper subset $D\subset \mathbb C\cup \{\infty\}$ as simply connected if both $D$ and $(\mathbb C\cup\{\infty\})\setminus D$ are connected.
In your case, the complement is $\gamma([0,\infty])$, which is connected because it is the continuous image of a connected space. And it is easy to see that $D$ itself is path-connected: you can find a path consisting of a horizontal and a vertical line segement from any point $x+iy$ to $-1-i\in D$, either via $x-i$ or via $-1+iy$.


text:
Q: Remove Currency Character from Currency String in C# How can I remove the currency character from a currency string e.g. 20,000.00 €?. I need only the numeric figure for further processing the data. I have tried with decimal.TryParse(temp, NumberStyles.Any.Sanitize(), CultureInfo.CurrentCulture, out result) but this gives result as false because in my case, CultureInfo.CurrentCulture is en-US whereas € is not US currency. Instead of €, if I pass $, it works fine, i.e. the value of result is true. Also, if the value of CultureInfo.CurrentCulture is de, the same 20,000.00 € value works fine.
I don't want to hardcode the culture here because in my application, I have 2 cultures, en-US and de. Can someone please suggest what I can do?


text:
Q: Bootstrap background blurry on mobile and tablet I have looked everywhere on the web (including here) for an answer to this issue. I spent 4 hours trying different found "solutions" yesterday, to no avail. I only post here when I have exhaustively researched and tried everything else, including all the answers I find on Stack Exchange.
I'm using Bootstrap Bootstrap v3.3.4
I have a website with a full page background image. When I resize the window in Firefox or another desktop browser, even all the way down to the smallest size, the background image (a brick wall) resizes and renders perfectly.
However, when I pull up the site on my cell phone (an LG) or my iPad 5, the background is HUGE and only shows a partial, VERY blurry portion of the background. (I.e., one small portion of ONE VERY BLURRY BRICK!)
Here is the code in my CSS file:
 body {
     background: url(../img/bg.jpg);
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;

}
I also tried adding this, per a "solution" found on the web. It changed nothing.
body:after{
  content:"";
  position:fixed; /* stretch a fixed position to the whole screen */
  top:0;
  height:100vh; /* fix for mobile browser address bar appearing disappearing */
  left:0;
  right:0;
  z-index:-1; /* needed to keep in the background */
  background: url(../img/bg-mobile.jpg) center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;

}
I tried creating a 768px wide image and inserting the following:
@media screen and (max-width:768px) {
body {
/* The file size of this background image is 93% smaller
 * to improve page load speed on mobile internet connections */
     /* Location of the image */
       background: url(../img/bg-mobile.jpg);

}
}
Notice the url points to a file specifically created for mobile.
Still no dice.
I am deeply frustrated and flummoxed. Please keep in mind that I am a self-taught programmer, so actual code examples/clear explanations are GREATLY appreciated.
Thank you guys from the bottom of my heart. :)

A: What I would like to recommend (because it happened to me before) is to remove the background-attachment fixed on mobile devices. It will reduce the size and will look better. Anyway, I also would like to recommend using images of at least 1680px wide. Here a good post.


text:
Q: Sending PUT request via HttpClient to Saucelabs not responding I am trying to send a PUT request to update a job on Saucelabs via their API. However, the following code hangs and I am not sure why.
using (var client = new HttpClient())
{
    var sessionId = Browser.Driver.GetSessionId();
    var uri = new Uri($"https://saucelabs.com/rest/v1/{Configuration.SauceUserName}/jobs/{sessionId}");
    var uriWithCred =
        new UriBuilder(uri)
        {
            UserName = $"{Configuration.SauceUserName}",
            Password = $"{Configuration.SauceAccessKey}"
        }.Uri;
    var payload = new StringContent($"{{\"name\":\"{TestMethodName}\"}}", Encoding.UTF8, "application/json");
    var request = new HttpRequestMessage
    {
        Method = HttpMethod.Put,
        RequestUri = uriWithCred,
        Content = payload
    };
    var response = client.SendAsync(request).Result;
}

The following cUrl request is successful (redacted credentials, of course).
curl -X PUT -s -u <username>:<access-key>
-d "{\"name\": \"test name\"}"
https://saucelabs.com/rest/v1/<username>/jobs/<job-id>

Why does this request hang and what can I do to make it successful?
For reasons unrelated to the question, I am unable to set the name of the job when setting the capabilities of the WebDriver.

A:
Why does this request hang and what can I do to make it successful?

Most probably there is a mixing of async and blocking calls like .Result on the client.SendAsync method which can cause deadlocks or as you put it, cause code to hang.
Consider making the method call async all the way using await.
public async Task CallAPIAsync() {
    using (var client = new HttpClient()) {
        var sessionId = Browser.Driver.GetSessionId();
        var uri = new Uri($"https://saucelabs.com/rest/v1/{Configuration.SauceUserName}/jobs/{sessionId}");
        var uriWithCred =
            new UriBuilder(uri) {
                UserName = $"{Configuration.SauceUserName}",
                Password = $"{Configuration.SauceAccessKey}"
            }.Uri;
        var payload = new StringContent($"{{\"name\":\"{TestMethodName}\"}}", Encoding.UTF8, "application/json");
        var request = new HttpRequestMessage {
            Method = HttpMethod.Put,
            RequestUri = uriWithCred,
            Content = payload
        };
        var response = await client.SendAsync(request);

        var content = await response.Content.ReadAsStringAsync();
    }
}


text:
Q: Pyspark (from csv file) is loading dataframe in a different format (I am new to pyspark)
I am trying to read a csv file into a pyspark dataframe as follows:
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession, SQLContext

spark = SparkSession.builder.master("local[1]").appName("SampleWork").getOrCreate()
df = spark.read.csv('train.csv',sep=",",header=True,inferSchema=True)

But I am not getting expected result dataframe here. How to read this file correctly.
I have added the first 3 rows of the sample csv file here.
csv file:
id,url_legal,license,excerpt,target,standard_error
c12129c31,,,"When the young people returned to the ballroom, it presented a decidedly changed appearance. Instead of an interior scene, it was a winter landscape.
The floor was covered with snow-white canvas, not laid on smoothly, but rumpled over bumps and hillocks, like a real snow field. The numerous palms and evergreens that had decorated the room, were powdered with flour and strewn with tufts of cotton, like snow. Also diamond dust had been lightly sprinkled on them, and glittering crystal icicles hung from the branches.
At each end of the room, on the wall, hung a beautiful bear-skin rug.
These rugs were for prizes, one for the girls and one for the boys. And this was the game.
The girls were gathered at one end of the room and the boys at the other, and one end was called the North Pole, and the other the South Pole. Each player was given a small flag which they were to plant on reaching the Pole.
This would have been an easy matter, but each traveller was obliged to wear snowshoes.",-0.340259125,0.464009046
85aa80a4c,,,"All through dinner time, Mrs. Fayre was somewhat silent, her eyes resting on Dolly with a wistful, uncertain expression. She wanted to give the child the pleasure she craved, but she had hard work to bring herself to the point of overcoming her own objections.
At last, however, when the meal was nearly over, she smiled at her little daughter, and said, ""All right, Dolly, you may go.""
""Oh, mother!"" Dolly cried, overwhelmed with sudden delight. ""Really?
Oh, I am so glad! Are you sure you're willing?""
""I've persuaded myself to be willing, against my will,"" returned Mrs. Fayre, whimsically. ""I confess I just hate to have you go, but I can't bear to deprive you of the pleasure trip. And, as you say, it would also keep Dotty at home, and so, altogether, I think I shall have to give in.""
""Oh, you angel mother! You blessed lady! How good you are!"" And Dolly flew around the table and gave her mother a hug that nearly suffocated her.",-0.315372342,0.480804970
b69ac6792,,,"As Roger had predicted, the snow departed as quickly as it came, and two days after their sleigh ride there was scarcely a vestige of white on the ground. Tennis was again possible and a great game was in progress on the court at Pine Laurel. Patty and Roger were playing against Elise and Sam Blaney, and the pairs were well matched.
But the long-contested victory finally went against Patty, and she laughingly accepted defeat.
""Only because Patty's not quite back on her game yet,"" Roger defended; ""this child has been on the sick list, you know, Sam, and she isn't up to her own mark.""
""Well, I like that!"" cried Patty; ""suppose you bear half the blame, Roger. You see, Mr. Blaney, he is so absorbed in his own Love Game, he can't play with his old-time skill.""
""All right, Patsy, let it go at that. And it's so, too. I suddenly remembered something Mona told me to tell you, and it affected my service.""",-0.580117966,0.476676226

A: You can use the custom escape character with the multiLine option.
df = spark.read.csv("test.csv", header=True, inferSchema=True, escape="\"", multiLine=True)

+---------+---------+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+--------------+
|id       |url_legal|license|excerpt                                                                                |target      |standard_error|
+---------+---------+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+--------------+
|c12129c31|null     |null   |When the young people returned to the ballroom, it presented a decidedly changed appearance. Instead of an interior scene, it was a winter landscape.
The floor was covered with snow-white canvas, not laid on smoothly, but rumpled over bumps and hillocks, like a real snow field. The numerous palms and evergreens that had decorated the room, were powdered with flour and strewn with tufts of cotton, like snow. Also diamond dust had been lightly sprinkled on them, and glittering crystal icicles hung from the branches.
At each end of the room, on the wall, hung a beautiful bear-skin rug.
These rugs were for prizes, one for the girls and one for the boys. And this was the game.
The girls were gathered at one end of the room and the boys at the other, and one end was called the North Pole, and the other the South Pole. Each player was given a small flag which they were to plant on reaching the Pole.
This would have been an easy matter, but each traveller was obliged to wear snowshoes.|-0.340259125|0.464009046   |
|85aa80a4c|null     |null   |All through dinner time, Mrs. Fayre was somewhat silent, her eyes resting on Dolly with a wistful, uncertain expression. She wanted to give the child the pleasure she craved, but she had hard work to bring herself to the point of overcoming her own objections.
At last, however, when the meal was nearly over, she smiled at her little daughter, and said, "All right, Dolly, you may go."
"Oh, mother!" Dolly cried, overwhelmed with sudden delight. "Really?
Oh, I am so glad! Are you sure you're willing?"
"I've persuaded myself to be willing, against my will," returned Mrs. Fayre, whimsically. "I confess I just hate to have you go, but I can't bear to deprive you of the pleasure trip. And, as you say, it would also keep Dotty at home, and so, altogether, I think I shall have to give in."
"Oh, you angel mother! You blessed lady! How good you are!" And Dolly flew around the table and gave her mother a hug that nearly suffocated her.                                                       |-0.315372342|0.48080497    |
|b69ac6792|null     |null   |As Roger had predicted, the snow departed as quickly as it came, and two days after their sleigh ride there was scarcely a vestige of white on the ground. Tennis was again possible and a great game was in progress on the court at Pine Laurel. Patty and Roger were playing against Elise and Sam Blaney, and the pairs were well matched.
But the long-contested victory finally went against Patty, and she laughingly accepted defeat.
"Only because Patty's not quite back on her game yet," Roger defended; "this child has been on the sick list, you know, Sam, and she isn't up to her own mark."
"Well, I like that!" cried Patty; "suppose you bear half the blame, Roger. You see, Mr. Blaney, he is so absorbed in his own Love Game, he can't play with his old-time skill."
"All right, Patsy, let it go at that. And it's so, too. I suddenly remembered something Mona told me to tell you, and it affected my service."                                                                                |-0.580117966|0.476676226   |
+---------+---------+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+--------------+


text:
Q: Sending ctrl-c to specific screen session I am designing a script to launch a process inside a named screen session.
as_user "screen -p 0 -S **$command** -X eval 'stuff \"wine LFS.exe /cfg=**$command**.cfg\"\015'"

So bash myscript.sh start test will create a screen named test and run the test.cfg with the software.
Now I want my script to access the specific screen session and do a CTRL+C to stop the running process so i can kill the screen session.
Something like this:
as_user "screen -p 0 -S **$command** **... kill the process with ctrl-c...**"
as_user "screen -p 0 -S **$command** -X eval 'stuff \"exit\"\015'"

A: I don't quite understand you but to send ctrl-c to a window in a screen session:
screen -S session_name -X at window_number stuff $'\003'
# or
screen -S session_name -X -p window_number stuff $'\003'

If you want to send something to all the windows, use # (needs to be quoted) as the window_number.
UPDATE:
Screen's stuff command also supports ^X (or ^x) to mean CTRL-X so the following command can also be used to send CTRL-C.
# Here '^C' is two chars, '^' and 'C'
screen -S session_name -X at window_number stuff '^C'


text:
Q: Scrapy FormRequest from response AtrributeError: 'str' object has no attribute 'encoding' I am trying to login to Facebook using Scrapy.
I have identified that mobile version of Facebook works without javascript, so I am using it.
The relevant code is
from loginform import fill_login_form
from scrapy.http import FormRequest

def parse(self, response):
    """Login to Facebook then pass on"""
    payload = fill_login_form(
        response.request.url,  # https://m.facebook.com
        response.body,
        self.login_user,
        self.login_pass
    )
    return FormRequest.from_response(
        response.request.url,
        formdata=payload,
        formid='login-form',
        callback=self.after_login
    )

The error I get is:
File "/XXX/scraps/scraps/spiders/fb.py", line 44, in parse
    return FormRequest.from_response(response.request.url, formdata=payload, formid='login-form', callback=self.after_login)
  File "/XXX/venv/lib/python3.6/site-packages/scrapy/http/request/form.py", line 42, in from_response
    kwargs.setdefault('encoding', response.encoding)
AttributeError: 'str' object has no attribute 'encoding'

Scrapy is on default settings.
I want my spider to login to m.facebook.com. I'm pretty sure it is just my weak google-fu, but I was not able to determine, how to move forward.

A: the from_response method requires the first argument to be a response object not the url, please check the docs, there's an example that uses the FormRequest.from_response to simulate a user login.


text:
Q: Filter SharePoint list by "current user member of group" I have a SharePoint online list, on a site were everybody in organization has read access.
The list has 3 columns: Title, Link, Site and is a table of contents to pages from different SharePoint sites, with different members. The list is populated by Flows that triggers when a page is published and it's name follows a pattern.
For example:
Article1 | Link-to-Article1 | Financial
Article2 | Link-to-Article2 | Administration
I would like to filter this list so that every user sees only the links to the sites he is member of.
Looking at the above example, if current user is member of Financial Team but not a member of Administration, he should see only Article1.
Is it possible to do this either by SharePoint view filtering or view formatting json?
Thank you!

A: You can add a fourth column (Group) with type User/Group to the list and populate it with group or groups, that should view it. After that you can use CAML Membership element for filtering.
Basically, your SPView.Query should be something like (if ShowForGroups is an internal name for the column, that contains groups):
<Where>
   <Or>
      <Eq>
         <FieldRef Name="ShowForGroups" />
         <Value Type="Integer">
            <UserID />
         </Value>
      </Eq>
      <Membership Type="CurrentUserGroups">
         <FieldRef Name="ShowForGroups" />
      </Membership>
   </Or>
</Where>

However, you won't be able to create such view, using SharePoint view creation page, you will need to use powershell for that.

A: I found the actual solution for this issue.
Using CAML query is not the solution as we want a proper view. Using CAML we are only able to get data in power shell which is of no use.
Follow these steps to achieve the goal:
1: Create a new column of Type "Person or Group" with any name say "Group Column"
2: Create a new User Group with any name say "Custom User Group"
3: When an item is created in the list, run a Power Automate flow that will loop through all the users in the user group "Custom User Group" and fill that "Group Column" with each email address.
4: Go to List Settings and Scroll down to open the Default List View. Apply [ME] filter and select "Group Column" for that filter.
You are done. Now whenever any person in that User Group will open the list. He will see all the items.
Similarly, you can create different user groups and different column in list and apply [ME] filter.


text:
Q: Conditional data show hide in Angularjs I am working on an application where I have to generate a table report, based on user filter.
And user can filter the result and submit new query using different parameter. Depending one of the checkbox and the results lists,I have to show hide a column in table.
How I can implement in an Angular way?

A: You can use ng-show with condition, like this:
<select ng-model="filter">
  <option value="blah"></option>
  <option value="foo"></option>
</select>

    1
    blah blah

    2
    foo foo

A: Showing and hiding columns seems a lot more involved than this to me. It's more than just simply applying a conditional ng-show attribute to an event handler -- at least, I have not found that idea to work as intended.
I'm currently researching how to hide a whole column of data in a database table and I came across this blog post just now.  It sounds like a workable solution and I can actually understand what the author is talking about -- which is a big deal for me as I'm only just learning my way around Angular.  Here is the link in case it helps you or someone else out on this issue.  I'll report back later whether it helped me or not.
http://entwicklertagebuch.com/blog/2013/11/datatable-with-fully-dynamic-columns-in-angularjs/
(Sample code from the link)
function createTDElement(directive) {
var table = angular.element('

');
return table.find('td');
}
app.directive('item', function($compile) {
  function createTDElement(directive) {
    var table = angular.element('

');
    return table.find('td');
  }

  function render(element, scope) {
    var column, html, i;
    for (i = 0; i < scope.columns.length; i++) {
      column = scope.columns[i];
      if (column.visible) {
        html = $compile(createTDElement(column.directive))(scope);
        element.append(html);
      }
    }

  }

  return {
    restrict: 'A',
    scope: {
      item: "=",
      columns: "="
    },
    controller: function($scope, $element) {
      $scope.$watch(function() {
        return $scope.columns;
      }, function(newvalue, oldvalue) {
        if (newvalue !== oldvalue) {
          $element.children().remove();
          render($element, $scope);
          $compile($element.contents())($scope);
        }
      }, true);
    },
    compile: function() {
      return function(scope, element) {
        render(element, scope);
      }

    }
  };

});

A: Consider adding a conditional style to a <col/> with ng-style or ng-class


text:
Q: javascript object creation for js remoting Hi I am trying to use a RemoteAction function from js remoting.The remote function accepts a custom object,so I need to pass it from javascript.For this I m creating a javascript object with all fields of custom object.
function my_object__c(){
   this.id = null;
   this.name = null
   ------------
   more fields here
   ------------
}

The values of id, name and all other fields are binded to vf page's inputFields like this :
<apex:inputfield value="{!myObj.Name}"></apex:inputfield>

is there a easier way to access these values and use them in js object my_object__c.I can only think of travesering the dom and get these based on ids.
Second,can the RemoteFunction accept multiple parameters ?

A: Mohith did a good job pointing you to the documentation for JavaScript Remoting for what is supported.
To get the values into your JavaScript object you can use jQuery to make it very easy.
Either put jQuery in a static resource or hotlink to one of the CDN hosted copies.
Here's how to do use jQuery with the static resources:
Put jQuery in your static resource, for example, in a zip called res in a subfolder called js and be sure to include it prior to using it.
Zip file with the structure /res/js/jquery-1.8.1.min.js is referenced from VF as follows:
<apex:includeScript value="{!URLFOR($Resource.res, 'js/jquery-1.8.1.min.js')}"/>

Then the JavaScript snippet:
<script type="text/javascript">
    var j$ = jQuery.noConflict();

    // Whatever function you end up calling to get the data from the page
    function doItToIt() {
        // Get the value of the name field
        yourObj.Name = j$('.name').val();
    }
</script>

<!-- somewhere on your page is your input with styleClass from above jQuery selector -->
<apex:inputfield value="{!myObj.Name}" styleClass="name" />

Here you can use styleClass instead of ID since the ID that you specify is not the ID that will get generated by Visualforce and then use the jQuery val function.  Just make sure that your styleClass is unique so that the jQuery selector works the way that you want it to.

A: Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes and interfaces as arguments. Generic sObjects must have an ID or sobjectType value to identify actual type. Interface parameters must have an apexType to identify actual type.
Your method can return Apex primitives, sObjects, collections, user-defined Apex classes and enums, SaveResult, UpsertResult, DeleteResult, SelectOption, or PageReference.
So answering your question
1)Yes remoting can take generic Sobjects with ID or sobjectType Value
2)Yes you can have multiple parameters without overloading
3)Yes i guess acessing dom will be the best practice to get those field values
Document link
http://www.salesforce.com/us/developer/docs/pages/Content/pages_js_remoting.htm


text:
Q: (change) Working only after pressing enter in angular 2 I want to show a list which shows the rows matching the user entered value in the text box.
List must keep changing dynamically as user keeps inputting values.
that's why I tried using (change) event listener on the input text box.
but list changes only after I press 'Enter' button.
Here's the code.

        <input type = "text" [(ngModel)] = "writerSuggest" (change) = "getWriterList($event)" />

        {{writers.name}}

        No writers with given name

A: You can use ngmodelChange event.
<input type = "text" [ngModel] = "writerSuggest" (ngModelChange) = "getWriterList($event)" />

A: Use ng modelChange which detects change of bound variables's value.
like
<input type = "text" [(ngModel)] = "writerSuggest" (ngModelChange) = "getWriterList($event)" />

A: You can try ngModelChange
example


text:
Q: Magento and Martial Arts SE have the same favicon The favicon of Magento is a blue speech bubble with MA, and the favicon of Martial Arts also is a blue speech bubble with MA.
Favicon of Magento:
Favicon of Martial Arts:
Note: I'm talking about the 16x16 favicons, not about the icons on the site list, which are different.
Another note: perhaps you are not able to reproduce it (Shadow Wizard could not), but then you'll still see it on the site list (screenshot provided by Shadow):

Can they please have different icons?

A: I assume this is status-completed for two reasons.
One, Magneto graduated and thus has its own favicon now:

and other sites that may have this issue like Poker and Politics (both are single words that start with PO) have different favicons:

or take some weird cases like Bioinformatics, Bitcoin, and Board & Card Games. Bioinformatics has BI. Bitcoin instead has BC. You would think Board & Card Games might also have BC as other sites like Artificial Intelligence use the first letters of their two words. Nah, Board & Card Games go with BG, G coming from Games: