text:
Q: RuntimeException: Unable to resume activity. Intent getting Extras I really don't know what's wrong:
I've made function, that moves user to AddNewQuestionClass
//function is in Activity Class
public void wroc(String sciezka){
    Intent intent = new Intent(this, AddNewQuestion.class);
    intent.putExtra("sciezka1", sciezka);
    startActivity(intent);
}

I'm also sending "sciezka" variable. Now, I'm getting this variable in AddNewQuesionClass:
@Override
protected void onResume() {
    super.onResume();
    Bundle bundle = getIntent().getExtras();
    sciezka_do_pliku_z_obrazem = bundle.getString("sciezka1");
    Uri myUri = Uri.parse(sciezka_do_pliku_z_obrazem);
    try {

        Bitmap jakisobraz = MediaStore.Images.Media.getBitmap(this.getContentResolver(), myUri);
        obrazekdoedycji.setImageBitmap(jakisobraz);
    }
    catch(Exception e){
        Log.e("EO", " " + e);
    }
}

Unfortunately, something don't works:
12-10 20:21:12.213: E/AndroidRuntime(9173): FATAL EXCEPTION: main
12-10 20:21:12.213: E/AndroidRuntime(9173): java.lang.RuntimeException: Unable to resume activity {app.piotrek.learning/app.piotrek.learning.AddNewQuestion}: java.lang.NullPointerException
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2701)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2729)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2215)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.app.ActivityThread.access$600(ActivityThread.java:142)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.os.Looper.loop(Looper.java:137)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.app.ActivityThread.main(ActivityThread.java:4931)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at java.lang.reflect.Method.invokeNative(Native Method)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at java.lang.reflect.Method.invoke(Method.java:511)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at dalvik.system.NativeStart.main(Native Method)
12-10 20:21:12.213: E/AndroidRuntime(9173): Caused by: java.lang.NullPointerException
12-10 20:21:12.213: E/AndroidRuntime(9173):     at app.piotrek.learning.AddNewQuestion.onResume(AddNewQuestion.java:185)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1184)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.app.Activity.performResume(Activity.java:5082)
12-10 20:21:12.213: E/AndroidRuntime(9173):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2691)
12-10 20:21:12.213: E/AndroidRuntime(9173):     ... 12 more

This is #185 line (there is an error):
 sciezka_do_pliku_z_obrazem = bundle.getString("sciezka1");

What's wrong?

A: Try this
getIntent().getStringExtra("sciezka1");

rather than bundle...
I  hope it will solve ur problem

A: It seems like your variable sciezka is null, so later in onResume() when bundle.getString('sciezka') the value of sciezka is empty thus throwing a null pointer exception.
Make sure sciezka is not empty, you can do a Log.i after
intent.putExtra("sciezka1", sciezka); to dump variable sciezka to confirm this.

A: It looks like the bundle you are trying to call method getString() on is null. That's the reason you're getting a Null Pointer Exception.


text:
Q: No module named 'fbprophet' in jupyter notebook inside visual studio code though it is listed in pip3 list screenshot

ModuleNotFoundError                       Traceback (most recent call last)
in
----> 1 from fbprophet import Prophet
ModuleNotFoundError: No module named 'fbprophet'

redpajama_set_name: RedPajamaStackExchange


text:
Q: DjangoUnicodeDecodeError and force_unicode I've simple Django model of news entry:
class NewsEntry(models.Model):
    pub_date = models.DateTimeField('date published')
    title = models.CharField(max_length = 200)
    summary = models.TextField()
    content = models.TextField()

def __unicode__(self):
    return self.title

Adding new news (in Admin page) with english text works fine but when i try to add news with russian text there is error:

TemplateSyntaxError at /admin/news/newsentry/
Caught DjangoUnicodeDecodeError while rendering: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128). You passed in NewsEntry: [Bad Unicode data] (class 'antek.news.models.NewsEntry')
Django Version: 1.2.2
Exception Type: TemplateSyntaxError
Exception Value: Caught DjangoUnicodeDecodeError while rendering: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128). You passed in NewsEntry: [Bad Unicode data] (class 'antek.news.models.NewsEntry')
Exception Location: /usr/local/lib/python2.6/dist-packages/django/utils/encoding.py in >force_unicode, line 88
Python Version: 2.6.5

The last item in traceback list is:

/usr/local/lib/python2.6/dist-packages/django/utils/encoding.py in force_unicode
Local vars:
e: UnicodeDecodeError('ascii', '\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82 \xd1\x80\xd1\x83\xd1\x81\xd1\x81\xd0\xba\xd0\xbe\xd0\xb3\xd0\xbe', 0, 1, 'ordinal not in range(128)')

Code looks correct: self.title is unicode object. Also, djangoproject.com use similar code in their blog application.
I spend much time to solve this problem and founded strange solution:
from django.utils.encoding import force_unicode
# ...
def __unicode__(self):
    return force_unicode(self.title)

But due to self.title is unicode object, force_unicode should return it without any changes.
Why return self.title doesn't work?

A: Problem was in utf8_bin collation in MySQL server. Full information here.

A: force_unicode comes with the potential of lost data. If you know the type of data that you are getting, it is much more realistic to simply use Python's decode method to properly convert the data. This can easily be done with a 'latin1' string (for example) like so:
my_unicode_string = my_latin1_string.decode('latin1')

A: My situation was even more paculiar, I was importing data from JSON file, the in memory created instance would throw a Unicode as follows:
DjangoUnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 21: ordinal not in range(128). You passed in <Company: [Bad Unicode data]> (<class 'companies.models.Company'>)

But retrieving it from database and running the code again worked without an issue, so if you having an issue where you get a Django error that contains [Bad Unicode data] try re-retrieving the object after save as a workaround.
    ...
company.save()
company = Company.objects.get(pk=company.pk) # avoiding bizarre [Bad Unicode data] error
logger.info("Company (locality exists) '{0}' created".format(company))
...

If anyone wishes to properly explain as to why feel free - my guess is the input data is not encoded in utf-8:
...
"address_city": "Dolbeau-Mistassini",
"name": "Bleuets Mistassini Lt\u00e9e",
...


text:
Q: How to get my Go Lambda function to give me a response when calling it in a browser? I created a microservice in Go that unmarshals the data off of a request body and stores it in DynamoDB.  The REST URL runs pretty much anywhere but a browser it seems.  When I run the fetch in a browser I get a 403 with no response.  I can get a 200 response using a Node script, curl command, or even when using a tool like repl.it to test.  For some reason though, it never wants to work in a web app, or the dev console (I'm using Chrome).  I tried running the request in multiple websites including the web app I'm building to run it in and all of them gave the same 403 no response result.
In API Gateway, Authorization is set to "none", and API Key is set to "not required", so I'm having a lot of difficulty in seeing how I can get a 403 on my endpoint.  On the frontend, my fetch request looks like something below.  The curl command that worked is below as well.  I followed this post before creating this, and although it's similar, this person does actually get a response, while mine gives me no response.  It works as a script, but just doesn't work in the browser.  How does this work anywhere but inside a browser?  If I can just get some info on what's going on, that would be awesome.  If I can get some info on how this can be solved, that would be REALLY awesome.
js
fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    data: JSON.stringify({
        Email: 'example@test.com'
    }),
})
    .then(res => res.json())
    .then(json => console.log(json))
    .catch(e => console.error(e))

curl
curl -H 'application/json' -d '{ "Email": "example@test.com" }' $URL

UPDATE: I discovered what I had going wrong.  It was a CORS issue.  I was not handling the OPTIONS method that was sent as a preflight request prior to my POST request.  The OPTIONS method gets sent automatically when in the browser, but does not if you're running the code anywhere else.


text:
Q: How to draw a wall- solidbox with OpenGL-es? I want to make a wall or a solid box like this:

That you can see,I have a window on the wall. Currently, I created 4nodes and integrate them to make the window, and add them to a parent node. But I cannot change the texture, only color.
So I want to draw a wall like this, that mean how to create the list of vertices to make it.
But I dont know how to do that.
Can anyone point me a way?
Thanks so much.

A: If I understand correctly, you're trying to figure out how to make a wall with a window as one polygonal object.
Make it out of four separate pieces, like this:
  AAAAAAAAA
  BBB   CCC
  BBB   CCC
  DDDDDDDDD

Unless you leave gaps between the pieces, it will look like a wall with a window.


text:
Q: How to prevent button text movement when button is active in Firefox? Sample:
<button>Button</button>

button {
    border: medium none;
    margin-top: 17px;
    width: 224px;
    height: 40px;
    background: none repeat scroll 0% 0% #7BA6BB;
    color: #FFF;
    outline: medium none;
    cursor: pointer;
}

http://codepen.io/anon/pen/ByaLZN
Browser: Mozilla Firefox (the latest version)
When button is clicked (active), button text moves right. How To prevent it?

A: As one of solutions : add padding:0 for button:active

button {
  border: medium none;
  margin-top: 17px;
  width: 224px;
  height: 40px;
  background: none repeat scroll 0% 0% #7BA6BB;
  color: #FFF;
  outline: medium none;
  cursor: pointer;
}

button:active {
  padding: 0px;
}
<button>Button</button>

Or you can add span(or maybe another tag that you like) into your button like this here:

button {
  border: medium none;
  margin-top: 17px;
  width: 224px;
  height: 40px;
  background: none repeat scroll 0% 0% #7BA6BB;
  color: #FFF;
  outline: medium none;
  cursor: pointer;
}

button:active {
  padding: 0px;
}
<button>Button</button>

A: If text is moving right - move button left, so text will remain in his position:
http://jsfiddle.net/goc68jy4/2/
button {
  ...
  padding:0px;
}
button:active{
    margin-left:-2px;
    padding-left:4px;
}

A: Add reset css
    *{margin:0; padding:0;}

Demo


text:
Q: jQuery - Apply CSS to div1 if div2 contains a certain word of text? With jQuery how can I apply css to a div, if another div contains a certain word?
So if div1 contains the text 'TriggerWord', I want div 2 to become red. Below is my attempt.
Thanks
     $("document").ready(function () {
       if ($("#div1:contains('TriggerWord')")) {
          $('#div2').css('color','red');
       }
    });

A: Don't quote document. Other than that your attempt is correct. The :contains() selector is what you need:
$(document).ready(function() {
    if ($('#div1:contains("TriggerWord")').length > 0) {
        $('#div2').css('color', 'red');
    }
});

or with the shorthand form:
$(function() {
    if ($('#div1:contains("TriggerWord")').length > 0) {
        $('#div2').css('color', 'red');
    }
});

