text:
Q: Sencha 2.4.2 cordova app stuck at "Device Ready" Screen on device I am new to sencha and creating a app which is coming up on browser but not device.
I have followed basic steps as mentioned in tutorial :
https://docs.sencha.com/touch/2.4/getting_started/building_your_first_app.html
To simulate the case, here are the steps we executed:

*

*sencha -sdk  generate app MyApp

*sencha cordova init com.mycompany.MyApp MyApp

*sencha web start         (with this we are able to run in browser)

*Updated app.json to include android:
"builds": {
  "web": {"default": true},
    "android": {
    "packager": "cordova",
    "cordova" : {
          "config": {
            "platforms": "android",
            "id": "com.mycompany.MyApp",
            "name": "MyApp"
        }
    }
}
},

*sencha app build android

*sencha app build -run android

*Post this we were able to open app in android studio from cordova/platforms/android

*when we executed from studio, it is always stuck at "Apache Cordova- Device is ready " screen .. which is from the html of MyApp/cordova/platforms/android/assets/www/index.html and it is not  referring to /MyApp/index.html

Its same behaviour on iOS as well!!
Are we missing out any steps here ?

A: You app.json was not structured properly. Edit your app.json to reflect below and run sencha app build.
"builds": {
    "native": {
        "default": true,
        "packager": "cordova",
        "cordova" : {
            "config": {
                "platforms": "android",
                "id": "com.mycompany.MyApp",
                "name": "MyApp"
            }
        }
    }
},


text:
Q: Softmax vs the Dirichlet distribution As far as I understand one can in principle model the distribution over a set of $k$ categories using e.g.:

*

*the Dirichlet distribution

*A softmax model.

As far as  I can tell, both use $k$ parameters to model the distribution over $k$ categories.
My questions:

*

*Does the "softmax distribution" have a name?

*Why isn't the softmax discussed more frequently in textbooks?

*If the Dirichlet distribution is a common distribution of choice for categorical outcomes, why do NNs use softmax layers instead of Dirichlet ones?

Context
Almost very textbook that I have encountered and that introduces common distributions (Binomial, Beta, Gaussian, Gamma, Poisson, Dirichlet) never mentions it (e.g. see this list of common distributions in Wikipedia).
Why isn't it presented more commonly in introductory books as type of common distribution? For almost any common distribution, Wikipedia (for example) covers their moments, marginal distributions, entropy, relationship to other known distributions, etc. Why not the same with the softmax distribution?
This is quite perplexing for me given the fact that softmax layers are actually extremely common in neural networks, and the converse is equally true, I have never encountered neural networks using "Dirichlet layers" for modeling categorical outcomes.
What explains this discrepancy? Is it a matter of tradition? Or is there a deeper connection and equivalency between them, and they just happen to go by different names?

A: The softmax function is a function. For a fixed input, you get a fixed output, just as for any other function. Someone might have invented a softmax distribution in some context, but that's not the meaning of "softmax function," as described in your post, or commonly used in neural networks.
The Dirichlet distribution is a distribution. Drawing from a Dirichlet distribution with some parameters will almost surely give a different result each time. The Dirichlet distribution is not a distribution over categories, it's a distribution over probability vectors.
The commonality that you've found between the softmax function and the Dirichlet distribution is that the results (function outputs, random draws) are always probability vecotrs: the vectors are non-negative, and sum to 1.
The normal distribution is a probability distribution which assigns positive probability to any real number. A linear function yields real number for any input. But you wouldn't conflate the two, because they're clearly different things in important ways. Likewise, the softmax function and Dirichlet distribution are distinct.

A: In fact, the distribution that is equivalent to the softmax function is the Boltzman distribution, which is in the list of common distributions you linked to. (The Wikipedia entry focusses on its original use in statistical mechanics and you would obviously ignore the $kT$ denominator for machine learning uses, though it's worth noting that softmax is not invariant under scale).
I can't answer why the Dirichlet PDF (as a function) is not as popular in NNs, though I suspect that this answer comparing softmax to normalisation is the reason. It suggests that softmax has the nice property of effectively cancelling out the log in cross entropy loss, leading to faster learning when the loss is larger.

redpajama_set_name: RedPajamaStackExchange


text:
Q: BufferedWriter works on Windows but not Mac So I am using this method to write to a file, it works totally fine on windows but when run on mac it creates the files but they are empty.
public static void writeLinesToTextFile(String path, String[] lines) {
File file = new File(r + path);
if (!file.exists()) {
    try {
        file.getParentFile().mkdirs();
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

    BufferedWriter bw;

    try {

        bw = new BufferedWriter(new FileWriter(file.getPath()));
        file.delete();
        file.createNewFile();

        for (int i = 0; i < lines.length; i++) {
            //System.out.println(lines[i]);
            bw.write(lines[i]);
            bw.write(System.getProperty("line.separator"));
        }
        bw.flush();
        bw.close();

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

}

I know the data is right because it prints correctly.
Thanks for any help, this has really been tripping me out.

A: Don't delete the file after creating a BufferedWriter. In Linux, every file has a unique file handle, so deleting and recreating a file with the same path creates 2 different file handles. I don't know what Windows does as I don't consider it a real OS, but from your post, it appears that it uses the same file handle.


text:
Q: Unity5 assignment params before update Now I have 3 C# scripts in my project
A is a class extends MonoBehaviour, I put it on a prefab.
B is not a mono class,it include some logic methods.
C is a test class, i will instantiate gameobjects in this class.
The question is: I want to assign B to A ,because A will call B.OnFixedTick() in FixedUpdate.
But if i code like this in class C (NOT CORRECT)
A.Instantiate(position,rotation);
A.GetComponent<B>().SetB(B);

The first Fixed-Tick in A will cause exception,because A.B is null.
Is the only way to code this in A.FixedUpdate()?
FixedUpdate(){if(B!=null)B.OnFixedTick(this);}

or is there any way to set B to A safety?
I'm sorry for my mistake but the first code block not correct.
There is the correct code below
GameObject obj = B.Instantiate(position,rotation);
obj.GetComponent<A>.SetB(B)

A: A.GetComponent() will only work if B is a component. By far the most common type of component is MonoBehaviour and you stated that B is not a MonoBehaviour.
If B is just an ordinary C# class the easiest way to assign it is in A.Awake
B = new B();
Or your could do the same thing in class C
A.B = new B();
There are of course many other ways of assigning a value to a property depending on your specific needs.


text:
Q: Flat linear set systems Let $X\neq \emptyset$ be a set. We say $E\subseteq {\cal P}(X)$ is a linear set system if for all $a\neq b\in X$ there is exactly one $e\in E$ with $\{a,b\}\subseteq e$.
Is there an infinite cardinal $\kappa$ and a linear set system $E\subseteq {\cal P}(\kappa)$ with $\kappa \notin E$ such that for all $x\in \kappa$ we have $|\{e\in E: x\in e\}| < \kappa$?
EDIT. Had to exclude cases like $E = \{\kappa\}$ which Noah Schweber made me aware of (thanks!).

A: Denote $\deg x =|\{e\in E\colon x\in e\}|$.
Take any $e\in E$; choose $x\notin e$. Then $e$ meets any $e'\ni x$ by at most one element, whence $|e|\leq \deg x<\kappa$.
Now, any $x$ is contained in $\deg x<\kappa$ sets of cardinality $<\kappa$ each; moreover (if this is needed), any of them except one has cardinality at most $\deg y<\kappa$ (for an arbitrary $y\neq x$).  All this implies that their union is of cardinality $<\kappa$; but their union is $\kappa$.


text:
Q: Same content-sections on multiple pages in wordpress - what alternative is best to do this? First of all, thanks to you who are trying to help me by reading my question :)
My question is this:
I have this theme I'm trying to complete. But there's one thing thats bugging me... If you look at this image:
This is the image I'm talking about

I want to include the section "Meriter" on multiple pages in wordpress. The admin should be able to change the images in this section together with the text under each image, but I only want the admin to be able to change this in one place...
What is the best way to do this? Custom post types? I really don't know, and it feels like I'm missing something here. How would you do this?
Much thanks for reading this and thanks for your help :)

A: I used Custom Post Types UI together with Advanced Custom Fields. Did the trick...


text:
Q: How to Custom Format Print .dat file column with awk I've got this file
#id|firstName|lastName|gender|birthday|creationDate|locationIP|browserUsed
933|Mahinda|Perera|male|1989-12-03|2010-03-17T13:32:10.447+0000|192.248.2.123|Firefox
1129|Carmen|Lepland|female|1984-02-18|2010-02-28T04:39:58.781+0000|81.25.252.111|Internet Explorer
4194|Hồ Chí|Do|male|1988-10-14|2010-03-17T22:46:17.657+0000|103.10.89.118|Internet Explorer
8333|Chen|Wang|female|1980-02-02|2010-03-15T10:21:43.365+0000|1.4.16.148|Internet Explorer

And i want to find dublicate browsers with count...So i need something like this
Firefox 1
Internet Explorer 3

I am using this code but the result is not what i want
Code:
awk -F '|' '!/^($|[:space:]*#)/{ print $8}' $3 | sort  | uniq -c | awk '{print $2 , $1}'

Result:
Firefox 1
Internet 3

What can i do so i can have whole "Internet Explorer" and the count right of the words ?

A: awk to the rescue!
$ awk -F'|' 'NR>1{c[$NF]++} END{for(k in c) print k, c[k]}' file

Explanation:
NR>1 skip the header
c[$NF]++ count distinct last fields in array c
END{.. at the end iterate the keys in array c and print key and
counts


text:
Q: How to stop Angular $rootElement.on('click') on ReactJS anchor tag? I've AngularJS and ReactJS both running on same page.
But when I click on any ReactJS  tag, Angular's $rootElement.on('click) getting triggered and page redirects.
I want to do few functionalities in ReactJS before page redirection.
I don't want to do changes in ReactJS, can anyone please suggest how I can handle this situation in Angular?

A: From your question what you can do is, not to add href attribute in  tag. Rather pass the routing location to a function:
Somethink

and in controller:
$scope.redirect = function(your_routing_path){
     // do what React gotta do and then redirect
     $location.path(your_routing_path);
 }

A: I've found a solution. In angular run we can simply write the below code block:
/**
 * We do not need to handle on-click handler if element belongs to reactJS.
 */
 $rootElement.off('click', '[data-reactid]');

So it won't handle any on-click scenario.


text:
Q: k2 articles in Joomla become unpublished if the author makes a minor change from the Frontend The "Authors" group doesn't have any publish rights. This is ok. So an Editor/Administrator does an initial approve of any article.
Problem comes if the Author decides to edit the already published article. When he hit "save" from the frontend, the item immediately becomes unpublished.(Because authors group doesn't have the right to publish items). So, this a huge problem at least for my case.
I want articles to remain published after the initial approval of the admin, even if the author makes adjustments. Any idea how to do something like this?
This logic comes as the default way of doing things in the Joomla Core.

A: You may want to consider switching from K2 to something like else like EasyBlog then... Or just don't use K2.  It seems like the default for K2 is to follow a workflow that conflicts with yours.
Otherwise you can modify K2 to suit your needs... I really don't recommend modifying extensions because then you can no longer make updates to them unless you plan to make the modifications every time you update (which is a pain).
You problem resides in the administrator/components/com_k2/models/item.php  The following lines are form version 2.6.1 line 785.
        if ($front)
        {
            if (!K2HelperPermissions::canPublishItem($row->catid) && $row->published)
            {
                $row->published = 0;
                $mainframe->enqueueMessage(JText::_('K2_YOU_DONT_HAVE_THE_PERMISSION_TO_PUBLISH_ITEMS'), 'notice');
            }
        }

If I understand you correctly you want something more like:
    if ($front)
    {
        $row->published = 1;
        if (!K2HelperPermissions::canPublishItem($row->catid) && $row->published && $isNew)
        {
            $row->published = 0;
            $mainframe->enqueueMessage(JText::_('K2_YOU_DONT_HAVE_THE_PERMISSION_TO_PUBLISH_ITEMS'), 'notice');
        }
    }

If I understand their model right by adding a check for $isNew to the if statement it will only apply published = 0 to new entries.  Which, if I understand you, are the only ones you want to affect.  This way if if the article already exists and it's published it will always stay published unless an admin changes it to unpublished.
I'm not sure if this will work the way I expect so let me know.

A: You should either allow Authors to edit any item or disable option for editing articles for authors.

A: Go to your joomla administration, go to k2 menu and in User Groups tabs create a group called editors and give it access to Publish item, then go back to Users tab and put those users that you want to make them editor in editors group.
Make sure your editor group users have access to Front-end item editing and Edit any item.
Your problem is because your editors have Edit any item access but they don't access to Publish item.

A: The permission that you want to set is actually in the k2 user group settings.  Look for Allow editing of already published items and set it to yes.
At least this is true for k2 v. 2.6.7, although I don't think any of the permission settings have changed since v.2.6.0 or earlier.


text:
Q: Bing Maps containsLocation function I have a site that uses both Bing and Google maps.  Each function has a Bing and Google version.  I am having trouble duplicating the google.maps.geometry.poly.containsLocation function in Bing maps.  Is there such a thing?
Basically I build a polygon and am looking to determine if a pushpin is located inside the polygon on the map.

A: Bing Maps V8 has a Spatial Math module which can do this calculation for you easily using the intersects function:
<!DOCTYPE html>

        <title></title>
        <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>

A: You can add your own method to do so using the extensibility of Bing Maps AJAX control. You can put that extension method on the Microsoft.Maps.Location class.
Microsoft.Maps.Location.prototype.IsInPolygon=function(polygon)
                {
                    var isInside = false;
                    var j = 0;
                    var x = this.longitude;
                    var y = this.latitude;
                    var paths = polygon.getLocations();

                    for (var i = 0; i < paths.length ; i++) {
                        j++;
                        if (j == paths.length) { j = 0; }
                        if (((paths[i].latitude < y) && (paths[j].latitude >= y)) || ((paths[j].latitude < y) && (paths[i].latitude >= y))) {
                            if (paths[i].longitude + (y - paths[i].latitude) / (paths[j].latitude - paths[i].latitude) * (paths[j].longitude - paths[i].longitude) < x) {
                                isInside = !isInside
                            }
                        }
                    }

                    return isInside;
                };

Here is a working example with Bing Maps V8:
<!DOCTYPE html>

        <title>Bing Maps - V8 - Polygon test</title>
        <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>


text:
Q: Is it good practice to delete no longer used objects and variables in JavaScript? In my code I use an object and variables inside a function. When in that function I no longer use the object and variables I delete it:
delete myObject;
delete myVar;

Is it good practice?
Does it give speed?
My JavaScript is server-side on smart.joyent.com.

A:
Is it good practice?

No. In fact it is disallowed in the new ECMAScript Fifth Edition 'strict mode':

When a delete operator occurs within strict mode code, a SyntaxError is thrown if its UnaryExpression is a direct reference to a variable, function argument, or function name (11.4.1).

If you really must, you can instead =null the variable to free up any object it referenced for garbage collection, but it's almost never going to result in any appreciable improvement in performance.
Deleting properties of long-lived objects to free now-unused referenced objects can be a good idea, especially in the case of breaking DOM cycles to prevent memory leakage in IE. Deleting local variables inside a short-lived function isn't sensible.

A: I'm not sure what engine your server is using, but client-side engines typically employ garbage collection, and I wouldn't be surprised if your server environment does as well. Unless you have an extremely particular situation, most attempts of manual cleanup are probably going to be on par with (or working against) the garbage collector.
In summary, I would bet you see absolutely no difference in performance. This is a good example of micro optimization.

A: And also instead of using delete method, It seems that Firefox 3 allows script to invoke garbage collector with:
Components.utils.forceGC

See https://developer.mozilla.org/En/Components.utils.forceGC
Other browsers may provide similar functions too. (except IE, i don't think it provides.)

A: It is not generally considered necessary but in extreme, high memory situations is may be something you should look into.  I do feel that its use prior to profiling and performance testing to be premature optimization.


text:
Q: LINQ count items created before or the same day past X days I am stuck at writing LINQ query to count items created before or the same day past X days.
I have the following table Items:
id   dateline (timestamp)  lastactivity  status
-----------------------------------------------------
1    1448395260            1448395260    done
2    1448308860            1448308999    in_progress
3    1448308860            1448395260    done
4    1448222460            1448395260    done
5    1448395260            1448395260    in_progress

I am trying to write LINQ query to get the number of created and existing in_progress items per day for past X days.
Item is counted if it's dateline <= DAY_END (23:59:59) AND (status != 'done' OR lastactivity >= DAY_START (00:00:00)).
If item's dateline is less then specific day and it was closed on that day is must be counted.
According to table items above, expected result should be something like this:
day           not_done_items_count
-----------------------------------
1448409599    5
1448323199    3
1448236799    1

(For the day value I took DAY_END timestamp.)
My current LINQ query looks like this:
var itemsPerDay = (from item in items
                   from i in Enumerable.Range(0, totalDays)
                   let dayStart = start.AddDays(i).ToUnixTimestamp()
                   let nextDay = start.AddDays(i).NextDay().ToUnixTimestamp()
                   where (item.dateline < nextDay
                       && (!item.status.Equals("done") || t.lastactivity >= dayStart)
                   select new { day = nextDay - 1 }
                  ).ToList();

var results = itemsPerDay.DistinctBy(t => t.day).Select(
    t => new OpenedItemsPerDay
    {
        day = t.day,
        count = itemsPerDay.Count(v => v.day == t.day)
    }).AsQueryable();

The code above executes too slowly and I am not sure if it is a correct way to do what I am trying to.
I also tried to play around with grouping but stucked: if the item was created earlier then DAY_X and it's status changed to done for example 2 days after I can only relate it to one group (day), I can't count it twice or more.

A: why not use groupby?  ( not infront of vs so pardon the syntax )
var d1 = datetime.now.adddays(-5).ToUnixTimestamp()
var d2= DateTime.Now.ToUnixTimestamp();

var grouppeditems = (for item in items
where item.lastactivity <= d2 && item.dateline >= d1 && (!item.status.Equals("done")
select item).GroupBy(gb=>gb.lastactivity)

foreach (var item in grouppeditems )
 Console.WriteLine ( item.Title + " " +  item.Count);

//might wanna group by something like this to group the same day
(d2-gb.lastactivity)/86400


text:
Q: How to create an API using Laravel 4 I have a question about how to create or build a simple API using laravel PHP framework.
I have searched a lot in the net, but dont get a proper answer.
Can anyone help me, Thanks in advance

A: One easy way is to just don't care about the views. For example:
In your UsersController.php
public function show($id) {
    $users = User::all();
    return $users;
}

Route.php
Route::get('/api/users', 'UsersController@show');

You'll then get a json object as response.
Then you can build it up with resources to get post, put etc to work. Read more in the laravel documentation: http://laravel.com/docs/routing
Laracasts has an entire series for building APIs: https://laracasts.com/series/incremental-api-development


text:
Q: DataSet не сохраняет изменения в БД Всем привет. Не могу понять в чем дело. Есть удаленная БД MSSQL SqlServer 2008r2, через DataSet  добаляю новую строку, заполняю ее данными, подтверждаю. А в оригинальной БД ничего не меняется. Почему так ? Помогите пожалуйста.
SqlConnection sc = new SqlConnection("Data Source=192.168.130.147;Initial Catalog=AutoLot1;Persist Security Info=True;User ID=Администратор;Password=blablabla");
        SqlDataAdapter sqda = new SqlDataAdapter("select * from [Inventory]; select * from [Customers];select * from [Orders]", sc);
        DataSet ds = new DataSet();
        sqda.Fill(ds);
        DataRow dr = ds.Tables[0].NewRow();
        dr[0] = 555; dr[1] = "VAZ"; dr[2] = "blue"; dr[3] = "Citten";

        ds.Tables[0].Rows.Add(dr);

        dr.AcceptChanges();
        ds.Tables[0].AcceptChanges();
        ds.AcceptChanges();
        Console.WriteLine(ds.Tables[0].Rows[ds.Tables[0].Rows.Count - 1][1]);
        Console.WriteLine(ds.HasChanges());

sqda.Update(ds); не помогает

A: Для сохранения данных используйте метод SqlDataAdapte.Update(ваш датасет). https://msdn.microsoft.com/ru-ru/library/at8a576f(v=vs.110).aspx

A: Здесь сложного на самом деле ничего нет. Вам нужно всего лишь написать параметризованный SQL запрос, который обновляет данные в нужной таблице. В приведенной мной ссылке это и демонстрируется.
Предположим у Вас есть таблица People с полями ID, Name. В данном случае, запрос может выглядеть так:
 // Ваш адаптер для таблицы People.
 SqlDataAdapter peopleAdapter = new SqlDataAdapter();

 // Команда Update.
 var command = new SqlCommand("UPDATE People SET ID = @ID, Name = @Name;", connection);

 // Описываем параметры команды.
 command.Parameters.Add("@ID", SqlDbType.Int, 0, "ID");
 command.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");

 // Выставляем команду адаптеру.
 peopleAdapter.UpdateCommand = command;

В принципе на этом все. Не забудь по аналогии реализовать команды, SELECT, INSERT, DELETE. (некоторые команды, такие как UPDATE, INSERT, DELETE можно реализовать автоматически)
// Обновляем данные в БД.
peopleAdapter.Update(dataSet);


text:
Q: How to make image upload not just from camera? I have three buttons in my application. One is for a camera, second is for a gallery and the third one is to upload. I changed my upload method from web server to googles firebase. Currently, I am only able to upload from my camera button. If I try to upload from gallery button it starts searching image in a temporary folder where images are saved when they are taken by a camera.
Taking image from gallery:
    private void ImageSelection()
{
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent, IMAGE_REQUEST);

}

On activity method:
        else if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null)
    {

        Uri FilePath = data.getData();
        try {

            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePath);
            mImageView.setImageBitmap(bitmap);
            mImageView.setVisibility(View.VISIBLE);
            mEditText.setVisibility(View.VISIBLE);
            staticSpinner.setVisibility(View.VISIBLE);

            if (TextUtils.isEmpty(mEditText.getText())){
                mEditText.setError("Privalomas laukas");
            }

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

Upload method:
private void UploadImage() {

    if(photoFile != null)
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        StorageReference ref = storageReference.child("images/"+ staticSpinner.getSelectedItem().toString().trim()+"_"+ mEditText.getText().toString());
        ref.putFile(Uri.fromFile(photoFile))
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
                        mImageView.setImageResource(0);
                        mImageView.setVisibility(View.GONE);
                        mEditText.setText("");
                        mEditText.setVisibility(View.GONE);
                        staticSpinner.setVisibility(View.GONE);
                        mCapture.setVisibility(View.VISIBLE);
                        mChoose.setVisibility(View.VISIBLE);
                        //mUpload.setVisibility(View.GONE);
                        photoFile = new File(String.valueOf(photoFile));
                        photoFile.delete();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
                        mImageView.setImageResource(0);
                        mImageView.setVisibility(View.GONE);
                        mEditText.setText("");
                        mEditText.setVisibility(View.GONE);
                        staticSpinner.setVisibility(View.GONE);
                        mCapture.setVisibility(View.VISIBLE);
                        mChoose.setVisibility(View.VISIBLE);
                        //mUpload.setVisibility(View.GONE);
                        photoFile = new File(String.valueOf(photoFile));
                        photoFile.delete();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
                                .getTotalByteCount());
                        progressDialog.setMessage("Uploaded "+(int)progress+"%");
                    }
                });
    }
}