And here's a live demo.

A: $(document).ready(function () {
    if ($("#div1").html().indexOf('TriggerWord') >= 0) {
        $('#div2').css('color', 'red');
    }
});

A: Regex method:
$(function() {

    var reg = /Trigger/g;

    if($('#div1').text().match(reg)) {
        $('#div2').css({color: 'red'});
    }

});

Working fiddle: http://jsfiddle.net/each/NJ966/

A: $(function() {
    if (/triggerWord/.test($("div1").text()) {
        $("div2").css('color', 'red');
    }
});


text:
Q: crossfilter filtering with blanks I'm using crossfilter and dc to render charts of subject-related observations.
Each observation gets treated as a dimension. However, not all rows will have values for all dimensions as some dimensions have data that is repeated over time. For example, Column A has four values over four rows, but Column B has only one value so the other three rows it will be 0 / "" / blank.
Now if I filter on Column B for rows with a certain range / value, then automatically I lose all other rows for Column A and if I wanted to filter on Column A AFTER filter on Column B then I'm only filtering out of the one common row that has values for both.
This may sound as a logical behaviour, but it's not true to the data, because if I wanted to filter subjects (i.e.) rows that have a certain range for Column A AND a certain range for Column B that results in a wrong result, because of the blank values which are not missing they are just there because it's a table and all columns are expected to have values for all rows.
Is there a way to be able to filter on Column B without that excluding values from Column B only because they're blank?
I'm sorry that took that much text to explain!
UPDATE
An example: observation data is collected for patients, let's say 'weight' and 'blood pressure'. For one subject there might be two weight readings, but four blood pressure readings. When I try to create the data structure for crossfilter, I create two columns one for weight and another for blood pressure. I want to display to the user two bar charts showing the distrubtion of values in each pbservation across all subjects. The user should be able to filter subjects with a weight range AND a blood pressure range. Because two of the rows for a subject will not have values for blood pressure, filtering on weight will filter out subjects(i.e. rows) that might be in the range for the blood pressure filter, but did not have a value for weight so they were wrongly excluded

A: I managed to do it with arrays so now instead of my data structured in a flat table-like structure:
{subjectId: "subject-101", study: "CRC305A", A: "24", B: "79"}
{subjectId: "subject-101", study: "CRC305A", A: "", B: "74"}
{subjectId: "subject-101", study: "CRC305A", A: "", B: "83"}
{subjectId: "subject-101", study: "CRC305A", A: "", B: "74"}
{subjectId: "subject-101", study: "CRC305A", A: "", B: "72"}
{subjectId: "subject-101", study: "CRC305A", A: "", B: "82"}
{subjectId: "subject-101", study: "CRC305A", A: "", B: "74"}
{subjectId: "subject-101", study: "CRC305A", A: "", B: "79"}
{subjectId: "subject-101", study: "CRC305A", A: "", B: "76"}
{subjectId: "subject-101", study: "CRC305A", A: "", B: "72"}

it's structured as below to allow variability in values from one column to another
{subjectId: "subject-101",
 A:["24"],
 B:["79", "74", "83", "74", "72", "82", "74", "79", "76", "72", "79", "76", "77", "72", "83", "69", "72"]
}

And the filtering magically works!
Have one problem still related to the behaviour of dimension.top and dimension.bottom with respect to arrays. I'll post that in another question

A: If the values are logically there, you should probably propagate them to the next rows before sticking them in crossfilter. Crossfilter doesn't have any concept of row order or defaulted values.
If I understand your question correctly, I'd do something like
var lastA, lastB, lastC;
data.forEach(function(d) {
  if(d.A)
    lastA = d.A:
  else
    d.A = lastA;
  if(d.B)
    lastB = d.B;
  else
    d.B = lastB
  // ...
});
var cf = crossfilter(data);

Trying to create sort of "wildcard values" like you suggest in your question, might be possible but you'd definitely have to change at least the filter handler for every chart, because they expect to be dealing with discrete values.


text:
Q: Java OpenCV - detecting ROI, creating submat and copy to original mat I'm trying to blur the faces of all people detected by the webcam.
The problem is that when the webcam detect a face the program shows the crop mat with the blur face.
I tried to put the blur face into the original mat but it doesn't work.
for(Rect rect : faces.toArray()){
    Imgproc.rectangle(frame, rect.tl(), rect.br(), new Scalar(0,0,255),3);
    Rect rectCrop = new Rect(rect.x, rect.y , rect.width, rect.height);
    Mat imageROI = grayFrame.submat(rectCrop);

    //frame is the original mat with the correct size
    Imgproc.GaussianBlur(imageROI, frame, new Size(55, 55), 55);
}

No face detection:

With face detection:

A: use this constructor of Mat
Mat imageROI = new Mat(grayFrame,rectCrop);

instead of
 Mat imageROI = grayFrame.submat(rectCrop);

The constructor gives you  reference to the data matrix that is owned by grayFrame. so any modifications to submat will effect the bigmat.The submat gives copy of the grayFrame data matrix for the crop rectangle. So the modifications on the submat will not effect the bigmat.


text:
Q: AutoIT Logging stops after a few days I run a very simply script to log date and time stamp of how many times I kick an agent off the phone when they are in an unavailable state (logged on to the phone but not "ready" to take phone calls) for too long.
The code (below) that I am using works great, however after a few days (usually 3ish) it stops logging.  The data is going to a text file, to my knowledge there isn't a line limit on a text file, no one is opening the file so it's not in a "read only" state (to my knowledge).  It is (the log file) saved to a shared drive on a server.
Is there anything I can do to prevent this anyone have any ideas?
Thanks.
$cDate = _NowDate()
$cTime = @HOUR & ":" & @MIN & ":" & @SEC
$TSEntry = ";" & $cDate & ";" & $cTime & ";" & $EMPID & ";" & "1"

Local $hFile = FileOpen("\\somedrive\somefolder\xxx TempCopy\RTALog.txt", 1)

_FileWriteLog($hFile, $TSEntry)
$cDate = ""
$cTime = ""
$TSEntry = ""

A: I believe I figured this out, at least I haven't had any issues (knock on formica) since I added the release line:
FileClose($hFile)


text:
Q: Doing calculations with dc.js numberDisplay I would like to make further calculations from the values of two separate numberDisplays in dc.js

Here's the code,
function makeGraphs(data) {

xf = crossfilter(data);
all = xf.groupAll();
txntypeDim = xf.dimension(function(d) { return d.txntype; });
sumAllTXN = txntypeDim.groupAll().reduceSum(function(d) {return d.txnamount;});

numberRecordsND = dc.numberDisplay("#number-records-nd",groupname)
numberRecordsTXN = dc.numberDisplay("#number-records-txn",groupname)

   numberRecordsND
    .formatNumber(d3.format("d"))
    .valueAccessor(function(d){return d; })
    .group(all);

   numberRecordsTXN
    .formatNumber(function(d){return d; })
    .valueAccessor( function(d) { return d; } )
    .group(sumAllTXN);

dc.renderAll(groupname);

}

I want to show the percentage of numberRecordsTXN/numberRecordsND in another div. Is there any way to achieve this?
Edit: solution code;
function makeGraphs(data) {

xf = crossfilter(data);
all = xf.groupAll();
txntypeDim = xf.dimension(function(d) { return d.txntype; });
sumAllTXN = txntypeDim.groupAll().reduceSum(function(d) {return d.txnamount;});

numberRecordsND = dc.numberDisplay("#number-records-nd",groupname)
numberRecordsTXN = dc.numberDisplay("#number-records-txn",groupname)
numberRecordsAVG = dc.numberDisplay("#number-records-avg",groupname)

   numberRecordsND
    .formatNumber(d3.format("d"))
    .valueAccessor(function(d){return d; })
    .group(all);

   numberRecordsTXN
    .formatNumber(function(d){return d; })
    .valueAccessor( function(d) { return d; } )
    .group(sumAllTXN);

   numberRecordsAVG
   .formatNumber(d3.format("d"))
   .valueAccessor(function(d){return d; })
   .group(groupall_percent(numberRecordsTXN, numberRecordsND));

dc.renderAll(groupname);

};

function groupall_percent(numerator, denominator) {
  return {
    value: function() {
      return numerator.value() / denominator.value();
    }
  };
};

A: The input to the numberDisplay is really simple - it is expecting a groupAll object for its group (confusing I know) and this is just an object with a .value() method.
So, you can easily create a fake groupAll which produces a percentage from two other groupAlls:
function groupall_percent(numerator, denominator) {
  return {
    value: function() {
      return numerator.value() / denominator.value() * 100;
    }
  };
}

You would use the resulting object just like the other groupAlls in your example.
But please note that your example doesn't follow your description. A percentage is always a count divided by another count and multiplied by 100. But your example is a sum of amounts divided by a count, which is an average.
To use this code for an average, you would remove the * 100 part.


text:
Q: como hacer select de un SQL server 2008r2 solo en el segundo registro? tengo estos registros de ejemplo
CREATE TABLE Corredores Row int, Usuario varchar (20), Lugar INT;

+---+-------+-----+
|row|Usuario|lugar|
+---+-------+-----+
| 1 | Jose  |  4  |
+---+-------+-----+
| 2 | carlos|  5  |
+---+-------+-----+
| 3 |fulanit|  7  |
+---+-------+-----+

Quiero solo me salga el registro de carlos ejemplo pero sin el JOSE
resultado:
+---+-------+-----+
|row|Usuario|lugar|
+---+-------+-----+
| 2 | carlos|  5  |
+---+-------+-----+

Con esto no me servira:
SELECT TOP 2 * FROM Corredores ORDER BY row desc

ya que me salgra OTRO registro el de Jose

A: Puedes directamente usar ORDER BY con OFFSET y FETCH NEXT:
SELECT *
FROM dbo.Corredores
ORDER BY [Row]
    OFFSET 1 ROWS
    FETCH NEXT 1 ROWS ONLY
;

A: Con la misma idea, puedes extraer una serie de valores con un criterio de ordenación, y del mismo obtener luego el elemento que encaje en lo que necesitas.
CREATE TABLE Corredores (Row int, Usuario varchar (20), Lugar INT)
go
insert into Corredores (row, usuario, lugar)
values
(1,'Jose',4),
(2,'Carlos',5),
(3,'fulanit',7);
go

Y con una tabla derivada obtienes los 2 primeros, y con la salida, solo 1 ordenado del revés.
Select Top (1) d.[row]
             , d.usuario
             , d.lugar
       From (
              Select Top (2) corredores.[row]
                           , corredores.usuario
                           , corredores.lugar
                     From corredores
              Order By row Desc
            ) As d
Order By row Asc;


text:
Q: Sparql Query for wikidata to get multiple values from property I am trying to create a wiki data SPARQL query. What I want to do is to get multiple items from the some property
For example:
I am trying to fetch all data that have property of instance of statistical packages.
But the problem I am facing is for example a Statistical Package of Social Sciences have property type 348  which have multiple versions. I wanted to fetch all these version and also the publication date if the version have publication date as well.
I read some document and try to create a query but I am unable to get all version from the property p:348.
SELECT ?software ?softwareLabel ?developerLabel ?versionLabel ?date
WHERE
{
  ?software wdt:P31 wd:Q13199995 .
   OPTIONAL { ?software wdt:P178 ?developer. }
  OPTIONAL { ?software  wdt:P348 ?version. }
   OPTIONAL {
  FILTER EXISTS {
       ?software wdt:P348 ?version2.
      FILTER ( ?version != ?version2 )
      }
     }

  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
}

Here I have attached the query that I am using to get all the required information.
I am really stuck on this problem. I would be really grateful for any kind of help.

A: either UNION or VALUES is your friend:
SELECT ?software ?softwareLabel ?developerLabel
    ?versionLabel ?date WHERE {   VALUES ?type
    {wd:Q7397 wd:Q13199995 wd:Q166142}   ?software wdt:P31 ?type
    OPTIONAL { ?software wdt:P178 ?developer. }
    OPTIONAL {     ?software p:P348 ?stmt.
    ?stmt ps:P348 ?version.
    OPTIONAL { ?stmt pq:P577 ?date. }   }
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". } }


text:
Q: The server committed a protocol violation. Section=ResponseStatusLine in c# I have spent a whole day trying to resolve this.  I have a custom webserver and requests to it from Chrome or POSTman ReST client work fine. As soon a s I use webclient or httpwebrequest in c#, I get :  The server committed a protocol violation. Section=ResponseStatusLine when trying to transfer a zip file to the client.
I have tried:
public static bool SetAllowUnsafeHeaderParsing20()
{
    //Get the assembly that contains the internal class
    Assembly aNetAssembly = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));
    if (aNetAssembly != null)
    {
        //Use the assembly in order to get the internal type for the internal class
        Type aSettingsType = aNetAssembly.GetType("System.Net.Configuration.SettingsSectionInternal");
        if (aSettingsType != null)
        {
            //Use the internal static property to get an instance of the internal settings class.
            //If the static instance isn't created allready the property will create it for us.
            object anInstance = aSettingsType.InvokeMember("Section", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });
            if (anInstance != null)
            {
                //Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not
                FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
                if (aUseUnsafeHeaderParsing != null)
                {
                    aUseUnsafeHeaderParsing.SetValue(anInstance, true);
                    return true;
                }
            }
        }
    }
    return false;
}