A: Added an else if statement. Stupid me


text:
Q: Is it possible to do WebRTC within Local Network from Pc to Pc with no use of Internet Access? Hi we are working on something today with webRTC, and our objective is only peer to peer access with not much use of Internet Access. We had this idea that the API will also be needing an Internet Access, yet our main agenda with the voice call it will not use much of Internet Access. We all know that data consumption of VoiceData would really be an issue if the Internet Speed would not be sufficient. Thats why we had this idea of WebRTC of peer to peer access within LAN Network only.
But sad to say there are no documentation that fits to our objective. this type of concept is very easy with VB but we were hoping to to this on a Browser.
Is there anyone who can give us a highlight on this?
Thanks

A: Yes, you can use WebRTC inside your local network without an access to Internet. You don't need to use any special tricks to achieve that.

A: Yes, you can use WebRTC on LAN. But you will require a signaling server that is inside your LAN network so that you can exchange the WebRTC SDP offer, answer and ICE candidates between your browser clients.

A: Other answers have noted that you can run a signaling server within the LAN.  This is true, however, this all depends on the fact that both machines can see each other, which is not always possible in all LAN setups.
It is also possible to use a signaling server that is on the Internet.  If in fact the browsers are able to talk to each other then they will and the only data that will hit the Internet is signaling traffic that is used to set things up.  All the media (audio, video) should go over the LAN.  In most cases, the signaling data is tiny, so if your goal is to minimize data usage, not eliminate it entirely, this should be good enough.
If you want to make sure that you aren't sending audio out over the Internet, first check that the two machines are able to see each other (ping should be able to tell you this).  To be really sure, you can see where the packets are going with a tool like Wireshark.


text:
Q: Surfaces formed by infinitesmal equilateral triangles at common vertices Say we have equilateral triangles coming together at a common vertex with each angle is $ 2 \pi/n= 2 \pi/6$.  As the hexagon side tends to zero we have a flat plane defined with hexagonally packed tiling and the Gauss curvature of the plane
$$K_6=0$$
Now in a similar manner $K_7, K_8$ repeated 3d tiling would form surfaces of negative curvature as $ \text{side of triangle}\to 0$, a defined polyhedral solid angle forms.
How to parameterize the surface in order to visualize it?
Thanks for all pointers, how to use GB theorem and so on..


text:
Q: Chrome extension - where to put more code I'm refactoring js plugin for chrome.
Its mostly based on jQuery with q and handlebars libraries.
For now there is 30k lines of code (2k in background page).
Is it better to include more logic in background or in content-scripts?
If for example I move most of functions to background page, and call them through chrome.runtime.sendMessage with callbacks.
Currently there are about 5k messages send between bg and content-scripts in one plugin run and it takes about 2 min.
Will moving help performance or will it crash it?


text:
Q: Why does this float overflow I understand the floating point numbers only have a limited precision. But I don't understand why a 64bit float (which I assume these are) will overflow with these values:
ipdb> (-1e+10 - 0.01)
-10000000000.01  # 0.01 still visible
ipdb> (-1e+20 - 0.01)
-1e+20  # 0.01 is gone, I assume because of floating point precision

This might be relevant:
ipdb> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

Note that the actual problem I want to solve is normalizing these values to be between 0 and 1 [-1.3229999632394e+32, 15000.0, -11.432000160217285, -11.321000099182129]

A: It's not often necessary to have this kind of precision, but there are packages that do it for you, for example Bigfloat
from bigfloat import *

print (-1e+20 - 0.01) == -1e20

with precision(64*2):
    a = BigFloat.exact(-1e+20)
    b = BigFloat.exact(0.01)
    print a == b

Will output:
True
False

Scaling also works
from bigfloat import precision, BigFloat
listy = [-1.3229999632394e+32, 15000.0, -11.432000160217285, -11.321000099182129]
m = min(listy) #do this before import, as BigFloat
M = max(listy)

with precision(128):
    scale = lambda x : (x-BigFloat(m)) / (BigFloat(M)-BigFloat(m))
    print [ scale(BigFloat(i)) for i in listy ]


text:
Q: Send Email For a selected file I am trying to send an email for a selected file in power automate, I would like to see the flow only on subfolders which I have set the flow but not on all Subfolders.
Ex: Parent Folder
SubFolder 1
SubFolder 2
SubFolder 3 - I want to see the flow only on this subfolder 3 and its subfolders, but not for complete library. And that is for only selected file.

A: Check out Reza Dorani's video, Run Power Automate flow from SharePoint - For a selected item trigger.  The entire video is gold, but at minute mark 18:00 he details how to conditionally show/hide the run flow button based on another column's value.  I hope this is enough to get you started.  Good luck!


text:
Q: .htaccess produces 500 Internal Server Error The content of .htaccess is:
php_value upload_max_filesize 64M

Works on localhost, screws up every hosting server I upload it to.
The error.log says: Invalid command 'php_value', perhaps misspelled or defined by a module not included in the server configuration
Is there another way to change the upload_max_filesize?

A: For other readers with the same problem and access to the server, this could also be caused by a misconfiguration of PHP as a module of apache. You can fix it reinstalling the module (or configuring the route to libphp.so by yourself in php.ini).
Have in mind that purge will remove the configuration of the packages which usually is nothing to worry, but you are warned just in case.
sudo apt-get purge libapache2-mod-php libapache2-mod-php7.2
sudo apt-get install libapache2-mod-php

A: The problem was the hosting provider, they only allow changing this via php.ini

A: It seems like the php module is not loaded. Make sure, it is installed with
sudo apt-get install libapache2-mod-php

and check if it is enabled in apache with
ll /etc/apache2/mods-enabled/*php*

if it is installed but not enabled, enable it (depending on your php-version) e.g. for PHP 8.0 with
sudo a2enmod php8.0.load

and restart apache
sudo apache2ctl graceful

A: I too was receiving a 500 internal server error. My error log showed:
Invalid command 'php_value', perhaps misspelled or defined by a module not included in the server configuration
I tried updating upload_max_filesize as suggested but it didn't work for me. The last line of my .htaccess file had:
php_value max_execution_time 120

I removed that line and the site resolved perfectly.

A: If php_value is not recognized as a valid command, it may be because PHP is not installed as an Apache module. Create a php file with the following contents:
<?php phpinfo();
Run the file to show your PHP configuration.  Search the page (Ctr+F) for "mod_php".  If you don't find it anywhere, this explains your problem.
If you have access to php.ini, you may be able to fix your problem by editing that file instead.  At the phpinfo page, look at the value under Loaded Configuration File for the location of the file to edit. On Linux, it will be something such as /usr/local/lib/php.ini
Open the ini file (it's just a text file) and look for the setting you want to change.  If it's not present, just add a line and set it as desired: upload_max_filesize=64M
Save the file and restart the Apache server.

A: If you don't want to remove the php_flag command in .htaccess but want to avoid the error, wrap the command as follows:
<IfModule mod_php5.c>
    php_flag display_errors 0
    php_flag display_startup_errors 0
</IfModule>

If you're using PHP7, use <IfModule mod_php7.c>

A: *

*Create .user.ini file

*Add the line upload_max_filesize="5M"


text:
Q: Mongoid authorize config does not work Using mongoid on rails
gem 'rails', '~> 5.1.4'
gem 'mongoid', '~> 6.1.0'

Mongodb version: 3.4.10

My mongoid.yml
development:
  clients:
    default:
      database: xxxx_development
      hosts:
        - xxx.xx.147.208:2200
      user: 'root'
      password: "xxxxxxxx"
      auth_source: admin

The user root is with the root role. The user/password can work with MongoBooster and mongo cli, I mean can db.xxx.find({}).
But in my rails app, it just throws
MONGODB | Topology type 'unknown' initializing.
MONGODB | Server xxx.xx.147.208:2200 initializing.
MONGODB | Topology type 'unknown' changed to type 'single'.
MONGODB | Server description for xxx.xx.147.208:2200 changed from 'unknown' to 'standalone'.
MONGODB | There was a change in the members of the 'single' topology.
MONGODB | xxx.xx.147.208:2200 | xxxx_development.count | STARTED | {"count"=>"news", "query"=>{}}
MONGODB | 116.62.147.208:2200 | xxxx_development.count | FAILED | not authorized on xxxx_development to execute command { count: "news", query: {} } (13) | 0.153356s
Completed 500 Internal Server Error in 364ms

I have tried many different configs, but can't make mongoid authorize work.
Any help will be highly appreciated.

A: MONGODB | Topology type 'unknown' initializing.
MONGODB | Server xxx.xx.147.208:2200 initializing.
MONGODB | Topology type 'unknown' changed to type 'single'.
MONGODB | Server description for xxx.xx.147.208:2200 changed from 'unknown' to 'standalone'.
MONGODB | There was a change in the members of the 'single' topology.

These are errors I got, as well, on my development environment, but not on any other environments.
My config:

*

*Rails 4.2.10

*Mongoid 5.2.1

*Mongodb 3.4.4

*MacOS Sierra 10.12.6

And this error was not caused by mongoid authorize work, in my case, but by random query..
I'm still looking for what really caused this error.
Also, here is my crash report
12:19:03 vie2.1   |  -- Control frame information -----------------------------------------------
12:19:03 vie2.1   |  c:0005 p:---- s:0014 e:000013 CFUNC  :sleep
12:19:03 vie2.1   |  c:0004 p:0010 s:0010 e:000009 BLOCK  /Users/7in4/.rvm/gems/ruby-2.3.1/gems/mongo-2.4.3/lib/mongo/cluster/cursor_reaper.rb:168 [FINISH]
12:19:03 vie2.1   |  c:0003 p:---- s:0008 e:000007 CFUNC  :loop
12:19:03 vie2.1   |  c:0002 p:0009 s:0005 e:000004 BLOCK  /Users/7in4/.rvm/gems/ruby-2.3.1/gems/mongo-2.4.3/lib/mongo/cluster/cursor_reaper.rb:167 [FINISH]
12:19:03 vie2.1   |  c:0001 p:---- s:0002 e:000001 (none) [FINISH]
12:19:03 vie2.1   |  -- Ruby level backtrace information ----------------------------------------
12:19:03 vie2.1   |  /Users/7in4/.rvm/gems/ruby-2.3.1/gems/mongo-2.4.3/lib/mongo/cluster/cursor_reaper.rb:167:in `block in start!'
12:19:03 vie2.1   |  /Users/7in4/.rvm/gems/ruby-2.3.1/gems/mongo-2.4.3/lib/mongo/cluster/cursor_reaper.rb:167:in `loop'
12:19:03 vie2.1   |  /Users/7in4/.rvm/gems/ruby-2.3.1/gems/mongo-2.4.3/lib/mongo/cluster/cursor_reaper.rb:168:in `block (2 levels) in start!'
12:19:03 vie2.1   |  /Users/7in4/.rvm/gems/ruby-2.3.1/gems/mongo-2.4.3/lib/mongo/cluster/cursor_reaper.rb:168:in `sleep'


text:
Q: Piping output of process to file asynchronously in windows I am trying to run a program using "start" and I want to have the output piped to a txt file, for example, I want to have the output of a simple http python server to be logged to a text file:
START cmd /c python -m SimpleHTTPServer 8000^>engineLog.txt

The above will print it to the log file but the problem with that is, it only prints it when the process finishes. Are there any way that I can store it to the log as it is running? Also is it possible to have it log in the txt file as well as having it print out in the console?

A: Give it a try:
START /b "Your title" "cmd /c python -m SimpleHTTPServer 8000 > engineLog.log | type engineLog.log"

Alternatively, you can get tee port for Windows.


text:
Q: Tab layout programmatically in android I need to use tab layout in which i try to access two activity classes in 2 tabs programmatically. I tried but getting error in run time. refer my code below,test activity
public class TestActivity extends TabActivity {
    protected static final View View = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Resources ressources = getResources();
        TabHost tabHost = getTabHost();
        // Android tab
                Intent intentAndroid = new Intent().setClass(this, AndroidActivity.class);
                TabSpec tabSpecAndroid = tabHost
                  .newTabSpec("Android")

                  .setContent(intentAndroid);

                tabHost.addTab(tabSpecAndroid);
        setContentView(tabHost);

    }
}

Android activity(activity which need to display in tab order in the name as andriod)
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidActivity extends Activity
{
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView textview = new TextView(this);
        textview.setText("This is Android tab");
        setContentView(textview);
    }
}

I don't know whats wrong in it. please give simple sample for TabLayout programmatically(without using any xml files).

A:
Create a parent class to display all the other classes in tab order

import android.app.TabActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TabHost.TabSpec;
import android.content.Intent;
import android.content.res.Resources;
import android.widget.TabHost;

public class TestActivity extends TabActivity {
protected static final View View = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Resources ressources = getResources();
    TabHost tabHost = getTabHost();
    // Android tab
            Intent intentAndroid = new Intent().setClass(this, AndroidActivity.class);
            TabSpec tabSpecAndroid = tabHost
              .newTabSpec("Android")
              //add .png type images in res folder hdpi,ldpi,mdpi,xhdpi
tabSpecAndroid.setIndicator("",getResources().getDrawable(R.drawable.arrival));//arrival is the name of png image, delete this line if u hav no images
              .setContent(intentAndroid);
            tabSpecAndroid.setIndicator("Android");
            tabHost.addTab(tabSpecAndroid);

    //Welcome tab
            Intent intentBus = new Intent().setClass(this, Welcome.class);
            TabSpec tabSpecBus = tabHost
                    .newTabSpec("Welcome")
                    .setContent(intentBus);
            tabSpecBus.setIndicator("Welcome");
            tabHost.addTab(tabSpecBus);
}
}

create first child class in which we want to display in tab order

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidActivity extends Activity
{
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView textview = new TextView(this);
    textview.setText("This is Android tab");
    setContentView(textview);
}
}

create a second child class in which we want to display in tab order

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Welcome extends Activity
{
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView textview = new TextView(this);
    textview.setText("This is Welcome tab");
    setContentView(textview);
}
}

in android manifest.cml add all child classes

<activity android:name=".AndroidActivity"     android:theme="@android:style/Theme.Black.NoTitleBar"></activity>
    <activity android:name=".Welcome" android:theme="@android:style/Theme.Black.NoTitleBar"></activity>
</application>

now run the code, thats it

A: A TabActivity probably already includes the content. Try not calling setContentView() and see if that solves your problem.


text:
Q: Delete Entries in File if the Same Entry Exists in a Master File I have a JSON master config file whose value may be overwritten by a specific account's config file (also in JSON). The Master file has this structure:
{
    "section1Configs": {
        "setting01": true,
        "setting02": true,
        "setting03": false
    },
    section2Configs: {
        "setting01": true,
        "setting02": true,
        "setting03": false
    },
    section3Configs: {
        "setting01": true,
        "setting02": true,
        "setting03": false
    },
    section4Configs: {
        "setting01": true,
        "setting02": true,
        "setting03": false
    }
}

The config file for a specific account may look like this:
{
    "section1Configs": {
        "setting01": true,
        "setting02": true,
        "setting03": true
    },
    section2Configs: {
        "setting01": false,
        "setting02": true,
        "setting03": false
    },
    section3Configs: {
        "setting01": true,
        "setting02": false,
        "setting03": false
    },
    section4Configs: {
        "setting01": true,
        "setting02": true,
        "setting03": false
    }
}

Note that they are identical except certain values (section01Config.setting03, section02Config.setting01, and section03Config.setting02) are different. Note also that the entire section4Configs block is the same in both files.
The ones that are the same are not needed since the application loads both and overwrites the Master file with the ones that are different in the account config.
What I would like to do is have a script that iterates through a directory of such account files and deletes the entry in each file that are the same key and value as the Master file. From this example I would end up with a file like this:
{
    section1Configs: {
        setting03: true
    },
    section2Configs: {
        setting01: false
    },
    section3Configs: {
        setting02: false
    }
}

There are over 200 account config files and doing this manually will take a lifetime. Any help is greatly appreciated!
------ EDIT -------
I tried to keep the question simple but I think a missing detail will have an impact on the answer.
The account and config JSON file consist of sections and their corresponding settings. This means that the JSON is one level deeper than what's mentioned above:
{
    "section1Configs": {
        "level1Settings": {
            "section01Lev01_01": true,
            "section01Lev01_012": true,
            "section01Lev01_02": true
        }
    }
}

Thanks!

A: May be better to use tools specialized for json like jq or jshon?
But if you'd like it can be done with paste and sed
paste config master | sed '/[{}]/! {/\(.\+\)\t\1/d;};s/\t.*//'