and
<system.net>
  <settings>
    <httpWebRequest useUnsafeHeaderParsing="true" />
  </settings>
</system.net>

in app.config.
I have also tried keep-alive=false and messed with the headers too/
This is the webrequest, which fails on the client2Downloadfile call:
private void sendManifest()
{

    Uri remoteuri = new Uri(Properties.Settings.Default.masterurl);

    SetAllowUnsafeHeaderParsing20();
    using (WebClient client = new WebClient())
    {
        NameValueCollection reqparm = new NameValueCollection();
        reqparm.Add("application", "TestApp");
        reqparm.Add("manifest", manifest);
        try
        {
            byte[] responsebytes = client.UploadValues(Properties.Settings.Default.masterurl, "POST", reqparm);
            string responsebody = Encoding.UTF8.GetString(responsebytes);
            if (responsebody != "")
            {
                using (WebClient client2 = new WebClient())
                {
                    client2.DownloadFile(Properties.Settings.Default.masterurl + "//" + responsebody + "transfer.zip", "c:\\temp.zip");
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

The webserver response can be seen at :
http://gplus2.net:9532/97e456f0-9b57-4315-b03d-40a67f76d440/transfer.zip

Any assistance is greatly appreciated as I have literally run out of ideas. It is obviously a malformed server header, but I have kept it to a minimum.

A: I had the same issue and I solved it using the following method. I created a custom web client that overrides the GetWebRequestMethod.
  class CustomWebClient : WebClient
{
    /// <summary>
    /// Returns a <see cref="T:System.Net.WebRequest" /> object for the specified resource.
    /// </summary>
    /// <param name="address">A <see cref="T:System.Uri" /> that identifies the resource to request.</param>
    /// <returns>
    /// A new <see cref="T:System.Net.WebRequest" /> object for the specified resource.
    /// </returns>
    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).KeepAlive = false;
        }
        return request;
    }
}

Then I made the request in the normal way like this
using (CustomWebClient client = new CustomWebClient())
        {
            client.Headers[HttpRequestHeader.Authorization] = "Basic " + base64String;
            responseData = client.DownloadData(baseUri);
        }

A: I struggled with that issue for a long time, and eventually the problem was a custom header that I added to IIS... I copied the value from somewhere and it contained {cr}:
Open IIS Manager -> go to the web site -> on content view, choose "Response Headers".
check the custom headers on IIS, remove headers if they are not needed, and also see if a header has a malformed value.


text:
Q: How to decode a scaled bitmap from URL efficiently I am designing an app which has to deal with large number of bitmaps with huge size from server. There are ways to decode
Option 1:

*

*Create a buffered inputstream from image url

*Decode only the bounds

*Create scale factor/sample size

*Create a buffered inputstream (again since bitmapfactory closes the stream once decoding is complete)

*Decode the bitmap

Option 2

*

*Create a buffered inputstream from image url

*Decode the bitmap in its original size

*Use bitmap.createScaledBitmap to create desired size.

With option 1, we need to download the bitmap twice where as with 2, we have to explicitly recycle the original sized bitmap which will trigger garbage collection which is a CPU intense operation.
Are there any other methods that can achieve this efficiently?

A: Option 3 :

*

*Download a file to the local file system

*use Option 1

ps. Option 2 will overflow your memory eventually. Highly not recommended.

A: Try to use inJustDecodeBounds. Set it to TRUE and load the file as it is.
The image won't be loaded into memory. But the outheight and outwidth properties of BitmapFactory.Options will contain the actual size params of the image specified. Calculate how much u want to subsample it. like 1/2 or 1/4 or 1/8 etc. and assign 2/4/8 etc. accordingly to the inSampleSize.
Now set inJustDecodeBounds to FALSE and call BitmapFactory.decodeFile() to load the image of the exact size as calculated above.


text:
Q: p:textEditor error I'm having trouble with the p:textEditor component of the Primefaces framework.
A context menu displays a p:dialog that allows you to enter text in a p:textEditor whose initialization is problematic.
I'm having trouble with the p:textEditor component of the Primefaces framework.
A context menu displays a p:dialog that allows you to enter text in a p:textEditor whose initialization is problematic.
Thanks for your help.
Here is my code and the error caused after:
      <p:contextMenu beforeShow="pageC()">
                <p:menuitem value="Ajouter une note"
                            actionListener="#{noteManagerBean.nouvelleNote()}"   <----------
                            oncomplete="PF('widgetNoteDialog').show()"
                            update="idNoteDialog"/>
            </p:contextMenu>

            <p:dialog id="idNoteDialog" widgetVar="widgetNoteDialog>
              ...
                <p:textEditor id="idTexte" value="#{noteManagerBean.noteSelectionnee.texte}" placeholder="Entrez votre texte ici" height="129" style="width: 294px; position: absolute; top: 0px; left: 12px; margin-left: -1px; background-color: transparent">
                        <f:facet name="toolbar">
                            <span class="ql-formats">
                                <button class="ql-bold"></button>
                                <button class="ql-italic"></button>
                                <button class="ql-underline"></button>
                            </span>
                        </f:facet>
                </p:textEditor>

And my bean code
    public void nouvelleNote() {  <---------- noteManagerBean

        setNoteSelectionnee(new UtiNote());

        getNoteSelectionnee().setRefUtilisateurFk(getRefUtilisateurFacade().getUtilisateur().getIdPk());
        getNoteSelectionnee().setPage("pageTableauContributeur");
        getNoteSelectionnee().setElement(null);
        getNoteSelectionnee().setType("N");
        getNoteSelectionnee().setTexte(null);       <---------- same problem with: setTexte("") , setTexte(new String())
        getNoteSelectionnee().setCouleur("Jaune");
        getNoteSelectionnee().setCouleurHexa("FFFA6D");
        getNoteSelectionnee().setPositionX(getNoteDialogLeft());
        getNoteSelectionnee().setPositionY(getNoteDialogTop());
    }

    @Entity
@Table(name = "UtiNote")
public class UtiNote implements Serializable {         <---------- UtiNote entity

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int idPk;
    private int refUtilisateurFk;
    private String page;
    private String element;
    private String type;
    private String texte;     <---------------
    private String couleur;
    private String couleurHexa;
    private String positionX;
    private String positionY;

    public UtiNote() {
    }
    + GETTER/SETTER

Error :
Infos: javax.el.PropertyNotFoundException: /templateNote.xhtml @70,261 value="#{noteManagerBean.noteSelectionnee.texte}": Target Unreachable, 'null' returned null
javax.el.PropertyNotFoundException: /templateNote.xhtml @70,261 value="#{noteManagerBean.noteSelectionnee.texte}": Target Unreachable, 'null' returned null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
at org.primefaces.util.ComponentUtils.getConverter(ComponentUtils.java:146)
at org.primefaces.component.texteditor.TextEditorRenderer.getConvertedValue(TextEditorRenderer.java:109)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1045)
at javax.faces.component.UIInput.validate(UIInput.java:975)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1248)
at javax.faces.component.UIInput.processValidators(UIInput.java:712)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at org.primefaces.component.dialog.Dialog.processValidators(Dialog.java:424)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:575)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1689)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIForm.visitTree(UIForm.java:371)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:403)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:266)
at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:57)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1193)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)

A: The problem in your code is that noteManagerBean.noteSelectionnee.texte throws a javax.el.PropertyNotFoundException. This happens because getNoteSelectionnee() returns a null value. I guess the error occurs whe first loading the page, so you should change your text editor's tag code to:
<p:textEditor id="idTexte"
              value="#{noteManagerBean.noteSelectionnee.texte}"
              placeholder="Entrez votre texte ici"
              height="129"
              style="..."
              rendered="#{not empty noteManagerBean.noteSelectionnee}"
              >