or awk
awk '{getline a < "master"} /[{}]/ || $0 != a' config

for each line in config-file gets corresponding(by number) row from master-file into variable a and if line consist {or} or not the same with ones from master-file print it.
Result:
{
    "section1Configs": {
        "setting03": true
    },
    section2Configs: {
        "setting01": false,
    },
    section3Configs: {
        "setting02": false,
    },
    section4Configs: {
    }
}

A: So I copied your bottom thing into two files.
File 1:
{
    "section1Configs": {
        "level1Settings": {
            "section01Lev01_01": true,
            "section01Lev01_012": true,
            "section01Lev01_02": true
        }
    }
}

And File 2...
{
    "section1Configs": {
        "level1Settings": {
            "section01Lev01_01": true,
            "section01Lev01_012": false,
            "section01Lev01_02": true
        }
    }
}

They only differ on the Level01_012 line.
Then I did:
grep -Ev '[{}]|^$' file1 | grep -Fxvf- file2

{
    "section1Configs": {
        "level1Settings": {
            "section01Lev01_012": false,
        }
    }
}

That command is broken down as follows:

*

*grep -Ev '[{}]|^$' file1

*

*Here we ask grep to please print every line in file1 which does not match either a { character or a } character, but it must match at least one character.

*Its output looks like:

        "section01Lev01_01": true,
        "section01Lev01_012": true,
        "section01Lev01_02": true

*grep -Fxvf- file2

*

*That is read by this second grep which interprets its - stdin input pattern -file as a -Fixed-string pattern -x entire-line match which it should -v not print to output. And so this second grep prints every line in file2 which doesn't exactly match the true/false lines in file1.

Now if your grep does not understand - as stdin we have a few options:
grep -Ev '[{}]|^$' file1 | grep -Fxvf /dev/fd/0 file2

...will work on most systems. A similar option is to use /dev/stdin, which is also pretty likely to work, if a little less so.
There is also a shell-specific implementation know as process-substitution which works in just about exactly the same way...
grep -Fxvf <(grep -Ev '[{}]|^$' file1) file2

...which may or may not work for you depending on your shell.
Another possibility is...
grep -Fxv "$(grep -Ev '[{}]|^$' file1)" file2

...which may or may not work for you depending on how large the output of the command-subbed grep is.
Try a few and probably you'll find one that works for you.

A: As was pointed out elsewhere on this page, a robust and efficient way to solve the problem is to use a JSON-aware tool such as jq.  The following provides a solution to the original problem; it can easily be adapted to solve variants.
(1) Put the following in a file, say minusConfig.jq:
def minus(o1;o2):
  o1 | with_entries( select(o2[.key] != .value) );

def minusConfig(o1;o2):
  reduce (o1|keys)[] as $key ({};
    minus( o1[$key] ; o2[$key]) as $v
    | if $v == {} then . else . + {($key): $v} end );

minusConfig($user; $master)

(2) Assuming the master and user config files are master.json and user.json respectively,
$ jq -n --arg master master.json --arg user user.json -f minusConfig.jq

produces:
{
  "section1Configs": {
    "setting03": true
  },
  "section2Configs": {
    "setting01": false
  },
  "section3Configs": {
    "setting02": false
  }
}


text:
Q: how to hide html table column based on td content populated via ng-iterate I am populating a table like the following using angularjs:

      col1
      col2
      col3
      col4
      col5

      {{row.col1}}
      {{row.col2}}
      {{row.col3}}
      {{row.col4}}
      {{row.col5}}

because the table has a lot of columns which often contain no values (NULL), I would like to hide those columns.
note: all rows would have that column value NULL.
Example (row.col1=NULL, row.col3=NULL):

      col2
      col4
      col5

      {{row.col2}}
      {{row.col4}}
      {{row.col5}}

so far I was not able to find/figure out a solution for this.
I'm starting to believe that this is not possible to do...

A: You could a global array that has a boolean variable for each column you want, and set that boolean accordingly.
 $scope.showColumn = [false, false, false, false];

Use a function to display your column value that way you get to set your booleans in case you encounter a non-null value.
  $scope.setVisible = function(colNum, colVal){
    if(colVal)
      $scope.showColumn[ colNum ] =true;
    return colVal;
  };

You'll then have to check the boolean for display and use the function for your column value:

     {{ setVisible(0, friend.name ) }}
     ...

See  Working plunk (try giving a 'none' property to any friend)

A: This is very easy to do in an ng-repeat. Just use ng-if.

      col2
      col4
      col5

    // ADD NG-IF TO YOUR REPEATER

      {{row.col2}}
      {{row.col4}}
      {{row.col5}}


text:
Q: How to show a survey form to users according to their role in wordpress? I have created 3 form with the help of contact form7 and I'm using contact form DB to store the details filled by the user to the database. How would it be possible to show that forms according to the user roles and user can fill that form only once! If a particular user already filled that form he won't see that form ever. And while the user is filling the form all the features on the screen will be disabled.

A: I would propose to do this with two conditions
First:
If user is ....
Source: (https://codex.wordpress.org/Function_Reference/get_userdata)
Second: I would add a hidden field with a default value or just a simple counter.
If counter is ...


text:
Q: Do I need to use invoke in backgroundworker progresschanged event? using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;

namespace DownloadFiles
{
    public partial class Form1 : Form
    {
        Stopwatch sw = new Stopwatch();
        Stopwatch stopwatch = new Stopwatch();
        string filesdirectory = "Downloaded_Files";
        string mainurl = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/";
        List<string> parsedlinks = new List<string>();
        string path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);

        List<string> results = new List<string>();
        //StreamWriter w = new StreamWriter(@"e:\monitordetector.txt");

        public Form1()
        {
            InitializeComponent();

            //DetectScreenName();

            label3.Text = "";
            label4.Text = "";
            label5.Text = "";
            label7.Text = "";
            button2.Enabled = false;
            button3.Enabled = false;
            filesdirectory = Path.Combine(path_exe, filesdirectory);
            if (!Directory.Exists(filesdirectory))
            {
                Directory.CreateDirectory(filesdirectory);
            }
            else
            {
                if (IsDirectoryEmpty(filesdirectory) == false)
                {
                    button3.Enabled = true;
                }
            }
        }

        public bool IsDirectoryEmpty(string path)
        {
            return !Directory.EnumerateFileSystemEntries(path).Any();
        }

        private string downloadhtml(string url)
        {
            backgroundWorker1.ReportProgress(0, "Downloading Main Url");
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Proxy = null;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string html = sr.ReadToEnd();
            sr.Close();
            response.Close();
            StreamWriter w = new StreamWriter(path_exe + "\\page.html");
            w.Write(html);
            w.Close();
            return html;
        }

        int Counter = 0;
        int percentage = 0;
        int total = 0;
        int countfiletodownload = 0;
        bool processStatus = false;
        private void Parseanddownloadfiles()
        {
            downloadhtml(mainurl);
            if (bgw.CancellationPending == false)
            {
                backgroundWorker1.ReportProgress(0, "Parsing Links");
                HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc = hw.Load(path_exe + "\\page.html");
                foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
                {
                    string hrefValue = link.GetAttributeValue("href", string.Empty);
                    if (hrefValue.Contains("US"))
                    {
                        string url = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/" + hrefValue;
                        parsedlinks.Add(url);
                        if (bgw.CancellationPending == true)
                            return;
                    }
                }
                countfiletodownload = parsedlinks.Count;
                total = parsedlinks.Count;
                backgroundWorker1.ReportProgress(0, "Downloading Files");
                processStatus = true;
                for (int i = 0; i < parsedlinks.Count && bgw.CancellationPending == false; i++)
                {
                    try
                    {
                        using (WebClient client = new WebClient())
                        {
                            sw.Start();
                            Uri uri = new Uri(parsedlinks[i]);
                            string filename = parsedlinks[i].Substring(71);
                            //client.DownloadFile(parsedlinks[i], filesdirectory + "\\" + filename);
                            client.DownloadFileAsync(uri, filesdirectory + "\\" + filename);
                            Counter += 1;
                            percentage = Counter * 100 / total;
                            string filenametoreport = filename.Substring(1);
                            countfiletodownload--;
                            backgroundWorker1.ReportProgress(percentage, filenametoreport);//countfiletodownload, filenametoreport);
                        }
                    }
                    catch (Exception err)
                    {
                        string error = err.ToString();
                    }
                }
            }
        }

        /*void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            // Calculate download speed and output it to labelSpeed.
            if (label12.InvokeRequired)
            {
                label12.Invoke(new MethodInvoker(delegate
                {
                    label12.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
                }));
            }

            // Update the progressbar percentage only when the value is not the same.
            if (progressBar1.InvokeRequired)
            {
                progressBar1.Invoke(new MethodInvoker(delegate
                {
                    progressBar1.Value = e.ProgressPercentage;
                }));
            }

            // Show the percentage on our label.
            if (label13.InvokeRequired)
            {
                label13.Invoke(new MethodInvoker(delegate
                {
                    label13.Text = e.ProgressPercentage.ToString() + "%";
                }));
            }
            // Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading
            if (label14.InvokeRequired)
            {
                label14.Invoke(new MethodInvoker(delegate
                {
                    label14.Text = string.Format("{0} MB's / {1} MB's",
                        (e.BytesReceived / 1024d / 1024d).ToString("0.00"),
                        (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
                }));
            }
        }*/

        /*void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            // Reset the stopwatch.
            sw.Reset();

            if (e.Cancelled == true)
            {
                MessageBox.Show("Download has been canceled.");
            }
            else
            {
                //MessageBox.Show("Download completed!");
            }
        }*/

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        BackgroundWorker bgw;
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            bgw = (BackgroundWorker)sender;
            if (bgw.CancellationPending == true)
            {
                return;
            }
            else
            {
                Parseanddownloadfiles();
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.UserState.ToString() == "Downloading Main Url")
            {
                label3.Text = e.UserState.ToString();
            }
            if (e.UserState.ToString() == "Parsing Links")
            {
                label3.Text = e.UserState.ToString();
            }
            if (e.UserState.ToString() == "Downloading Files")
            {
                label7.Text = countfiletodownload.ToString();//parsedlinks.Count.ToString();
                label3.Text = e.UserState.ToString();
            }
            if (processStatus == true)
            {
                if (e.UserState.ToString() != "Downloading Files")
                {
                    label4.Text = e.UserState.ToString();
                    label7.Text = countfiletodownload.ToString();
                    progressBar1.Value = e.ProgressPercentage;
                    /*using (var bitmap = new Bitmap(this.Width, this.Height))
                    {
                        this.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
                        bitmap.Save(@"e:\screens\ss.gif" + countscreenshots, System.Drawing.Imaging.ImageFormat.Gif);
                        countscreenshots += 1;
                    }*/
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                string fff = null;
            }
            label3.Text = "Operation Cancelled";
            button1.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            label3.Text = "Cancelling Operation";
            backgroundWorker1.CancelAsync();
            button2.Enabled = false;
            timer1.Stop();
            stopwatch.Stop();
            stopwatch.Reset();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label3.Text = "";
            label4.Text = "";
            label7.Text = "";
            backgroundWorker1.RunWorkerAsync();
            timer1.Start();
            stopwatch.Start();
            button1.Enabled = false;
            button2.Enabled = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Process.Start(filesdirectory);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label5.Text = string.Format("{0:hh\\:mm\\:ss}", stopwatch.Elapsed);
        }
    }
}

for some reason the code inside the event make the whole application to not to be async. If I comment the code not to use it then it's async working fine.
I also want to use the client_DownloadProgressChanged that now is not in use to show and display the downloading infos.
Like speed time using progressBar info per current file download and info for overall progress download.

A: No*, you do not need to Invoke in a BackgroundWorker's ProgressChanged event. DoWork is run on a background thread but the thread that executes the code inside ProgressChanged (and the other event handlers on a backgroundworker) is done by the thread that created the backgroundworker, which should be the same as the thread that created the other ui controls and hence no Invokation required
*Having said this, pay close attention to the part where I said that BGW will run the ProgressChanged event using the thread that created the BGW. In most cases this will be the UI thread.. if you've used a thread other than the UI thread to create the BGW then YES, invokation would be required. Create the BGW on the UI thread along with all your other controls, if you want a simple life. For the rest of my advice I'll assume this is what you've done.
I wasn't able to understand exactly your problem, but remember that it's the UI thread that runs the event handler. If you send that thread off doing some long task or blocking operation as part of your efforts to update the labels in the UI then it will make the application seem hung. You must let the UI thread complete the code in the event handler as soon as possible. If it will need to access data that is from a long or blocking operation, either have the DoWork calculate the data before it raises its progress, or use another method to avoid blocking the UI thread, like async task pattern
Note that Invoke and blocking the ui are completely different things. Windows controls may only be accessed by the thread they were created with. If another thread wants to access the control, it should use Invoke to cause the ui thread to do the work instead. This is a very different thing to the notion of not jamming up your ui by using the UI thread to read 50 gigabytes from a slow server and not using something that lets it quickly get back to its job of processing window messages and keeping the app responsive


text:
Q: Replacing a keypad on DYMO LetraTag I'm rebuilding my label printer to become an Internet service using an ESP8266. It's a fun project, never mind the usefulness. The keypad will be removed and instead my MCU emulates keypresses.
The keypad has:

*

*8 pins that always have 3.2V (red cables on the picture)

*7 pins that have 2.6V (black cables, faint LEDs)

When a key is pressed it connects one of the 8 pins with one or more of the 7 pins. I can verify this by connecting them (see picture for writing "ABC").

*

*"A" is red cable number 2 connected to black cable number 3.

*"B" is red cable number 3 connected to black cable number 3.

.... and so on. Plenty of combinations.
I could achieve my goal by replacing each of the buttons with a transistor. That would require 50 pins (because there are 50 buttons). Simple stupid, I can do that with a bunch of 545's. However, I'd like to see if it's possible to find a more clever solution.
How does this device know what pin I'm drawing current from? I can make six letters by adding voltage to each of the black pins. But I need the combination of red+black to get all combinations.
Would it work to somehow simulate drawing current from each red pin individually and at the same time add voltage to the black pins? Then I only need 15 pins, way fewer components.

A: It is a keyboard matrix, and it could be active scanned matrix.
To connect any "row" wire to any "column" wire, you could just use two 8-to-1 analog multiplexers to connect any two wires together.


text:
Q: Can't customize admin template I want to customize the admin template. This is what I did:

*

*Created a folder for the new template C:/xampp/htdocs/myblog/templates/admin

*Copied the standard template from C:\Python27\Lib\site packages\django\contrib\admin\templates\admin\base_site.html

*Edited the copied template

*Configured django to use the new template (added to new directory to TEMPLATE_DIRS in settings.py)
TEMPLATE_DIRS = (
   'C:/xampp/htdocs/myblog/templates'
)

This is all there is to do according to the Django documentation
I also tried restarting the server, which didn't work.


text:
Q: Why does the sheaf cohomology of the constant sheaf on $\mathbb{R}$ vanish? Sorry if this is a very basic fact, but for some reason I am not able to solve it.
I am trying to prove for $X =\mathbb{R}$ that the sheaf cohomology groups $(i>0)$ of the constant sheaf $\mathbb{Z}_{X}$ vanish.
From what I gather online it has something to do with $\mathbb{R}$ being simply connected. I know it is even contractible and that these cohomology groups are isomorphic for homotopic spaces, but I am looking for an argument not using this homotopy argument.
I think I understand this sheaf, namely that $\mathbb{Z}_{X}(U) = \mathbb{Z}^{I}$ where I has cardinality equal to the number of connected components of $U$ and the restriction maps are just projections and diagonal maps. But somehow I can't seem to find a flasque/injective resolution or a sort of dimension shift argument. I can use excision and mayer-vietoris but I don't know if this helps.
Thanks in advance for any help!

A: Call a sheaf on $\mathbb{R}$ interval-flasque if for every inclusion of open intervals $(a, b) \subseteq (a', b')$, the restriction map $\Gamma((a', b'), \mathscr{F}) \to \Gamma((a, b), \mathscr{F})$ is surjective.  (Here, we allow $a = -\infty$ and/or $b = \infty$ and similarly for $a', b'$.)  We then claim that any interval-flasque sheaf of abelian groups on $\mathbb{R}$ is acyclic in $\mathfrak{Ab}(\mathbb{R})$.  Since in particular, the constant sheaf $\mathbb{Z}$ on $\mathbb{R}$ is clearly interval-flasque, that will imply the desired result.
The proof proceeds similarly to the proof for generally flasque sheaves.  Here I'll follow the outline of the facts that the proof from Hartshorne's Algebraic Geometry uses:

*