This way it will not fail before noteSlectionnee is set.


text:
Q: User actions like social networks facebook,myspace, all big ones I am working on a social network type site in PHP, I have done this once before and the site outgrew my coding ability to keep up, this was a couple years back and now I am wanting to tackle this project again.
Basicly on my network there is a friend_friend mysql table that keeps track of who is who's friend, for every confirmed friend, there are 2 entries into the DB
here is that table:
    CREATE TABLE IF NOT EXISTS `friend_friend` (
  `autoid` int(11) NOT NULL AUTO_INCREMENT,
  `userid` int(10) DEFAULT NULL,
  `friendid` int(10) DEFAULT NULL,
  `status` enum('1','0','3') NOT NULL DEFAULT '0',
  `submit_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `alert_message` enum('yes','no') NOT NULL DEFAULT 'yes',
  PRIMARY KEY (`autoid`),
  KEY `userid` (`userid`),
  KEY `friendid` (`friendid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1657259 ;

I then have a user table with all users info called friend_reg_user
Then a table for bulletins that users post, the object is to only show bulletins from users who you are friends with.
Here is bulletins table
CREATE TABLE IF NOT EXISTS `friend_bulletin` (

  `auto_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(10) NOT NULL DEFAULT '0',
  `bulletin` text NOT NULL,
  `subject` varchar(255) NOT NULL DEFAULT '',
  `color` varchar(6) NOT NULL DEFAULT '000000',
  `submit_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `status` enum('Active','In Active') NOT NULL DEFAULT 'Active',
  `spam` enum('0','1') NOT NULL DEFAULT '1',
  PRIMARY KEY (`auto_id`),
  KEY `user_id` (`user_id`),
  KEY `submit_date` (`submit_date`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=455144 ;

Ok so to do this I would either run a query on the friend_friend table to get all friends of a user and add them to a string like this 1,2,3,4,5,6 those would be friend ID numbers and then select from bulletin table where bulletin author ID is in my friend ID list
The second method is to use JOINS to get all this data at once.
My quest now finally, once the site gets very large, when there are millions of friends records and bulletins in the DB this all slows down, what are my options to speed things up?  Is there a better way to do this?  Also I am planning on changing bulletins to include more then just bulletins but do more of user actions like the big sites do now so it will show status updates and blogs and bulletins and all

A: What you are looking to do can likely be done in a number of ways.  You can have a summary rollup table that combines all of the associated data (friends in this instance) for a given member.
That is a pretty basic approach but it can become much more sophisticated.
Summary rollups act as a persistent caching mechanism.  You'll have to keep this up to date by some method - a cron job, MapReduce, etc.  You dont want to compute all that data every time you need it - instead, compute it at regular intervals so that it is ready quickly.
Memcache is a great tool for caching but that caches data that has to be computed at some point anyway.  Unfortunately, Memcache is not persistent.  That means that if the memcached servier or service dies, so does your data.
You can explore some advanced cutting edge technologies such as MongoDB, CouchDB, Project Voldemort and neo4j for some even more efficient tools.
Id also recommend looking at the source code for the open source PHP based social network Elgg at http://www.elgg.org/

A: Facebook uses memcached to store SQL databases as distributed hash tables. That's probably your best bet.


text:
Q: affecting disabled options when select or deselect All in ng-multiselect-dropdown I am using the npm package ng-multiselect-dropdown for multiple select in my angular project and its working fine except one case like below:
we have one selected field and it's also disabled. but when I clicked on select All then it's deselected first and select other fields and after that I am not able to select this disabled option again. So my question is now how can we stop this I mean disabled value should not be deselected on choose Select All/Deseclect All.
you can check in below link also
https://stackblitz.com/edit/ng-multiselect-dropdown-selected-disabled-values-problem?file=src/app/app.component.html

A: First of all: It is not the best user experience to select disabled items. But if you wanna do it you can it do with a little trick:
Use the onSelectAll method on your dropdown.
(onSelectAll)="onSelectAll($event)"
And then set it again on onSelectAll. the "...this.selectedItems1" clone the object and then we add the two disabled items.
Code
onSelectAll(data: any) {
    setTimeout(() => {
      this.selectedItems1 = [...this.selectedItems1,
        {id: 1, text: 'AAAAAAA', isDisabled: true},
        {id: 2, text: 'BBBBBBB', isDisabled: true}
      ];
    })
  }

But a onDeselectAll function does not exists. So on unselectAll all items are deselected.
In the end: This is not a bug, this is the expect behavior, look here:

User: If there are disabled checkboxes in the dropdown and when select all is selected, it is selecting the disabled checkboxes as well.

Author: Got it. will be fix in next release.


text:
Q: PayPal configuration I do PayPal integration, and I'm having two issues.

*

*In the settings of pay button you can specify a fixed price or drop-down list with a variety products and prices. How to make button (or URL address) for ufixed price? To be able select price before sending.

*How to automatically receive notification of successful payment? Server must run the script, but only in case successful payment.

A: *

*Buy now button can let your customers to enter their preferred amount and then pay you. You can leave a blank in the amount field when you create Buy Now button on your PayPal account.

*You can integrate PayPal IPN to reach this requirement.
https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNIntro/


text:
Q: How to add data to an existing file and also read it with Java This is a simple program where the user inputs two variable values and chooses an operator. THe program displays the results and then asks the user if they would like to save to a file. The format should be x + y = z. The declared variable which should catch that user input is
    resW = "";

I am unable to get resW to capture the user input variable values so that it can be then saved to the file. If I enter
    resW = "x + y = z";

then that is what is saved. Second problem...when it saves it writes over the previous save. I need it to save each entry as a new line. I don't know how to do that.
Finally, I also would like to view the file as well. As far as I can tell all that I need is the FileReader and BufferedReader to do so. It is not working though and simply moves on to the next line of code.
if (answer.equals("Y")||answer.equals("y")){
    System.out.println(resW);
    bufferedWriter.write(resW);
    bufferedWriter.newLine();
    System.out.println("Results Saved to File.");
}
System.out.println("Do you want to review the results Y/N");
answer = inS.nextLine();

if (answer.equals("Y")||answer.equals("y")){
    FileReader fileReader = new FileReader(fileName);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
}

A: Just use a PrintWriter, and PrintWriter.println, and be sure to close the file
if (answer.equals("Y")||answer.equals("y")) {
    System.out.println(resW);
    printWriter.println(resW);
    printWriter.close();


text:
Q: How to explicitly define the additional arguments in lapply (R) I have a function with two arguments, as follows:
MyFun = function(y, z){0.5*y + 10*z}

I want z to be fixed at 10, and y to take one of the following 1:10.
Using lapply I wrote:
lapply(X = 1:10, FUN = MyFun,  z=10)

This does the job but it seems that R understands that y is X because it is the missing argument to MyFun. My question is how can I define y explicitly in the additional arguments. I would like to type something like:
lapply(X = 1:10, FUN = MyFun, y=X, z=10)

which obviously will not work as R will look for X in the general environment. The problem with implicitly defining y is that when I have a function with, let say, 10 fixed arguments and one argument taking the value of X, it will be complicated (for an external reader) to conclude which argument is running on X. Things are even more complicated if the function contains    ...

A: You may do this with Map() from base (similar to lapply())
Map(MyFun, y=1:10, z=10)

or mapply() also from base, if you want a vector in return (similar to sapply())
mapply(MyFun, y=1:10, z=10)
#  [1] 100.5 101.0 101.5 102.0 102.5 103.0 103.5 104.0 104.5 105.0


text:
Q: Calling symfony helper from a php script needed for Ajax? N00b question:
I'm using Symfony with Doctrine. I have a form where I've added a little Jquery & Ajax check of whether a username that has been inputted into the form already exists. The jQuery calls a short PHP script on my web root that does the MySQL database check and returns true/false, which is then used to determine what error message to show.
However, if possible, I'd like to move the database call to a symfony helper function that then returns the true/false, rather having all the connection info etc on my web root. But I can't seem to be able to call the helper function correctly - all other components of the functionality work fine.
This is what I've got in my little php script:
$availability = GenericHelper::checkUsername();  // a public static function
echo $availability; // returns true/false to Jquery

Anyone? Thanks.

A: Did you correctly load the helper?
sfContext::getInstance()->getConfiguration()->loadHelpers('Generic');

Then you should be able to call checkUsername() directly.
Or you can try to put GenericHelper.class.php to the lib/ directory, this way it will be auto-loaded.

A: Helpers are not meant for that sort of job (they are only meant for "view" related work, that is, generate html, etc).
Instead your should create an action (either in the same controller as your form or in a dedicated ajax controller, I personaly find the first option more easily maintenable) that will do the username check using a method of the model. See http://gist.github.com/286797 for a code example on how to do that (please note this code has not been tested and therefore could not work ootb).
You would then direct your Ajax query to that action.


text:
Q: Error al implementar SDWebImageSwiftUI en Swiftui Estoy intentando mostrar imagenes gif SDWebImageSwiftUI

https://github.com/SDWebImage/SDWebImageSwiftUI

pero me da error en animated Image url

Cannot invoke 'init' with an argument list of type '(url: URL?,
options: SDWebImageOptions)'
Use of unresolved identifier '$isAnimating'

import SwiftUI
    import SDWebImageSwiftUI
    import SDWebImage

struct gifView: View {
    var body: some View {
     Group {
            // Network
            AnimatedImage(url: URL(string: "https://raw.githubusercontent.com/liyong03/YLGIFImage/master/YLGIFImageDemo/YLGIFImageDemo/joy.gif"), options: [.progressiveLoad]) // Progressive Load
            .onFailure { error in
                // Error
            }
            .resizable() // Actually this is not needed unlike SwiftUI.Image
            .placeholder(UIImage(systemName: "photo")) // Placeholder Image
            .indicator(SDWebImageActivityIndicator.medium) // Activity Indicator
            .transition(.fade) // Fade Transition
            .scaledToFit() // Attention to call it on AnimatedImage, but not `some View` after View Modifier

            // Data
            AnimatedImage(data: try! Data(contentsOf: URL(fileURLWithPath: "/tmp/foo.webp")))
            .customLoopCount(1) // Custom loop count
            .playbackRate(2.0) // Playback speed rate

            // Bundle (not Asset Catalog)
        AnimatedImage(name: "animation1", isAnimating: $isAnimating);) // Animation control binding
            .maxBufferSize(.max)
            .onViewUpdate { view, context in // Advanced native view coordinate
                view.toolTip = "Mouseover Tip"
            }
        }
    }
}

struct gifView_Previews: PreviewProvider {
    static var previews: some View {
        gifView()
    }
}

A: //
//  gifView.swift
//  umbre
//
//  Created by Desarollo on 11/27/19.
//  Copyright © 2019 Dream. All rights reserved.
//

import SwiftUI
import SDWebImageSwiftUI
import SDWebImage

struct gifView: View {
      let url = URL(string: "https://s5.gifyu.com/images/ubrellagif.gif")!
     var body: some View {
         VStack {
             AnimatedImage(url: url)
                 .scaledToFit()
                 .frame(width: 850, height: 850)

         }
     }
}

struct gifView_Previews: PreviewProvider {
    static var previews: some View {
        gifView()
    }
}


text:
Q: jquery search in iframe i have smth like following code:
<html>
  <head>
  </head>
  <body>
     <button id="test1" onclick="OnSave()">Save</button>
  </body>
<script>
 function OnSave() {
  if ($("#test2").length)
    {
         alert("i see iframe");
    }
  else
    {
       //some code that will call Iframe via ajax
    }
  }
</script>
</html>

When i click this button iframe have added:
<html>
      <head>
      </head>
      <body>
         <button id="test1" onclick="OnSave()">Save</button>
         <iframe id="test2" src="smth">//button inside that will fire OnSave event</iframe>
      </body>
    <script>
     function OnSave() {
      if ($("#test2").length)
        {
            alert("i see iframe");
        }
      else
        {
          //some code that will call Iframe via ajax
        }
      }
    </script>
    </html>

So, when i click button that will call OnSave function from iframe,jquery didn't see my iframe or smth inside it.How should i call check if iframe exist?

A: You're not calling the OnSave function like that.. try to do this instead
<button id="test1" onclick="OnSave()">Save</button>

(Note the parenthesis after the function name)
Edit: Ok, so you may want to get back to parent window before calling the function
window.parent.functionName();


text:
Q: react and php and mobile I am using react for my frontend, PHP and MySQL for the backend. React is running on localhost, port 3000 and xampp server is in localhost, port 80.
I am getting data from MySQL to php parse to json format. For the frontend, I used axios API to call the data.
While I am in browser, I am able to see the data, but when I access the same page from mobile, I can see only the tables not the json data.

A: Its probably because you are running your application locally, and wont be able to access localhost on your mobile (because as the word itself suggests its LOCALhost). If your mobile is on the same network as your desktop you can access the site from your computers local ip address.

A: I guess your front-end is configured to use http://localhost as the back-end url ? Which means that when running on your phone, its using the phone host as the back-end url :)
Try setting the back-end url to http://192.168.1.99 on the front-end.

A: Change API url to:
http://192.168.1.99/assets/data.php

You used localhost/assets/data.php, but your xampp was installed on your PC, not on your mobile, so your mobile can't access to this.

A: Hi to test it on mobile you could also used Remote Device from chrome developer tools.
For details you can check on this Link
https://developers.google.com/web/tools/chrome-devtools/remote-debugging/webviews


text:
Q: How to check if the dates are not the same I try to write a script that can calculate the difference between two dates, in days, and the diff does not behave as I need to.
More specific, lets say we have the following two date/times:
2015-03-18 23:00
2015-03-19 02:00
The actual time difference is four hours, and in this terms the diff works fine !
But what I like to know is, if the calendar date has been change, and what  is the actual difference.
So in the example above, the calendar dates having 1 day difference.
In the following example
2015-03-18 23:00
2015-03-21 02:00
I have three days difference. So how can I calculate this date difference ?
At the moment I use the following code:
$datetime1 = new DateTime('2009-10-11 23:30');
$datetime2 = new DateTime('2009-10-12 02:30');

$interval = $datetime1->diff($datetime2);

echo "
";
print_r($interval);
echo "
";

and the result is the following:
DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 0
    [h] => 3
    [i] => 0
    [s] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 0
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

Is there any idea ? Thanks ...

A: you surely could use a function like this:
$time1 = strtotime("2008-12-13 10:42:00");
$time2 = strtotime("2010-10-20 08:10:00");

$diff = $time2-$time1;
// the difference in int. then you can divide by 60,60,24 and
// so on to get the h:m:s out of it

or if you more into the build in php functions then something like this might suit your needs:
$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');

$interval = date_diff($date_a,$date_b);

echo $interval->format('%h:%i:%s');

best regards.

A: A really simple solution
Notice: this will only work if the days are in the same month.
$datetime1 = new DateTime('2015-03-18 23:00');
$datetime2 = new DateTime('2015-03-21 02:00');
$difference = $datetime2->format('d') - $datetime1->format('d'); //3

Clean solution
You could remove everything from the date, but the year, month and day and use diff() as you already did.
$datetime1 = new DateTime('2015-03-18 23:00');
$datetime2 = new DateTime('2015-03-21 02:00');
$datetime1modified = new DateTime($datetime1->format('Y-m-d'));
$datetime2modified = new DateTime($datetime2->format('Y-m-d'));
$difference = $datetime1modified->diff($datetime2modified)->d; //3

A: What you can do is remove the Time from each of the dates and then calculate.
example:
$datetime1 ='2009-10-11 23:30';
$datetime2 = '2009-10-12 02:30';

$date1_explode = explode($datetime1,' ');
$date1_explode = explode($datetime1,' ');

$date = $date1_explode[1];
$date = $date2_explode[1];
$date1 = new DateTime($datetime1);
$date2 = new DateTime($datetime1);

$interval = $date1->diff($date2);

echo "
";
print_r($interval);
echo "
";

A: If you don't care about the hours and want to know only if the date changed you can try to diff the dates after you set them to the same hour:
$datetime1 = new DateTime('2009-10-11 23:30');
$datetime2 = new DateTime('2009-10-12 02:30');

// Work on duplicates to not change the original objects if they are needed later
$date1 = clone $datetime1;
$date2 = clone $datetime2;

// Set the same hour on both $date1 and $date2
$date1->setTime(0, 0, 0);
$date2->setTime(0, 0, 0);

// Now you can simply compare $date1 to $date2 to see if they are equal
if ($date1 == $date2) {
    echo('$datetime1 and $datetime2 are on the same date.');
} else {
    echo('$datetime1 and $datetime2 are on different dates.');
}

// Or you can compute the difference
$diff = $date2->diff($date1);
// and format it as you like
echo('There are '.$diff->format('%d').' days between '.$date1.' and '.$date2);


text:
Q: Unable to join Wifi Network I have a strange unexplainable issue with connecting to my home wifi. Let me set this up. I use a Macbook Pro 2016 and iPhone 6S. My router is in the same room that I use the said devices and had always been working fine. Until today.
This morning when I tried to use my MBP, I am unable to join the wifi network that I am usually always on. However, my iPhone is having none of the issues. My iPhone can still connect to the wifi. Strangely enough, I couldn't even connect my MBP to my iPhone's hotspot in the said room. So I did all the troubleshooting methods; delete the necessary network files in the SystemConfiguration folder, reset MBP, reset router, reset NVRAM, and Reset SMC. Still didn't solve the issue.
So I tried moving away from the router, outside my room. Then it worked. I was able to connect to my wifi. When I moved back into my room, the connection died and disconnected. So my question is, what the? There are no new wireless devices in my environment, so I don't understand why as I move away from the router I am able to connect to the network as opposed to moving closer to the router.
Any clues?


text:
Q: Python - string split into columns by template I have a string with spaces and I would like to insert commas , into specific positions based on a template that I define into a list.
For example:

*

*Input
String_in = "{080002092014Mark    21022017392 Ert02 stereo-Gaman09 39-934.4930start 23kg0093029   }"

Template = [2,5,13,21,29,30,33,39,44,55,61,63,65,77]

*Output
String_out = "{0,800,02092014,Mark     ,2102201,3,92 ,Ert02 ,stereo-Gaman09 ,39-934.4930,start ,23,kg,0093029   ,}

Code Tried:
def my_f(string, template, comma):
    for i in template:
        print(string[:i] + comma + string[i:])
my_f("asd asdget t45 4", {1,3,7}, ",")

Output:
a,sd asdget t45 4
asd, asdget t45 4
asd asd,get t45 4

There should only be 1 line with all the commas, not 3 lines.

A: You could do something like:
def split_by_template(s, template, sep=","):
  output_pieces = []
  prev_pos = 0
  for i in template + [len(s)]:
    output_pieces += [s[prev_pos:i]]
    prev_pos = i
  return sep.join(output_pieces)

Or a more concise solution:
def split_by_template(s, template, sep=","):
  return sep.join(s[a:b] for a, b in zip([0] + template, template + [len(s)]))

This basically zips every template position with the previous one, so a template like [1, 2, 5], would produce pairs of [(0, 1), (1, 2), (2, 5), (5, len(str)]. Note that we added an extra [0] and [len(str) at the beginning and the end, so the first and last pieces are correct.
Then cut the relevant pieces of the string, and join them by comma.

A: You can use string slicing to get the portions of the string and make a list of the portions. Then use
','.join(lst) to get the result.
Loop through the template values, remember the previous (say pos1 and pos2). The String_in[pos1:pos2] gets the portion. The last portion will be String_in[pos1:]. The pos1 will be initialized to zero, the pos2 will be the loop variable -- assigned to pos1 at the end of the loop.
lst = []
pos1 = 0
for pos2 in Template:
    lst.append(String_in[pos1:pos2])
    pos1 = pos2
lst.append(String_in[pos1:])
String_out = ','.join(lst)

Something like that, but not tested -- not being at the computer with Python.


text:
Q: React js adding product detail page error: Failed prop type: Invalid prop `to` supplied to `Link`, expected one of type [string, object, function] I am trying to build product detail page for my first ecommerce website, and run into this problem when I want to click one of the product at the home page and direct to the product detail page:
It supposes to show the product detail page "DetailProductPage" when I click one of the product title,the browser still shows the path :local3000/product/{productid},but fail to show the detailproductpage and I got an error in console: Failed prop type: Invalid prop to supplied to Link, expected one of type [string, object, function]
Below is the code, and the current website is weiwhite.com
In App.js
import React, { useEffect } from 'react';
import './App.css';
import Header from './Header';
import Home from './Home';
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";
import {auth} from './firebase';
import { useStateValue } from './StateProvider';
import {loadStripe} from '@stripe/stripe-js';
import {Elements} from '@stripe/react-stripe-js';
import Footer from './Footer';
import DetailProductPage from './DetailProductPage';

function App() {

  return (
    <Router>

      <Switch>
        ...
        <Route path='/'>

          <Home />

        </Route>

        <Route path='/product/:productId'>
          <DetailProductPage />
        </Route>

        </Switch>

    </Router>
  );
}

export default App;

In Product.js
import React from 'react';
import "./Product.css";
import { useStateValue } from './StateProvider';
import {Link} from "react-router-dom";
import {Card} from 'antd';
import DetailProductPage from './DetailProductPage';

function Product({item}) {

   const [{basket},dispatch]=useStateValue();

   const addToBasket=() =>{
     //dispatch the item into the data layer
      dispatch ({
        type:'ADD_TO_BASKET',
        item: {
          id: item.id,
          title: item.title,
          image: item.image,
          price: item.price,
        },
      });
   };

  return (

    {/* <a href={`/product/${item.id}`}> */}

    <a href={`/product/${item.id}`}>

{item.title}

            $
            {item.price}

        {/*

            {Array(rating).fill().map((_, i) =>(

))}

 */}
      <button onClick={addToBasket}> Add to Basket</button>

    {/* </Link> */}

  );

}

export default Product;

In Products.js
import styled from "styled-components";
import Product from "./Product";
import { productItems } from "./Data";

const Container = styled.div`
    width: 100%;
    display: flex;
    padding: 10px;
    flex-wrap: wrap;
    justify-content: space-between;

`;

const Products = () => {
  return (
      <Container>
          {productItems.map(item =>(
              <Product item={item} key={item.id}/>
          ))}
      </Container>
  );
};

export default Products;

in Datas.js

export const productItems = [
    {
        id: 1,
        image: "../Swiming_fish_W.png",
        title: "Swim Fish",
        price:49.99,
    },

    {
        id: 2,
        image: "../Duckling_W.png",
        title: "Bath Duckling",
        price:49.99,
    },
...

in DetailProductpage.js
import React from 'react'

function DetailProductPage() {
  return (

DetailProductPage

  )
}

export default DetailProductPage

A: I found that in App.js, the route to './product/:id' have to be placed above the home page '/'. after this change, everything works well.


text:
Q: OrCAD Footprint in .brd layout different from the .dra file I made a custom footprint for an 8 pin TSSOP IC, using custom padstacks and creating a new package (no wizard). Each of the four pins on a side are 0.3mm wide and 0.5mm apart (BSC). In the .dra file everything looks right. However, when I add the components into a .brd file, the pins have a couple issues. On both sides, the two middle pins are 0.6mm away from the corner pins, and only 0.4mm away from each other. Not only are these the wrong distances, it also doesn't add up to the correct total distance from corner pin to corner pin (1.6mm instead of 1.5mm). The pins are also only 0.2mm wide instead of 0.3mm. Any idea what could be causing this? I know there are a bunch of options/settings that could contribute but I don't know what they are (fairly new OrCAD user).
Image with blue pinsis .dra, red pins is .brd

A: The .brd file has its own copy of all footprints and padstacks from the first moment they were used. If it did not, then every time you moved the .brd file you would need to move every other file with it too, even footprints and padstacks in other directories. And someone mucking with a component or padstack for use in design could destroy its use in a previously existing design.
Similarly, footprint files also contain their own copy of the padstacks they are using which also need to be refreshed.
You need to refresh the footprint and/or padstacks in the .brd file if you ever want the .brd file to take on any changes.
For footprints, Place>Update Symbols
For padstacks which appear directly in the .brd file (and not those that appear through a symbol. Things like vias.) you go Tool>Padstack>Refresh.
It might vary a bit from version to version, so basically look in the menus that you normally use to place components or where you handle padstacks.
For that matter, you can also export all padstacks and footprints used in a .brd file with File>Export>Libraries
EDIT:
I just noticed you are talking about a new footprint. If the footprint had never been used before, then either the the units being used for either your footprint or .brd file are not what you think they are. Or the datums for various things like padstacks aren't what you think they are.
I always use move x, move y, move x y, move ix, move iy, and move ix iy commands for placement.
If it's anything else I would need to see the file. I've always used a wizard though but often need to modify things afterwards for weird irregular footprints.

A: General info (aiming for clarity, not perfect accuracy), feel free to correct me if I made dumbnesses.
Orcad uses DRA files to generate a "symbol" (footprint) file (PSM). This PSM file is what is ACTUALLY used in your board design. The filename of the PSM (without the extension) must match the value of the "PCB Footprint" field in your schematic.
SO, if your "PCB Footprint" == "smr0805", then orcad will look for a file called smr0805.psm, and copy that in to your design.
If you reference a PADSTACK in your SYMBOL drawing, orcad will look for a .PAD file of the same name, and copy that in to your design.
For both the SYMBOL and PADSTACK, orcad will search in directories you tell it to in the respective design feature paths setting.
Things to check:

*

*Ensure your DRA file has generated a PSM file. This should happen automatically, but you can ensure it happened.

*Ensure Orcad has the PATHs of both your PSM and PAD files that you are creating.

*Orcad will use the FIRST file it finds, from top to bottom. So, ensure your paths are ordered "correctly". In my case, my directories are ordered so that the find priority is: project, company library, orcad standard library, downloads.

*as DKNguyen said, ensure all your pads and symbols are up to date.


text:
Q: __vite_ssr_import_1__.Client is not a constructor Error I am developing a simple app to showcase CRUD operations with Appwrite and Nuxt 3 (Release Candidate 11). The source code to the same can be found here.
I am using the landing page of the app (index.vue) for simple redirection i.e. if the account exits in the accountStore, I want to redirect the user to /workouts route, else ask them to login by redirection to the /login route.
The problem I am facing is when I am landing on the index.vue page (with no user session in progress in Appwrite), I am still getting redirected to /workouts route, instead of the /login route. I presume the reason for the same is the following error that is being logged in the console.

I need help in figuring out from where is the error message originating and how to possibly remedy it.
Here is my public github repo: https://github.com/EshaanAgg/workout-buddy

A: Maybe this is a bug with Nuxt 3 or Vite since Nuxt 3 is currently only a release candidate.
Also, in my opinion, Server Side Rendering (SSR) always complicates things so much. It doesn't look like you're using SSR, so you could possibly update your nuxt.config.ts to disable SSR:
{
   // ... other stuff
   ssr: false
}


text: Q: Алгоритм генерации SMS-кода Кто-нибудь знает, какие алгоритмы используются при генерации SMS-кодов для привязки телефонных номеров к аккаунтам? Используется ли при этом номер телефона или просто берётся случайный незанятый на текущий момент код?


text:
Q: Como deixar novo form sem depender do outro? Aqui o código que faz abrir meu Form4:
Form4 form4 = new Form4();
form4.Show();
// Aqui um código gigantesco que demora aproximadamente 1 minuto para ser executado.
form4.Close();

O problema é que enquanto o Form4 está aberto, ele fica meio cinza e estático, não da pra mover ele e nem fechar. Eu entendo que ele fica meio dependente do código do form anterior, como resolver isso?

A: Olá, de uma olhada em: Processamentos longos...
Lá tem uma resposta postada por mim e acredito que seja uma solução para você.
Basicamente você precisa iniciar este segundo form em uma Thread diferente da que executa o processamento principal, assim os forms ficam independentes e quando um processamento longo for executado o outro form não ficara congelado.
Abraços!


text:
Q: Remotely enable Windows 10 RDP without physical access Given that I have network access and valid login credentials to my Win 10 Pro machine which was upgraded overnight from Win 7, how do I remotely enable Remote Desktop Protocol on my newly upgraded Win 10 machine from a Linux server on the same network?
The Win 10 upgrade which ran overnight disabled RDP which I had previously enabled in Win 7. I can SSH in to a Linux machine on my home network and have network access to the Win 10 machine from there. I only have access to a Linux machine on the same network. I do not have physical access to the Win 10 machine right now.


text:
Q: Why does clicking expand button closes the side panel in react? i have a side panel with items listed. when the list item content overflows expand button appears and clicking that expand btn would show the entire content of list item
For this i have created a expandable component. this will show arrow_down when list item content overflows and clicking arrow_down shows up arrow_up.
However with the below code, clicking button 1 just makes the sidpanel disappear instead of arrow_up appearing. could some one help me solve this. thanks.
export default class Expandable extends React.PureComponent{
    constructor(props) {
        super(props);
        this.expandable_ref = React.createRef();
        this.state = {
           expanded: false,
           overflow: false,
        };
     }

    componentDidMount () {
        if (this.expandable_ref.current.offsetHeight <
             this.expandable_ref.current.scrollHeight) {
             this.setState({overflow: true});
        }
    }

    on_expand = () => {
        this.setState({expanded: true});
        console.log("in expnad");
    };

    on_collapse = () => {
        this.setState({expanded: false});
    };

    render () {

        return (

                    {this.props.children}

                {this.state.overflow && this.state.expanded &&

                        <button  onClick={this.on_collapse}>
                            {this.props.arrow_up}</button>

}
                {this.state.overflow && !this.state.expanded &&

                        <button onClick={this.on_expand}>
                            {this.props.arrow_down}</button>

}

        );
    }
}

In the above code i pass the base_height to be 42px.
Edit:
i have realised for the side panel component i add eventlistener click to close the side panel if user clicks anywhere outside sidepanel. When i remove that eventlistener it works fine....
class sidepanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.sidepanel_ref = React.createRef();
    }

    handle_click = (event) => {
        if (this.sidepanel_ref.current.contains(event.target)) {
            return;
        } else {
            this.props.on_close();
        }
    };

    componentDidMount() {
        document.addEventListener('click', this.handle_click, false);
    }

    componentWillUnmount() {
        document.removeEventListener('click', this.handle_click, false);
    }

    render() {
        return (

                    {this.props.children}

        );
    }
}

when i log the event.target and sidepanel_ref.current i see the button element in both of them but svg seems different in both of them.
How can i fix this?

A: Probably it is because click events bubble up the component tree as they do in the DOM too. If you have an element with an onClick handler inside an element with another onClick handler it will trigger both. Use event.stopPropagation() in the handler of the inner element to stop the event from bubbling up:
export default class Expandable extends React.PureComponent{
    constructor(props) {
        super(props);
        this.expandable_ref = React.createRef();
        this.state = {
           expanded: false,
           overflow: false,
        };
     }

    componentDidMount () {
        if (this.expandable_ref.current.offsetHeight <
             this.expandable_ref.current.scrollHeight) {
             this.setState({overflow: true});
        }
    }

    toggleCollapse = event => {
        // use preventDefault here to stop the event from bubbling up
        event.stopPropagation();
        this.setState(({expanded}) => ({expanded: !expanded}));
    };

    render () {
        const {className, container_classname, base_height, expand, arrow_up, arrow_down} = this.props;
        const {overflow, expanded} = this.state;

        return (

                    {this.props.children}

                {overflow && (

                        <button onClick={this.toggleCollapse}>
                            {expanded ? arrow_up : arrow_down}
                        </button>

                )}

        );
    }
}


text:
Q: How to use Wikipedia's Table of Clebsch–Gordan coefficients? Wikipedia has a nice article outlining Clebsch-Gordan coefficients.
For example, to my understaning, this table tells us how to combine two particles, each having a maximum total angular momentum $1$ into one wavefunction with maximum angular momentum $2$:

Take the first column from the last table. It tells us, I believe:
$|2,0\rangle = \sqrt{\frac{1}{6}} |1,1\rangle |1,-1\rangle +\sqrt{\frac{2}{3}}|1,0\rangle|1,0\rangle+\sqrt{\frac{1}{6}} |1,-1\rangle|1,1\rangle$
How I interpret this:
The total angular momentum of a particle which arises from such a combination of wavefunctions of two other particles will have total angular quantum number 2 (so total angular momentum $\sqrt{j(j+1)\hbar^2}=\sqrt{2(2+1)\hbar^2}$), but $0$ around the $z$ axis (as $m_j$, what I understand to be the angular momentum around the $z$ axis, is $0$).
So the constituent particle's angular momentum is not aligned with each other, in fact they are antialigned enough so that the total z-directional angular momentum will be 0.
Is this interpretation of what's going on correct? My concern is that there are no tables for $m=-1,-2$. If my interpretation of the situation is correct, I see no reason why I couldn't produce a combined particle with these $m$ values, if I can do it for $m=0,1,2$.

A: The Wikipedia article says the following:

For brevity, solutions with $M < 0$ and $j_1 < j_2$ are omitted. They may be calculated using the simple relations
$$ \langle j_{1},j_{2};m_{1},m_{2}\mid j_{1},j_{2};J,M\rangle =(-1)^{J-j_{1}-j_{2}}\langle j_{1},j_{2};-m_{1},-m_{2}\mid j_{1},j_{2};J,-M\rangle .$$
and
$$ \langle j_{1},j_{2};m_{1},m_{2}\mid j_{1},j_{2};J,M\rangle =(-1)^{J-j_{1}-j_{2}}\langle j_{2},j_{1};m_{2},m_{1}\mid j_{2},j_{1};J,M\rangle.$$

In other words, the Clebsch-Gordon coefficients for a negative value of $m$ are the same (up to a sign) as those for the corresponding positive value of $m$, so long as you switch the signs of $m_1$ and $m_2$ as well.


text:
Q: How to check if a variable value already exists in a file? This is my code. I want to check whether or not the value the user entered for idnum already exists as the idnum for any other patient in the file "patient.dat". This code doesn't show any error but it doesn't work logically either. I'm using the TurboC 7 compiler.
void patient::idnum(patient p)
{
   do
   {
     clrscr();
     int found4=0;
     cout<<"enter a 4 digit id number";
     cin>>idno;
     ofstream f3;
     ifstream f4;

     f4.open("patient.dat",ios::in);
     f4.seekg(0);

     while(!f4.eof())
     {
       f4.read((char*)&p,sizeof(p));
       if(p.getid()==idno)
         cout<<" id number already in use.. try again";
       else
         found4=1;
     }

     if(found4==1)
     {
       cout<<"valid entry... pls continue";
       f3.open("patient.txt",ios::out|ios::app);
       f3.write((char*)&p,sizeof(p));
       f3.close();
       getch();
     }

   } while(p.getid()!=idno);
}


text:
Q: Changing directory on mac affects all files in Xcode Project I simply wish to change the name of a folder that lies in my root project folder.
I have changed the name of a project (say from Proj1 to Proj2).
I now have a folder on my desktop that reads Proj2. Inside is Proj2.xcodeproj and a folder called Proj1 with all of my source files and resources.
I want to change that folder to be consistent and read Proj1, however if I change it every file in my xCode proj becomes red.
Is there a technique to change this folder within xCode such that I can rename the folder and keep all my files intact with the appropriate structure (such as what groups the files are in)?

A: It's annoying, indeed.
However, there's no way to keep files on the hard drive (SSD, ..) and group names and the project structure in Xcode in sync automatically.
You can re-assign the locations of the files in your red folders manually to fix it.
Wish Xcode would offer a feature like this since we've switched to Xcode from MW CodeWarrior, but..

A: After you rename the folder, open the project in Xcode and select this folder. You can choose the renamed folder in the File Inspector Pane.


text:
Q: If $f : X \to Z$ is a morphism of schemes, which factors through an open $i : U \to Z$ on the level of topological spaces... If $f : X \to Z$ is a morphism of schemes, which factors through an open $i : U \to Z$ on the level of topological spaces... then is there a (unique) morphism of schemes $g : X \to U$ which makes the diagram commute.
I believe I just proved this (it is a tautology, just define the map to be the restriction of $f^{\#}$ on the relevant opens), but I want to make sure that I am not fooling myself (this stuff feels so complicated...).
Can someone comment?

A: Let $g \colon X \to U$ denote the topological map.

Lemma 1. We have a canonical isomorphism $f_* \mathcal O_X|_U \cong g_* \mathcal O_X$.

Proof. Let $V \subseteq U$ be open. Then $f^{-1}(V) = g^{-1}(V)$, so
$$(f_* \mathcal O_X|_U)(V) = f_* \mathcal O_X (V) = \mathcal O_X (f^{-1} V) = \mathcal O_X(g^{-1}V) = (g_* \mathcal O_X)(V).$$

Lemma 2. The restriction of $f^\# \colon \mathcal O_Z \to f_* \mathcal O_X$ to $U$ gives a morphism of sheaves of rings
  $$g^\# \colon \mathcal O_U \to g_* \mathcal O_X.$$

Proof. The identification of Lemma 1 is an isomorphism of sheaves of rings.

Lemma 3. Let $z \in U$. Then $\mathcal O_{Z,z} = \mathcal O_{U, z}$.

Proof. One is the colimit over all opens $V \subseteq Z$ containing $z$, and the other over all $V \subseteq U$ containing $z$. The latter forms a cofinal system in the former, thus the colimits agree.

Proposition. The pair $(g,g^\#)$ is a morphism of locally ringed spaces.

Proof. Lemma 1 and Lemma 2 show that it is a morphism of ringed spaces. Let $x \in X$. By assumption, the map $f^\#_x \colon \mathcal O_{Z, f(x)} \to \mathcal O_{X,x}$ is a local ring homormophism, hence by Lemma 3 so is $g^\#_x \colon \mathcal O_{U,f(x)} \to \mathcal O_{X,x}$.
Remark. One then needs to go on to prove that $f$ factors through $g$, and that such a factorisation is unique. I will not carry out these steps.


text:
Q: Siddhi polling interval on sqs source not working Hi I'm new to Siddhi and have set up an app with a SQS source, I've tried setting the polling interval to 10 seconds and the Max number of messages to 1.
However I just get a constant stream of messages as if it is just ignoring the values.
Here's my code with sensitive info removed

@App:name('SQS TEST')
@App:description('Description of the plan')

@source(type = 'sqs',
    queue = '',
    access.key = '',
    secret.key = '',
    region = '',
    polling.interval = '10000',
    wait.time = '20',
    max.number.of.messages = '1',
    delete.messages='false',
    number.of.parallel.consumers = '1',
    @map(type = 'json', fail.on.missing.attribute='false', enclosing.element='$.entries',
        @attributes(val1 = 'val1', val2='val2')))

define stream inStream (val1 string, val2 string);

@sink(type = 'log', prefix = 'Cafe Feed:')
define stream log_received (val1 string, val2 string);

from inStream
select val1,val2
insert into log_received;

Any help would be much appreciated thank you.

A: The default behavior for the SQS source is to pull messages from the sqs queue until there are no messages left in the queue the amazon API allows the devs to define the number of messages retrieved per request the above 'max.number.of.messages' exposes that property.
To overcome this issue you can fix the visibility timeout of the queue to a greater value to stop the messages from being returned or delete a message after reading from the queue.


text:
Q: Getting Jquery Error: SyntaxError: missing : after property id in form validations Following is my code of contact form but when I am trying to test it on just name Above error is occured

<form id="form">

Name: *
<input type="text" id="name" placeholder="Name"/>
Email: *
<input type="text" id="email" placeholder="Email"/>
Contact No: *
<input type="text" id="contact" placeholder="10 digit Mobile no."/>
Message:
<textarea id="message" placeholder="Message......."></textarea>
<input type="button" id="submit" value="Send Message"/>
</form>

After running this code getting following error in console. Googling everywhere but no solution found.Please help me.
SyntaxError: missing : after property id
    var name = $("#name").val();

A: Your brackets and braces are incorrect on the #submit click function:
$(document).ready(function(){
    $("#submit").click(function() { // note extra ) here
        // your code...
    });
}); // swapped order of braces here

A: Just correct closing brackets of $(document).ready(function(){

A: Your code will be like this:


text:
Q: How to activate an Anaconda environment in a Singularity recipe I am trying to create a singularity image and recipe that will create an anaconda environment and then activate said environment so I can build the python wheel of a project in that environment so it's 100% installed and functional after the singularity build is completed.
Bootstrap: docker
From: nvidia/cuda:9.0-cudnn7-devel-ubuntu16.04

%environment

  # use bash as default shell
  SHELL=/bin/bash

  # add CUDA paths
  CPATH="/usr/local/cuda/include:$CPATH"
  PATH="/usr/local/cuda/bin:$PATH"
  LD_LIBRARY_PATH="/usr/local/cuda/lib64:$LD_LIBRARY_PATH"
  CUDA_HOME="/usr/local/cuda"

  # add Anaconda path
  PATH="/usr/local/anaconda3/bin:$PATH"

  export PATH LD_LIBRARY_PATH CPATH CUDA_HOME
  export MKL_NUM_THREADS=1
  export OPENBLAS_NUM_THREADS=1

%setup
  # runs on host
  # the path to the image is $SINGULARITY_ROOTFS

%post
  # post-setup script

  # load environment variables
  . /environment

  # use bash as default shell
  echo "\n #Using bash as default shell \n" >> /environment
  echo 'SHELL=/bin/bash' >> /environment

  # make environment file executable
  chmod +x /environment

  # default mount paths
  mkdir /scratch /data

  #Add CUDA paths
  echo "\n #Cuda paths \n" >> /environment
  echo 'export CPATH="/usr/local/cuda/include:$CPATH"' >> /environment
  echo 'export PATH="/usr/local/cuda/bin:$PATH"' >> /environment
  echo 'export LD_LIBRARY_PATH="/usr/local/cuda/lib64:$LD_LIBRARY_PATH"' >> /environment
  echo 'export CUDA_HOME="/usr/local/cuda"' >> /environment

  # updating and getting required packages
  apt-get update
  apt-get install -y wget git vim build-essential cmake

  # creates a build directory
  mkdir build
  cd build

  # download and install Anaconda
  CONDA_INSTALL_PATH="/usr/local/anaconda3"
  wget https://repo.continuum.io/archive/Anaconda3-5.0.1-Linux-x86_64.sh
  chmod +x Anaconda3-5.0.1-Linux-x86_64.sh
  ./Anaconda3-5.0.1-Linux-x86_64.sh -b -p $CONDA_INSTALL_PATH

  # download and install CaImAn
  git clone https://github.com/flatironinstitute/CaImAn.git
  cd CaImAn
  conda env create -n caiman -f environment.yml
  source activate caiman
  pip install .
  caimanmanager.py install
  source deactivate

%runscript
  # executes with the singularity run command
  # delete this section to use existing docker ENTRYPOINT command

%test
  # test that script is a success

I've tried both conda activate and source activate and get the same error for both.
+ source activate caiman
/bin/sh: 41: source: not found
ABORT: Aborting with RETVAL=255
Cleaning up...

Is this just something I have to do afterwards by making the image writable?
That would be the next default solution, but it would be nice if the recipe could just work.
*Edit 1
. activate caiman returns.
+ . activate caiman
+ [[ -n ]]
/bin/sh: 4: /usr/local/anaconda3/bin/activate: [[: not found
+ [[ -n ]]
/bin/sh: 7: /usr/local/anaconda3/bin/activate: [[: not found
+ echo Only bash and zsh are supported
Only bash and zsh are supported
+ return 1
ABORT: Aborting with RETVAL=255
Cleaning up...

*Edit 2
By using a newer version of Anaconda, the not found error goes away. All I did was change the Anaconda distribution I got with wget, and I also forced and update just to be doubly sure.
# download and install Anaconda
  CONDA_INSTALL_PATH="/usr/local/anaconda3"
  wget https://repo.continuum.io/archive/Anaconda3-5.3.1-Linux-x86_64.sh
  chmod +x Anaconda3-5.3.1-Linux-x86_64.sh
  ./Anaconda3-5.3.1-Linux-x86_64.sh -b -p $CONDA_INSTALL_PATH
  conda update -n base -c defaults conda
  pip install --upgrade pip

A: If I am not wrong (which is totally possible) the same happens with virtualenv.
The problem is source is not a command, try:
. activate caiman

instead of
source activate caiman

Editing after updated question, check this https://github.com/conda/conda/issues/6639 you might want to investigate what your activate is doing (seems to be looking for non existing files)


text:
Q: java.util.Date cannot be cast to Object[] I'm using java reflection to call methods at runtime. How do I cast a date object into an object array?
ie,
Method m = ....;
Object[] result = (Object[]) m.invoke(...);

public Date getDate() {
   return new Date();
}

Would give:
java.lang.ClassCastException: java.util.Date cannot be cast to [Ljava.lang.Object;

Edit: yeah, I should just add it to an Object array instead and return it.

A: you don't need to as invoke is a varargs method. you can do.
 Object result = method.invoke (instance , new Date ());

There is no need to create an array.
If it's the result you want to change you can wrap it, but I suspect there is no real need to do this. I would see if you really need an array


text:
Q: Use UNION in Codeigniter and get error? I want select data with UNION as follow:
$find = 'hello';
$data = $this->db->query('SELECT * FROM tour_foreign_residence WHERE name LIKE '%$find%' UNION SELECT * FROM tour_foreign WHERE name LIKE '%$find%''); // Line number 46

But I encounter this error:
> A PHP Error was encountered
 Severity: Warning
 Message:
> Division by zero
 Filename: foreign.php
 Line Number: 46

>
> A Database Error Occurred
 The query you submitted is not
> valid.
 Filename:
> D:\xampp\htdocs\system\database\DB_driver.php
 Line
> Number: 257

How can I fix it?
Update:
Error:
> A Database Error Occurred
 Error Number: 1222
 The used SELECT
> statements have a different number of columns
 SELECT * FROM
> tour_foreign_residence WHERE name LIKE "%hello%" UNION SELECT * FROM
> tour_foreign WHERE name LIKE "%hello%"
 Filename:
> D:\xampp\htdocs\system\database\DB_driver.php
 Line Number: 330

A: You're throwing single quotes in the string without escaping them. That could be your problem.

A: Table tour_foreign_residence and tour_foreign have a different number of columns. Remove * after each select to set the same number of columns.

A: Change this:
$data = $this->db->query('SELECT * FROM tour_foreign_residence WHERE name LIKE '%$find%' UNION SELECT * FROM tour_foreign WHERE name LIKE '%$find%'');

to
$data = $this->db->query('SELECT * FROM tour_foreign_residence WHERE name LIKE "%' . $find . '%" UNION SELECT * FROM tour_foreign WHERE name LIKE "%' . $find . '%"');


text:
Q: Android Studio AVD screen size and position I have a problem with Android Studio AVD as You can see on the image below:
AVD screenshot
I am using Android Studio 2.3.1 up to date in Fedora Linux.
No matter if I change the resolution, screen size, phone type of the AVD it looks the same as in the image.
How can I fix it?
Thank You!

A: I'm struggling with similar problem right now. In my case... I've created the AVD from a command line for example avdmanager --verbose create avd --force --name myEmulator--device "4in WVGA (Nexus S)" --package "system-images;android-23;google_apis;x86" --tag "google_apis" --abi "x86" and then if you want to run newly created AVD emulator you should type the command 'emulator -avd myEmulator (and optional arguments)'. Maybe it was an issue with a path to system image.


text:
Q: Official documentation for attachment form fields I'm trying to use the attachment_fields_to_edit hook to create new fields on media attachments. According to the new documentation, one of the parameters is an "array of attachment form fields".
I can't find, however, where on the documentation are the specs on how to build this array. I found this page on the Codex, but the provided example uses only value, label and helps. I found a few more parameters in the source of get_attachment_fields_to_edit, such as input and html, and in a few tutorials I see required.
add_filter('attachment_fields_to_edit', 'new_attachment_field', 10000, 2);
function new_attachment_field( $form_fields, $post ) {
  $field_value = get_post_meta( $post->ID, 'newfield', true );
  $form_fields['newfield'] = array(
    'value' => $field_value ? $field_value : '',
    'label' => __( 'New Field' ),
    'required' => true,
    'input' => 'textarea',
    'html' => '<no idea what goes here>',
    '???' => '???',
    'helps' => __( 'Help message' )
  );
  return $form_fields;
}

Most are intuitive, except for html. And I don't know if there are more parameters I'm unaware of.
Where can I find more information in the official documentation?

A: TL;DR : I guess there's no official and complete documentation, not even in the source. html in a $form_fields is used for custom HTML markup, if you decide not use the provided options.
Longer Answer:
Hey @22510, I am not sure I understood your question correctly and I am guessing what you really want to know is what are the mandatory items in the array for a specific item in $form_fields, as you don't need to create it because it already exists, is created by core as you can see in line 1210 of wp-admin/includes/media.php (as WordPress 4.7.4)
Which brings to answer properly. In cases like this, where there no or little documentation, the best course of action is reading the source. But in this instance, the source is not properly documented. Bummmer.
But if you follow the trail inside the code you will notice the purpose of this field.
Example from lines 1216-1220:
    'post_excerpt' => array(
        'label'      => __('Caption'),
        'input'      => 'html',
        'html'       => wp_caption_input_textarea($edit_post)
    ),

Lines 1236-1242:
    'image_url' => array(
        'label'      => __('File URL'),
        'input'      => 'html',
        'html'       => "<input type='text' class='text urlfield' readonly='readonly' name='attachments[$post->ID][url]' value='" . esc_attr($image_url) . "' />
",
        'value'      => wp_get_attachment_url($post->ID),
        'helps'      => __('Location of the uploaded file.')
    )

And a little below, on lines 1285-1289:
    $form_fields['align'] = array(
        'label' => __('Alignment'),
        'input' => 'html',
        'html'  => image_align_input_fields($post, get_option('image_default_align')),
    );

You see, when you create a new field, if you don't provide an input value, it will use an text input type. If you do provide a value like 'input' =>'textarea' it will create and textare automatically, but if you 'input' =>'html', then you are telling WordPress to use the markup you will specify in html array item.
So, in media.php lines 1219 and 1285 they use two functions to create this markup, 1239 simply uses an string with some variables.
So, if you will use a normal textarea field, you don't need html:
$form_fields['newfield'] = array(
    'value' => $field_value ? $field_value : '',
    'label' => __( 'New Field' ),
    'required' => true,
    'input' => 'textarea',
    'helps' => __( 'Help message' )
);

But if, for example, you want a photo credits field prepopulated with the post author name, you would use html as the vale for input key and a custom markup string for the html key :
$form_fields['credits'] = array(
    'value' => $field_value ? $field_value : '',
    'label' => __( 'Photo Credits' ),
    'required' => true,
    'input' => 'html',
    'helps' => __( 'Give credits where credit is due.' ),
    'html'  => "<input type='text' class='text credits' name='attachments[$post->ID][credits]' value='" . esc_attr( esc_get_the_author_meta( 'user_nicename', $post->post_author ) ) . "' />
",
);

Hope this helps.


text:
Q: Showing o refuting that $(1+|x|^2e^{|x|^2})\mathcal{F}u\in S'(\mathbb{R}^n)$? A doubt.
Let $u$ in $L^p(\mathbb{R}^n)$ (then $u\in S'(\mathbb{R^n}$) the set of tempered functions) and $\mathcal{F}$ is the Fourier transform.
I know that $\mathcal{F}u\in S'(\mathbb{R}^n)$ but $(1+|x|^2e^{|x|^2})\mathcal{F}u\in S'(\mathbb{R}^n)$? (or $(1+|x|^2e^{|x|^2})\mathcal{F}u\in L^p(\mathbb{R}^n)?$)