*If $0 \to \mathscr{F}' \to \mathscr{F} \to \mathscr{F}'' \to 0$ is a short exact sequence, and $\mathscr{F}'$ is interval-flasque, then $0 \to \Gamma(U, \mathscr{F}') \to \Gamma(U, \mathscr{F}) \to \Gamma(U, \mathscr{F}'') \to 0$ is exact for every open interval $U$.  Here, in using Zorn's Lemma to show there exists a maximal preimage of $x \in \Gamma(U, \mathscr{F}'')$, you will need to use the fact that the union of a chain of intervals is again an interval.  Then, in showing that a preimage on a strict subinterval can be extended (and therefore, a maximal preimage must be a section over the full larger interval), you will need to use the fact that a nonempty intersection of two intervals is an interval, and likewise for the union of two overlapping intervals.

*If $0 \to \mathscr{F}' \to \mathscr{F} \to \mathscr{F}'' \to 0$ is a short exact sequence, and $\mathscr{F}'$ and $\mathscr{F}$ are both interval-flasque, then so is $\mathscr{F}''$.  Here, the proof is pretty much the same as for the generally flasque case: use the previous fact, along with the Snake Lemma on the obvious morphism between short exact sequences of abelian groups.

*Any injective object of $\mathfrak{Ab}(\mathbb{R})$ is interval-flasque.  Well, we know it's flasque, so in particular it's interval-flasque.
So now, the standard proof that flasque sheaves are acyclic will also work for interval-flasque sheaves, with just a global replacement of "flasque" with "interval-flasque" in the proof.  Note that we do need the fact here that $\mathbb{R} = (-\infty, \infty)$ is considered an open interval in the preceding facts.

Now, it might be interesting to see where this proof fails if you try to apply it on $S^1$ instead of $\mathbb{R}$.  In particular, what goes wrong if you try to replace "open intervals in $\mathbb{R}$" with "open arcs in $S^1$"?  What goes wrong if you try to fix this failure by restricting to open arcs of length less than $\pi$?


text:
Q: react-admin - How to set input values based on another i'm trying to create a ZIP code input that loads street, state and city values automatically in a Create form using React-Admin. How can I populate the inputs based on the onBlur event of the zip code input?
The best result i achieved is the following scenario:
I created a custom component that has 4 Inputs: zip code (in my country is called CEP), street address, state and city. Then I added an onBlur event on the zip input and set the value on the inputs based on state attributes. Here is the code
class CustomAddressInput extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      cep : '',
      address : '',
      uf : '',
      city : '',
    }
    this.setAddress = this.setAddress.bind(this);
  }
  setAddress(e){
    if(e.target.value != undefined){
      endereco(e.target.value).then((result)=>{
        this.setState({
          cep: result.cep,
          address: result.logradouro,
          uf: result.uf,
          city: result.localidade
        });
      });
    }
  }

  render() {
    const { classes } = this.props;
    return (
      <TextInput label="CEP" source="cep" onBlur={(e) => this.setAddress(e)} defaultValue={this.state.cep} />
      <TextInput label="Endereco" source="address" defaultValue={this.state.address}/>
      <SelectInput label="Estado" source="state" choices={stateList} defaultValue={this.state.uf}/>
      <TextInput label="Cidade" source="city" defaultValue={this.state.city}/>
    );
  }
}
export default withStyles(styles)(CustomAddressInput);

And i'm using it on a Create
...
<Create {...props}>
  <SimpleForm>
    <TextInput label="Nome" source="name"/>
    <TextInput label="CPF/CNPJ" source="cpfcnpj"/>
    <TextInput label="Email" source="email"/>
    <TextInput label="Senha" source="password" type="password" />
    <TextInput label="Telefone" source="phone" type="tel"/>
    <CustomAddressInput/>
    <BooleanInput label="Pode criar outros usuários do sistema" source="canCreateUser" defaultValue={false}/>
    <BooleanInput label="Pode gerenciar projetos" source="canCreateProjects" defaultValue={false}/>
    <BooleanInput label="Pode visualizar honorários" source="canSeeFees" defaultValue={false}/>
  </SimpleForm>
</Create>
...

I know i'm setting the values in a wrong way because when the values are set, all the create form is wiped. What should i do? I'm not familiar developing with React.
Thanks in advance

A: I think i found the proper way of doing this. I moved the auto fill address function to a onChange event on the SimpleForm element and removed it from the CEP input. It works like a charm now. Here is the code:
Custom Address input
export default withStyles(styles)(
  class CustomAddressInput extends React.Component {
    render() {
      return (

            <TextInput label="CEP" source="cep" parse={parseCep} format={parseCep} validate={validateCEP}/>

            <TextInput label="Endereco" source="address"/>
            <SelectInput label="Estado" source="state" choices={stateList}/>
            <TextInput label="Cidade" source="city"/>

      );
    }
  }
);

And the Create Component
const autoFillAddress = (event)=>{
  if(event.cep){
    if(event.cep.length === 9){
      endereco(event.cep).then((result)=>{
        event.address = result.logradouro;
        event.state = result.uf;
        event.city = result.localidade;
      });
    }
  }
}
...
<Create {...props}>
  <SimpleForm onChange={autoFillAddress}>

      <TextInput label="Nome" source="name" validate={validateName}/>
      <TextInput label="CPF/CNPJ" source="cpfcnpj" parse={parseCpfCnpj} format={parseCpfCnpj} validate={validateCpfCnpj}/>

      <TextInput label="Email" source="email"validate={validateEmail}/>
      <TextInput label="Senha" source="password" type="password" validate={validatePassword}/>

    <TextInput label="Telefone" source="phone" type="tel" parse={parsePhone} format={parsePhone} validate={validatePhone}/>
    <CustomAddressInput />
    <BooleanInput label="Pode criar outros usuários do sistema" source="canCreateUser" defaultValue={false}/>
    <BooleanInput label="Pode gerenciar projetos" source="canCreateProjects" defaultValue={false}/>
    <BooleanInput label="Pode visualizar honorários" source="canSeeFees" defaultValue={false}/>
  </SimpleForm>
</Create>
...


text:
Q: How to add button in header [As-is image]http://sdrv.ms/1bx8Bxm
[To-be image]http://sdrv.ms/1aGADfo
We want to move the maintain button from context to header. We try a lot of method. some sample code but have error once we add in to our code. Can anyone help us pls?
the first image is what we are now, the second image is what we want to reach.
Thank you so much!!!

our code for maintain button in xml is like this:
<Button
android:id="@+id/maintain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Maintain"
android:background="#F77D03" />

A: Put this code in menu folder of resource
main1.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_maintain"
        android:showAsAction="always"
        android:title="Maintain"/>

</menu>

And this in Activity
@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main1, menu);// Menu Resource, Menu
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch(item.getItemId())
        {
        case R.id.action_maintain:
            Toast.makeText(getApplicationContext(), "Item 1 Selected", Toast.LENGTH_LONG).show();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }


text:
Q: JS detect mobile & desktop width & resize AND reload I have a function that detects the window width and based on that does jquery things that mobile would have and does jquery things for desktop. I have two functions, one that alters content resize and one on reload. What I am trying to do is combine the two into one function. The problem now is anything in the resize function just resizes. Even $("html").width();
Anyone have any ideas or solutions? Thanks.
//ON RESIZE
$(window).resize(function () {clearTimeout(this.id);this.id = setTimeout(checkTimer, 500);});
function checkTimer() {
    var width = $(window).width();
//MOBILE
    if (width < 640) {
        mobileView();
    }
//TABLET
    else if (width > 640 && width <966) {
        appendFix();
    }
//DESKTOP
    else if (width >966) {
        appendFix();
    }
};
//ON RELOAD
    var width2 = $(window).width();
//MOBILE
    if (width2 < 640) {
        mobileView();
    };
//TABLET
    if (width2 > 640 && width2 <966) {
        appendFix();
    };
//DESKTOP
    if (width2 > 966) {
        appendFix();
    };

A: Think I found the solution.
$(window).resize(function () {clearTimeout(this.id);this.id = setTimeout(mobileSize, 500);});
    function mobileSize() {
        sizes();
    }
    $(window).load(function() {
        sizes();
    });
function sizes() {
        var width = $(window).width();
        if (width < 640) {

        }
        else if (width > 640 && width < 966) {

        }
        else if (width > 966) {

        }
    }


text:
Q: web.xml in Spring Boot throws Unable to locate Spring NamespaceHandler for XML schema namespace I've generated Spring Boot application with annotation driven configuration.
However I wanted to configure some of the Spring Security with xml configuration because I have already a XML file that does it.
So I've created web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

</web-app>

and added @ImportResource("classpath:web.xml") to my @SpringBootApplication class
@SpringBootApplication
@ImportResource("classpath:web.xml")
public class Application extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(new Class[] { Application.class, WebAppInitializer.class }, args);
    }
}

And then I get:

2016-10-23 13:01:52.888 ERROR 9120 --- [           main]
  o.s.boot.SpringApplication               : Application startup failed
org.springframework.beans.factory.parsing.BeanDefinitionParsingException:
  Configuration problem: Unable to locate Spring NamespaceHandler for
  XML schema namespace [http://java.sun.com/xml/ns/javaee] Offending
  resource: class path resource [web.xml]

What is wrong?

A: The web.xml is no spring beans configuration file, so you must not include it in the spring bean configuration (you must not use @ImportResource("classpath:web.xml") )!

*

*The web.xml is to configure your servlet container (for example tomcat).

*The spring beans xml files are to configure Spring

So both are different.
Springs @ImportResource annotation is for importing spring bean configurations but not for servelt container configurations!

A: This code shows how you can use existing XML (not web.xml)configuration files in your main Spring Boot application(or maybe you have already some Java config that you need to use):
@ImportResource("classpath:applicationContext.xml")
@Configuration
public class SimpleConfiguration {
@Autowired
Connection connection; //This comes from the applicationContext.xml file.
@Bean
Database getDatabaseConnection(){
return connection.getDBConnection();
}
// Mode code here....
}


text:
Q: UWP Minimal Window Size larger than 500x500 Is there a workaround to the imposed limitation by Microsoft in order to set a Minimum Size of an UWP Application larger than 500x500? Without the limitation I would simply do:
ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(800, 600));

There was a similar question and a proposed workaround, but as stated in the comments, it provokes flickering, as it simply resizes the Window back, but does not disallow making it smaller in the first place.

A: I'm afraid this is the current state of things. I suggest this should be reported to the WinUI GitHub repository, as it might be something to be discussed for future versions of WinUI/UWP API.
I suppose the reasoning is that specifying minimum size higher than these bounds would limit the users with smaller screen size from using the application. Because screen size is not a requirement which can be enforced, it is preferred that applications are functional at different sizes.


text:
Q: SocketIO server not emitting event back to user who triggered event I'm using socket.io-client in my frontend (React) and socket.io in my backend (Express) application. On my server I created an event that when triggered should send a message to all users in a room, it looks something like this.
socket.on('connection', () => {
    // OTHER SOCKET EVENT LISTENERS (join, etc.)
    socket.on('my_event', async (roomId) => {
        // DO SOME DATABASE STUFF
        const response = ...;
        socket.in(roomId).emit('my_event_response', response);
    }
});

On my client looks something like this.
// socket.ts
export const socket = io(process.env.REACT_APP_SERVER_URL || '', { withCredentials: true });
export const SocketContext = React.createContext({} as Socket);

// parent.ts
export const ParentNode: FC = () => {
    const roomId = ...;
    return (
        <SocketContext.Provider value={socket}>
            <ChildNode roomId={roomId} />
        </SocketContext.Provider>
    );
}

// child.ts
export const ChildNode: FC = ({ roomId }) => {
    const socket = useContext(SocketContext);

    useEffect(() => {
        socket.on('my_event_response', () => {
            console.log("USER TRIGGERED EVENT")
        })
        return () => {
            socket.off('my_event_response')
        }
    }, [socket]);

    const handleClick = useCallback(() => {
        socket.emit('my_event', roomId)
    }, [socket, roomId]);

    return (
        <div>
            <button onClick={handleClick} />
        </div>
    );
}

When a user clicks a button to trigger an event, the server correct catches it and emits the response to all the users BUT the user that emitted the original event (my_event). I checked to make sure I'm not re-render my component and missing the event somehow. Is there a way to fix this so that the user who emitted the original event also gets the response?

A: Use io.in(...).emit(...) because socket.to(...).emit(...) emits to everyone in the room except the sender whereas io.in(...).emit(...) emits to everyone including the sender.


text:
Q: Python preferences on eclipse I'm using ubuntu 12.04
Ive installed eclipse and downloaded python for it
But when I go into the preferences I cannot find python
I am a complete beginner at this even with commands in ubuntu terminal  I can do very little but I'm slowly learning
Finally fixed this by uninstalling python from ecplise
then running ecplipse via command line as root
updated eclipse
then reinstalled python

A: After uninstalling PyDev from eclipse and removing its update as-well I closed eclipse
Then I run eclipse as root from the command line
sudo eclipse

I then reinstalled Pydev and all was OK


text:
Q: Getting "error cannot stat" messages in Windows when attempting to switch branches I am new to Git and have been running smoothly until this snag. I have just worked on a branch b1 and committed a number of changes, mostly involving moving files around to different folders. I then did
git push
git checkout master
git push

and everything was fine. Then I tried to do
git checkout b1

and I get a huge list of errors for all the files I recently changed, each one saying:
error: cannot stat '....': Permission denied

I look in my directory and it seems to be a weird mix of the old folders I should have in master right now (the old ones) and then new folders that should only appear if b1 is checked out, which when I try to click on them deny me axis. Seems like things are stuck in a limbo state.
Rebooting fixed the problem, but I want to know the source of the issue so that I don't need to resort to that if it happens regularly, or at least how I can avoid it.
I'm running Windows 10 on a laptop and pushing to GitHub.

A: Surely you've figured this out, but if you're running backend (python) or frontend (angular) services be sure to stop them as these processes may created this lock scenario.


text:
Q: Android image map. - displaying an .svg and using it as an image map (touch zones) I am looking for a way to display an image and have the user tap on different parts of the image to navigate and perform actions.
I was considering using an invisible color map to check which parts have been touched.
But since i also want to highlight the selected areas, i was thinking of using vectors.
There is a nice library to render svg files into an image view here,  but it doesn't handle touches.
Is there a library out there that does? Or any smarter way of doing this?
(I also checked out this project but it won't swallow .svg files and my vector image is far too complex to insert all the data by hand)

A: Interesting problem! I'm not convinced you can't use a combination of the libraries you mentioned.
What I would do is first use SVG-Android to programmatically read in your SVG file. Looking at SVG-Android, it looks like it returns the final product as a PictureDrawable, which is a subclass of Drawable.
Right after SVG-Android finishes processing the SVG graphics, I'd use ImageView.setImageDrawable to load the main ImageView with the PictureDrawable we just generated. Then I'd just use that ImageView as the base for the implementation of "Images with Clickable Areas" you linked in the original question.
Honestly, I think the hardest part will be getting SVG-Android to work correctly (I've played with it a bit, and it's a bit finicky). However, I don't think you'll have much difficulty combining the SVG-generated drawable with the clickable areas. It's a simple change in the source of the base image.
Good luck!

A: Not sure if this is the sort of thing you are after but here is an example of click enabled svg in a Android WebView:
WebView webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.w3.org/TR/SVG/images/script/script01.svg");

It should show a red circle that you can click on and the circle changes size.
Here is the same example reworked with the svg loaded from the assets folder and an android javascript interface exposed so you do callbacks into android code from your svg file.
  WebView webView;

  public class WebAppInterface {
    /** Show a toast from svg */
    @JavascriptInterface
    public void showToast(String toast) {
      Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
    }
  }

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

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.addJavascriptInterface(new WebAppInterface(), "Android");

    String svg = loadSvg();
    webView.loadData(svg, "image/svg+xml", "utf-8");
  }

  String loadSvg() {
    try {
      BufferedReader input = new BufferedReader(new InputStreamReader(
          getAssets().open("test.svg")));
      StringBuffer buf = new StringBuffer();
      String s = null;
      while ((s = input.readLine()) != null) {
        buf.append(s);
        buf.append('\n');
      }
      input.close();
      return buf.toString();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return null;
  }

and the test.svg file:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="6cm" height="5cm" viewBox="0 0 600 500"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example script01 - invoke an ECMAScript function from an onclick event
  </desc>
  <!-- ECMAScript to change the radius with each click -->
  <script type="application/ecmascript"> <![CDATA[
    function circle_click(evt) {
        Android.showToast("Hello from SVG");
      var circle = evt.target;
      var currentRadius = circle.getAttribute("r");
      if (currentRadius == 100)
        circle.setAttribute("r", currentRadius*2);
      else
        circle.setAttribute("r", currentRadius*0.5);
    }
  ]]> </script>

  <!-- Outline the drawing area with a blue line -->
  <rect x="1" y="1" width="598" height="498" fill="none" stroke="blue"/>

  <!-- Act on each click event -->
  <circle onclick="circle_click(evt)" cx="300" cy="225" r="100"
          fill="red"/>

  <text x="300" y="480"
        font-family="Verdana" font-size="35" text-anchor="middle">
    Click on circle to change its size
  </text>
</svg>

A: It's very very simple ;-)
You must create an javascript interface to handle click from web view and add this file to your web view. Just flow the step:
1) Create JavaScript Interface
public class WebViewInterface {
    @JavascriptInterface
    public void showDetail(String content) {
        Toast.makeText(getActivity(), content, Toast.LENGTH_SHORT).show();
    }
}

2) Add interface to web view
WebView webView = findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewInterface(), "Android");

3) Edit svg file same as this one
<?xml version="1.0" standalone="no"?>
<svg width="10cm" height="10cm" viewBox="0 0 600 500"
    xmlns="http://www.w3.org/2000/svg" version="1.1">
    <desc>Sample SVG</desc>
    <script type="application/ecmascript"> <![CDATA[
    function section_click(evt) {
        Android.showDetail("OnClick: " + evt.id);
    }
  ]]> </script>

    <rect id="rect" onclick="section_click(this)" x="1" y="1" width="598" height="498" fill="none" stroke="blue"/>

    <circle id="circle" onclick="section_click(this)" cx="300" cy="225" r="100"
        fill="red"/>

    <text id="text" onclick="section_click(this)" x="300" y="480"
        font-family="Verdana" font-size="35" text-anchor="middle">
        Click on each element
    </text>
</svg>


text:
Q: MySQL LOAD DATA INFILE "not found (Errcode: 13 - Permission denied)" Last week this was working, and today it isn't. I have not changed the php file. All I have done in the interim is run apt-get update on my Ubuntu 15.04 server.
The MySQL statement I have is:
LOAD DATA INFILE "/var/www/html/uploads/TitleList.csv" INTO TABLE tblLSITitleList FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY "\"" IGNORE 5 LINES;

This gives the following error:

File '/var/www/html/uploads/TitleList.csv' not found (Errcode: 13 - Permission denied)

I have tried the following solution (which was how I solved this exact problem early last week:
LOAD DATA INFILE Error Code : 13
I have checked the apparmor and the uploads folder is still there.
I have also tried chmodding various permissions, including 777, but nothing helps.
Any clever suggestions?

A: From the docs:
For security reasons, when reading text files located on the server,
the files must either reside in the database directory or be
readable by all

I recommend copying your .csv file to database directory, something like
cp TitleList.csv /var/lib/mysql/yourdbname/TitleList.csv

and then
LOAD DATA INFILE 'TitleList.csv' INTO etc ...

A: While one could copy the CSV into the mysql data directory, however this is not a good on-going solution. If you're using SQL command-line or code, include the LOCAL option into the query.

*

*For Example: Instead of LOAD DATA INFILE try LOAD DATA LOCAL INFILE
If you're using cPanel or phpmyadmin to import the CSV using LOAD DATA then be sure to Enable Use LOCAL keyword. This worked for me in a shared server environment.
This should prevent one having to copy the CSV to the MySQL data directory each time.

A: Adding the LOCAL keyword worked for me. I also made sure that the file has READ permission, since I'm working in Ubuntu:
LOAD DATA LOCAL INFILE '/path/to/file/name.csv'
    INTO TABLE 'table_name'
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\n';

A: In my case, LOAD DATA INFILE is a success with the first dataset.
But with the second dataset, I've got this errcode 13.
What I did (win user), I press CTRL+ALT+DELETE and then I selected Start Task Manager, then I went to the processes tab and selected Excel then pressed End Task.
Then tried again the LOAD DATA INFILE and it worked.
Note:  Before this, I tried to open the CSV file just to check the dataset.
It took too long, therefore, I closed it immediately before the file opened.
Maybe the incomplete process disturbed the load process.
I'm not sure with PHP because I just using phpmyadmin and play with MySQL