text:
Q: How to repeat async call? I have a program which does a simple http get in an async call and writes it to the console:
using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Hello
{
    class Program
    {
        private static readonly HttpClient client = new HttpClient();
       static async Task Main(string[] args)
        {
            await ProcessRepositories();
        }
        private static async Task ProcessRepositories()
        {
            client.DefaultRequestHeaders.Accept.Clear();
            var stringTask = client.GetStringAsync("https://localhost:8080");
            var msg = await stringTask;
            Console.Write(msg);
        }
    }
}

How could I repeat the whole process to make it write it to the console until a button is pressed?

A: class Program
{
    private static readonly HttpClient client = new HttpClient();
    static async Task Main(string[] args)
    {
        while (true)
        {
            var consoleKey = Console.ReadKey().Key;
            if (consoleKey == ConsoleKey.Enter) // if pressed Enter
                await ProcessRepositories();
            else if (consoleKey == ConsoleKey.Escape) // if pressed Esc
                break;
        }

        Console.WriteLine("Finish");
    }

    private static async Task ProcessRepositories()
    {
        client.DefaultRequestHeaders.Clear(); // idk why you cleaning headers, but OK
        Console.Write(await client.GetStringAsync("https://localhost:8080"));
    }
}

A: You can use Polly library for such calls. Do not use infinity loop, it is bad practice.
Here is an example about retry with exponential backoff.

A: To keep processing data until a key is pressed;
private static readonly HttpClient client = new HttpClient();

public static async Task Main(string[] args)
{
    var tokenSource = new CancellationTokenSource();
    var process = ProcessRepositories(tokenSource.Token);

    Console.ReadKey();

    tokenSource.Cancel();
    try
    {
        await process;
    }
    catch (OperationCanceledException) { }
}

private static async Task ProcessRepositories(CancellationToken token = default)
{
    while (!token.IsCancellationRequested)
    {
        Console.Write(await client.GetStringAsync("https://localhost:8080", token));
        await Task.Delay(30_000);
    }
}


text:
Q: Inconsistent line endings in SSIS Flat File import I have a large, pipe delineated text file with no text qualifiers, and it looks like whatever spit out this file accidentally spit out false "LF" markers in the last column every few hundred rows.
The last column is a descriptive column, and It is not text qualified in any way like it should be.
file looks similar to this:
id|data|data|data|data|Description[LF]
id|data|data|data|data|Description[LF]
id|data|data|data|data|Description[LF]
id|data|data|data|data|Descr[LF]
iption[LF]
id|data|data|data|data|Description[LF]
Id|data|data|data|data|Description[LF]
id|data|data|data|data|Descripti[LF]
on[LF]
id|data|data|data|data|Description[LF]
id|data|data|data|data|Description[LF]
id|data|data|data|data|Description[LF]
id|data|data|data|data|Description[LF]
id|data|data|data|data|D[LF]
escription[LF]

I'm pretty new to SSIS and SQL in general, Does anyone have any advice on how to fix this?

A: I did actually find a way to fix it in Notepad++, because I don't know C# and I don't know SSIS well enough..
The ID was 8 Digits long, and followed by 7 Blank spaces. That was absolutely unique to this file.
In notepad++ I used (Find Extended) to search and replace "\n"(LF) with nothing
then I used the this expression for find:
(\d\d\d\d\d\d\d\d[[:blank:]][[:blank:]][[:blank:]][[:blank:]][[:blank:]][[:blank:]][[:blank:]])

to find all 8 digit numbers with 7 trailing spaces, and for replace, used this:
\r\n\1

to put a [CR][LF] in front of those 8 digit numbers.
Lo and behold it worked!
But either way.. My boss contacted the client and is requesting a better file. Now I get kudos, and we get proper data. Thanks for the advice all!

A: If I had to take a guess, I would say that this is occurring because of how the file is created... you are probably having data that just happens to include certain special characters which are being incorrectly interpreted as a Line Feed.
Check this site to see if the data within your problem lines match any of these encodings. If this is the case then ultimately you have two options available:
1) Create some elaborate and complicated ETL process to detect and correct the file data before you process it. This is inadvisable as it will be a major pain to create and maintain.
2) Try changing the way this file is produced. Most text export wizards will allow you to place quotes (") around text items so that your import process can quickly detect something as a text block as opposed to a series of encoded characters to interpret.

redpajama_set_name: RedPajamaStackExchange


text:
Q: DAG to $3$ CNF SAT Given a DAG G, how to reduce it to $3$ CNF SAT to prove it is NP Hard?.
Take a Directed Graph, instead of weighted we assign some alphabets to the edges. When we try to find a path from S to T, we consider the alphabets in the edges say ABEDA. So the cardinality(ABEDA) is 5. But A ia already recorded so we can ignore the last A, so the cardinality now is 4(ABED). Now the clear question,
Given the DAG, can we say that finding the path of cardinality k is NP-Hard?.
Note : This is a question to find a path $P$ from Source $S$ to Sink $V$ with cardinality $k$ or path value of atmost $K$. Proving NP wasn't so hard, since we can verify a path existence in $O(|V|*|E|)$ atmost time.

A: Note: The answer below refers to an earlier version of the question. Appropriate changes will be made in due course.
I don't think the problem is NP-hard, although you also need to be clearer about what the problem is, and you have the reduction the wrong way around (and the technicalities wrong).
There are two different basic problems you mention: (1) finding a path of length at most $k$ from source $s$ to sink $t$ in a directed acyclic graph (presumably unweighted, but it doesn't really matter) and (2) finding a path of exactly $k$ edges.
I'm not clear on what you mean by "cardinality" and "path value". Normally "cardinality" would mean the number of edges, and if I were forced to guess, "path value" would be the total weight of the edges in the path.
Regardless, all of these problems are solvable in polynomial time:

*

*the shortest path problem is in P for general weighted graphs, so certainly is for DAGS (see for example the wikipedia page),

*finding a path with $k$ edges in a DAG can be solved by dynamic programming (this answer can easily be adapted),

*going even further longest path is also in P for DAGS, just in case you want paths of length at least $k$.

So you're probably not going to find an NP-hardness proof for these problems (if you do, you've just proved P = NP).
To address the other points, you can't reduce a DAG to 3-CNF SAT. A DAG is just a class of graphs, 3-CNF SAT is a problem. You reduced problems to other problems. As part of the reduction you map the input of one problem to the input of another. Furthermore, to prove NP-hardness, you need to reduce an NP-hard problem to the problem you're looking at (the idea being that if you could solve the new problem quickly, you could also solve the hard problem quickly).
So the question you should be asking is whether there is a reduction from 3-CNF SAT to your problem. This reduction would take a propositional formula in 3-CNF and construct a DAG such that the formula is satisfiable if and only if the DAG has an $st$-path of [length|weight] [at most|exactly|at least] (circle as applicable) $k$.
The final point is that $NP$, by definition, only contains decision problems, so you would technically have to phrase the problem as something like "Given a DAG $D$ with a source vertex $s$ and a sink vertex $t$, and integer $k$, does $D$ contain an $st$-path with exactly $k$ edges?". Note that this just asks a yes/no question, the output is not the path itself.


text:
Q: TextWrangler, How to hide page guide automatically? I know there's an option item to show/hide page guide in TextWrangler, but I just wonder, if there's an operation to hide page guide automatically ever time I run TextWrangler application? AUTOMATICALLY!
Thanks!

A: Try "Preferences"->"Appearance" and uncheck "Page guide" in the section "Editing window".


text:
Q: Does it ever make sense to write 2 classes with identical names in the same python program? Are there any scenarios where it would make sense to write two python classes in the same program with the same name using different parameters? I was thinking through this program, but my 2nd test class will just overwrite the first. Is this always the case?
class test:
    def __init__(self):
        print("first class")
    def oneplus(self, x):
        print(x + 1)

class test:
    def __init__(self):
        print("second class")
    def twoplus(self, x):
        print(x + 2)

t = test()
t.twoplus(1)

will just result in using the 2nd instance:
second class
3

A: yes, if you define a class with the same name as an already existing class, it will override the definition.
BUT existing instances of the first class will still behave as usual.
small example:
class test:
    def __init__(self):
        print("first class")
    def oneplus(self, x):
        print(x+1)

t1 = test()

class test:
    def __init__(self):
        print("second class")
    def twoplus(self, x):
        print(x+2)

t2=test()
t1.oneplus(1)
t2.twoplus(1)

Output:
first class
second class
2
3

If you never use the first class, IDEs like PyCharm will even warn you about this:

A: A program may consist of more than one module. In that case, it can make a lot of sense to have a class with the same name. For example if you have a feature that works differently in Windows vs Linux, you can have a module implementing the windows-specific stuff, and a module implementing the Linux-specific stuff. Both would have classes with identical names. In your code, you could do
if os.name == nt:
    from windows_support import Feature
else:
    from linux_support import Feature

This could be done for any external influence, not just the platform.
If you have only a small number of differences, usually ones that are a subset of the module in question, you can have two classes with identical names in different branches of an if statement. For example:
if os.name == 'nt':
    class Feature:
        ...
else:
    class Feature:
        ...

The statements def, class, and most forms of import are assignments. It makes just as much sense to assign a different value to a name under different conditions as it does a different class or function. After all, classes are just objects in python.
That being said, all the examples above work best if both options implement the same public interface.
An example of different classes that unconditionally have the same name in the same namespace that serves a real life purpose is forward declaration for type hints. Until PEP 563 introduced delayed evaluation of annotations in Python 3.7, it was impossible to use a class name in an annotation until it was assigned. By extension, that meant that methods of a class could not accept or return instances of the class they were defined in, and circular references between classes were not supported without a workaround. That workaround was to define an empty definition of a class with the same name, before the classes that would be using it in type hints. This would actually keep a reference to the forward-declared throwaway class around, which was one of the motivations for PEP 563.

A: As mentioned above, the second assignment of test will override the first assignment. Basically, when a class is assigned in Python it is stored in memory with a type, value, and reference count. In this case the first assignment of "Test" creates a python object (Test1) with a reference count of 1 and the second assignment of "Test" creates another python object (Test2) with a reference count of 1, but "Test" is no longer referencing the original python object (Test1) so its reference count decreases to 0.
Example of names in Python.
Great resource for python objects: https://realpython.com/pointers-in-python/

A: Unless you plan on making the system recognize the second definition only, then making two variables with the same name will not make a difference.

A: You can add 1 more method in Test class,
class test:
   def __init__(self):
      print("first class")
   def oneplus(self, x):
      print(x + 1)

   def twoplus(self, x):
      print(x + 2)

t = test()
t.oneplus(1)
t.twoplus(1)


text:
Q: Stored Procedures - End of days I'm listening to the Hanselminutes Podcast; "StackOverflow uses ASP.NET MVC - Jeff Atwood and his technical team". During the course of the Podcast they are speaking about SQL server and say something along the lines of 'The days of the Stored Procedure are over'.
Now I'm not a DBA but this has taken me a bit by surprise. I always assumed that SPs were the way to go for speed (as they are complied) and security not to mention scalability and maintainability. If this is not the case and SPs are on their last legs, what will replace them or what should we be doing in the future?

A: SPs are probably the way to go if you are ONLY concerned about speed.  But if you care about scalability or maintainability, SPs might not be the best.  Our architecture is built on SPs and after 10 years of code, it is very hard to maintain and very buggy. A good ORM mapper might be a better choice.

A: Maintenability
Probably SPs are better. If maintaining hundres of SPs are hard, maintaining them in business tier components is even harder.
Performance
Caching of queries might be producing near performance to SP. But they can't match performance of SPs across varieties of databases in varieties of platform. Network latency is another area of concern, though the gap is reducing nowadays.
Debug
Is probably fairly easy with SPs than debugging business tier + db tier put together.
There can be even more +ve points using SPs.
But looking at the modern trend of programming, its rather "wise" to go with 'N' tier architecture for plenty of business reasons than sticking with "old" SP based approach.
Good system should have mix of both. Probably following 80-20 principle, 20 being SPs.

A: maybe i'm too old-school, or too lazy, or both, but i have to disagree. Time and again stored procedures have 'saved the day' because when a minor back-end change or bug appears we only have to fix the stored procedure instead of updating the desktop application on several dozen desktops plus the web server. In addition, the users are not interrupted. This saves a great deal of effort and user hassle.
In addition, some DB operations are just going to be more efficient on the server rather than going back-and-forth across the network, esp. when one stored procedure calls another which calls another etc. (with or without cursors)
EDIT: in a SOA architecture the update-the-client-apps issue is mitigated (thanks maud-dib), but stored procedures calling each other is still more efficient than multiple network round-trips to the SOA layer. And updating the SOA layer is not always trivial either.

A: Stored procs are useful for stuff that is not CRUD -- such as specialized, cross-table logic that is best executed in the DB.  CRUD operations should not use SPs unless they are the automatically generated output of an ORM tool like TableAdapters.

A: ORM and LINQ to SQL seem to be the current trends for replacing StoredProcs.
I personally have used ORM and find it much easier to maintain and support.
Some of the reasons stated for using stored procs where never legitimate reasons to begin with.
You do make a good point about having a stored procedures when you service multiple applications; they essentially become the DAL, usually with some business logic in there.

A: When you combine SPs with logic with the database itself, you effectively convert the DB in to something akin to an Application Server.
Back when this was the hammer that was most handy, it made a lot of sense. But now with ubiquitous availability of Application Servers, it makes more sense to leverage them for things like centralized logic and business rules and rely on the DB for persistence only.

A: Some good point make on both sides (as it were) but no-one has made much of the security implication. Wrapping up all DB interaction in SPs means you can lock down the DB so that any interaction with the data can be tightly controlled.
If you think of Encapsulation, you can regard the DB as an object and the SPs as methods and properties that expose the objects functionality to the outside world.
In some larger development environments, UI and Business layer developers aren't allowed near the DB. They specify their requirements and the separate team provides and interface via SPs.
There are some good reasons for not using SPs and some good reasons for only using them - depends on your application and your environment. But rest assured that SPs won't be going anywhere anytime soon.

A: On modern systems, parameterized queries are compiled and cached at the server, so they're just as fast as a stored procedure. They have most of the same security features as well.
For databases that serve a single application, it makes more sense to have the query logic there at the relevant location in the code.  If nothing else it makes it easier to do source control.  If you keep stored procedures on the server keeping track of them can quickly become a mess.  Additionally, if you're using an ORM tool you may not have much in the way of real SQL anyway.
If your database serves several different applications, then you may still want to use stored procedures to enforce business rules between application.

A: Judging from the lackluster performance of this site, I'm going to wager the major bottleneck is the database.
I'm not convinced in any way that the LINQ 2 SQL ORM they are using is one bit faster than a sproc.

A: I'd say that SPs aren't maintainable and they don't scale.  Ask any developer who's had to add functionality to a SP heavy system.  Why have half your logic in a different layer?  There's nothing to replace, just don't use 'em.
Googled this great post.

A: I keep hearing the argument that SPs are good if you have multiple applications connecting to the database or that it makes bug fixing easier.
THIS IS WHAT A SERVICE LAYER IS FOR!
Business logic goes in the service layer, application logic goes in the application/web site.
It's alot harder to debug and maintain hundreds of SPs (especially if there generated) than it is to maintain well written code that talks to a DB via an ORM tool.

A: It also depends on what your stored procedures are doing.
For example if it's just
select a from b where x = y

then a stored procedure is probably overkill. But I personally tend to use stored procs to return multiple result sets and page results within the database.
In my cases I can see a benefit to using them. It is an extra layer to deal with but if you have your code well organised and logical I don't see too much hassle personally.
A good project with stored procedures is always going to be better than a shoddy project without and vice versa.

A: Just throwing my little advice here. Before SQL 2005 (maybe even farther than that), SP were faster. However, SQL Server 2005 and up are really optimized and they cache your queries as you go. In fact, we had a web application transfered to a new SQL server. The application started by running slowing for everyone. Everything was taking "3/4 of a second" or 1 second to run. Then SQL started compiling the most used query and everything went from slow to blazing fast.
Of course, we swapped the server while there was a lot of people running on it (which can explain why it was slow at first). But trust me. SP are not over. They just have other uses than being tied to an application.

A: This question also bleeds into one posted earlier today.

A: SP's are generally used way too soon in the dev process. They should be used when you have a bottle neck sql statement. For example, you probably don't need an SP for deleteing or creating users for an app. For most companys that should be pretty static.

A: Could it rather be that Jeff Atwood knows stored procedures will be around forever and was merely trying to stimulate thought and debate? I like to think that what he really would like to do is to write a persuasive essay entitled "Stored Procedures Considered Harmful" :)

A: I might add that some work be better done at the DB level.
e.g. Cross tab results in SQL 2005, Recursive queries.
I agree that some of the simple stuff such as SELECT, INSERT, UPDATE, DELETE can be taken care of by ORM, Linq.
So, it is stupid to say that days of stored procedures are over.
How many people really have to worry about DB platform changes (SQL to Mysql, Oracle)?

A: Part of this is driven by the availability of non-relational datastores. SPs generally imply a relational database; ORM and Linq offer the the ability to create abstraction layers that are richer than SQL offers, and sometimes a better match for the abstractions we use in other parts of the design (the "impedance mismatch" problem.)
And it can also be considered a function of architecture. SPs imho match pretty well with a classical table-driven application, and can provide a convenient way to architect an abstraction layer at the business-objects level.
They're not so handy if your data store is xml, or an analytical database.

A: Stored Procedures / Views / Functions are still a good "Interface" to the database if you are running multiple enterprise applications sharing the same database.
App#1 - You need to add a new relationship/field, or change a nullable column to non null.
App#2-10 - May or may not use this database object
The first thing I want to do is check my database object dependencies to determine how its used and if I'll break anything. Well, guess what, if you have a bunch of external queries VIA ORM / SQL you would have no idea of the dependencies.
This is the only drawback I found having direct access to tables.
For a single application using single database, this really isnt an issue. Although you still have to look at the application code for dependencies in addition to the database.

A: Bah!
ORM, SPs, View, Magic Wands, or whatever.
Each "tool" has its place in your belt, use the tools you have wisely.
The only thing that has "changed" ( really improved ) is that some ORMs have nice caching tools already baked in and MySql and Sql 2005+ can handle dynamic or ad hoc query/execution plan caching.
The potential performance loss from throwing the all sorts of dynamic sql at your db server has been somewhat mitigated.  Its just easier to go without stored procedures now.  Stored Procs aren't going anywhere.


text:
Q: Get smaller size of image, get_the_post_thumbnail My theme is using this code in a shortcode to get the image of the post. However, this is the full size image and i am looking to get the small thumbnail instead. How could I do this?
   $image_output       = '
' . get_the_post_thumbnail( get_the_ID(), 'entry', NULL ) . '
';

A: Just change the code to:
$image_output = '
' . get_the_post_thumbnail( get_the_ID(), 'thumbnail', NULL ) . '
';

See in the Codex:
Thumbnail Sizes
get_the_post_thumbnail


text:
Q: How to merge two branches with Git based on file differences instead of commits? I have a question regarding the merging process which can be quite difficult when using Git.
I'm familiar with most commands and got a good-running local repository on a different machine (on which I commit changes for our live-server at this moment). I also know the complete workflow within Git (Local Repos/Index/Workspace etc).
The problem is on my own development machine (standard Win8 machine).
I had a lot of trouble merging two branches and whatnot and finally solved all conflict with "git mergetool" command only to find out that not all files are merged.
Situation
I have my own branch on which I'm developing software, lets call it "myBranch". Then we have the "release" branch which is our final stage before we push to the live-server. I need to have all the code of "release" in "myBranch". They have a common ancestor at some point.
The thing right now is (after weeks of struggling getting everything to work, hence my frustration) there are pieces of code in "release" that aren't in "myBranch". Running "git merge" gives me the message "Already up-to-date".
Question
Thus my question is: How can I let Git compare two branches based on actual file differences instead of commit differences so I can merge code I haven't got in my own branch yet, code that exists on the "release" branch but is not seen as a difference.
If my question is not complete enough please ask for additions and I'll try to make it as complete as possible.
Thanks in advance!

A: If I have understood the question correctly, this is a very common situation in software development: Changes are done on a dev branch forked off a release branch that itself gets new commits in the mean-time. Assuming you are on 'myBranch', periodically rebase to 'release'.
$ git fetch --all
$ git rebase origin/release

If completed successfully, it will merge all changes in 'release' to 'myBranch' and it would look like you did your changes right on top of the latest 'release' branch.


text:
Q: How to read content in image and pdf in alfresco I want to know how to search content from image and PDF in alfresco using OCR integration
please let me know the steps how can i do this??Using Kofax or EpheSoft scanning software..
Let me know the steps...
I tried out https://docs.alfresco.com/4.1/tasks/kofax-amp-install.html link but failed to install amp files..
For ex:content is search from image or pdf
How is it possible?
please help me..
Thanks in advanced

A: It's not 100% clear so her it goes.
First OCR is not something Alfresco does, but Kofax/Ephesoft.

*

*Check if Kofax/Ephesoft does OCR right. Save the PDF manually in Alfresco and check if it's searchable.

*Install the Kofax AMP

*Install the Alfresco releasescript in Kofax

*Connect to Alfresco from Kofax via the releasescript (define a root folder to scan to)

*Scan to Alfresco and all should be well.

For Ephesoft, follow this http://addons.alfresco.com/featured/document-capture-ephesoft


text:
Q: check memory usage I'm using C#.
Is it possible to check how much memory each variable in my code has been using during the runtime?
I can't get a clue as to which construct in my code has been using up memory which is ultimately leading my system to crash.
Thank You

A: There are several good memory profilers available such as ANTS Memory Profiler.
Alternatively you can use WinDbg + SOS. WinDbg is a free download from Microsoft and SOS is part of the .NET framework. Check Tess' blog for how to debug memory issues with WinDbg + SOS.


text:
Q: Anyone please tell me the difference between #filename and filename.html

  home

  home

please anyone clarify this.
when i click on home with #filename as href element it is not navigating to next page...

A: #filename is a fragment identifier. It links into an element in the page.
filename.html is a URI. It is a link to a (usually) different page.
Given your example + a small change:

  home

  home

 The home

#filename links to the span with id="filename". If that span is not visible, the page will jump to it (but there will be no call to the server to refetch the page).
filename.html links to the html page in the same directory whose filename is filename.html.

A: Say your website is www.website.com
home will change the URL to www.website.com#filename but not actually refresh the page. If there happens to be an element with the attribute name="filename" the browser will jump to that element.
home will redirect the browser to www.website.com/filename.html

A: #filename will take you to a given anchor (or element with the ID of filename) on the current page.
filename.html will take the user to the HTML file called filename.html.

A: #filename is an anchor refering to something on the current page. filename.html is an URI and refers to a (most probably different)webpage.


text:
Q: Integrate AWS s3 bucket with flutter I'm creating flutter application with Firebase authentication. But I need to store some recording files (mp3) to cloud storage. I need to use aws s3 as a requirement. So I tried to integrate the that with flutter.
I have found official plugin called amplify_storage_s3 on pub.dev
But I had to read from documentation I need to amplify authentication to use that.
I don't want to use amplify auth because I'm already done it with firebase authentication.
So what I can do?


text:
Q: Does the VerticalCallout algorithm in PieChart3D work correctly? In real world usage you often want to use real world labels with long strings (say 15-20 characters) in 3D pie charts. Here is a toy example :
Clear[labeler];
labeler[datax_][v_, {1, c_}, ___] :=
  Placed[Column[{datax[[c]], v}, Alignment -> Center,
    BaseStyle -> Directive[FontFamily -> "Arial", 11]],
   "VerticalCallout"];
data = Transpose[{"This is label " <> ToString[#] & /@ Range[14],
    Range[14]}];

PieChart3D[{data[[All, 2]]},
 ChartElementFunction ->
  ChartElementDataFunction["ProfileSector3D", "Profile" -> 4],
 ChartStyle -> 54,
 ImageSize -> 400,
 LabelingFunction -> labeler[data[[All, 1]]],
 PerformanceGoal -> "Speed",
 PlotRange -> All,
 SectorOrigin -> {Pi, 0},
 SectorSpacing -> 0.2]

We see that the plot area seems to have been determined without reference to the labels that will be placed around the chart. Consequently the labels are cut off.
Q. Is this an Image Padding issue?
A. no (note that All gives the same output as Full)

Q. So why not expand the margins around the image to give the labels enough space to be rendered?

So increasing the image margins merely creates another graphics area around the original image.
This looks like a bug or design flaw to me. Does anyone have any ideas about how to get VerticalCallout labels working in PieChart3D?

A: WRI Tech support confirm a bug. ImagePadding->All should work.
Edit
To address Bretts comment: In 2D ImagePadding->All works -- the ImageSize increases in the x direction by the amount of padding required. Nothing has to give. Why does something have to give in 3D?


text:
Q: regex returning only the first found I'm trying to search for a certain word in a string data but it only returns the first match.
const searchFunc = (stringData, searchedType) => {
  const regex = new RegExp(`${searchedType}(.*)`, "g");
  var arr = regex.exec(stringData);
  while (arr !== null) {
    prefix = arr[1].replace(/[`_:'",.]/gi, "")
    return prefix;
  }
};

i call the search function in another one like this :
searchFunc(data, "path");

my strinData is like this :
{
  path: '/aaa',
  ...
},
 {
  path: '/bbb',
  ...
  },
},
{
  path: '/ccc',
  ...
},

The output i get :
=>  /aaa

The output i want
=>  /aaa
=>  /bbb
=>  /ccc

A: Create an array to put the results in, then push to that array in every iteration of the while loop, and return the array at the end of the function:

const searchFunc = (stringData, searchedType) => {
  const pattern = new RegExp(`${searchedType}(.*)`, "g");
  const results = [];
  let match;
  while (match = pattern.exec(stringData)) {
    results.push(match[1].replace(/[`_:'",.]/gi, ""));
  }
  return results;
};
const data = `routes: [
{
  path: '/aaa',
  xxx: {
    ...
  },
},
 {
  path: '/bbb',
  xxx: {
    ...
  },
},
{
  path: '/ccc',
  xxx: {
    ...
  },
},
],`

const prefixValue = searchFunc(data, "path");
console.log(`prefix found => ${prefixValue}`);

Note that this is an X/Y problem: ideally, fix whatever's serving you that string so that it gives you proper JSON instead, so that you can parse it into an object and use object/array manipulation methods instead, for example:

const searchFunc = (data, prop) => data.map(obj => obj[prop]);
const dataArr = [{
    path: '/aaa',
    xxx: {},
  },
  {
    path: '/bbb',
    xxx: {},
  },
  {
    path: '/ccc',
    xxx: {},
  },
];

const prefixValue = searchFunc(dataArr, "path");
console.log(`prefix found => ${prefixValue}`);


text:
Q: Remove green screen from a image and make it transparent I found a solution to this but the background is not transparent, it's black and I don't know how I should make it transparent.
Here's my code:
from PIL import Image

image = Image.open('pic.jpg')
image.show()
image_data = image.load()
height,width = image.size
for loop1 in range(height):
    for loop2 in range(width):
        r,g,b = image_data[loop1,loop2]
        image_data[loop1,loop2] = r,0,b
image.save('changed.png')

A: If your background consists of one color, then you can replace it with transparent in the following way:
from PIL import Image

img = Image.open('pic.png')
rgba = img.convert('RGBA')
data = rgba.getdata()
green_rgb = (0, 128, 0)  # change it to your exact bg color

new_data = [item if item[:-1] != green_rgb else (255, 255, 255, 0) for item in data]

rgba.putdata(new_data)
rgba.save('changed.png', 'PNG')

However, if your background is of different shades, then you will have to write additional checks and determine the boundaries of acceptable shades of green.


text:
Q: How to change Page Title with Tag Manager in order to show different title in Analytics? The best solution would be to modify website that is being tracked and change it to generate more valuable Page Titles.
However, that isn't possible and I would like to use breadcrumbs to provide new Page Title for Analytics.
I've created new variable for title in Tag Manager and added a Trigger for it in a Tag.
And yet the Page Title isn't changing and therefore I ended up wondering should this tag be fired before Analytics tag?
EDIT:
I've now used it with Preview mode and I can see that it is at least trying to set a new value for title. However, the value seems a bit too "unescaped" and I think that there's some hidden characters that cause problems.
EDIT 2:

function() {

    var a = jQuery('.breadcrumb_container a');

    delete a[0];

    var textValues = jQuery(a).map(function() {

        return jQuery(this).text();

    }).get();

    var str = textValues.join(' > ');

    return str;

}

A: There is no need to create a new trigger. You should edit your existing pageview tag and set field of title as indicated below:


text:
Q: How to find all SO10 text modules used in an SAP Adobe Form? How do I find all the text modules used in an Adobe Form? Is there a table somewhat like TADIR where I could type in the Adobe Form name and the object names (text modules) for that form name will appear?

A: My answer regarding Smart Forms is perfectly valid for Adobe Forms too. Adobe Forms also have SO11 text elements hard-coded in the form FM code. The only difference is link between Adobe form FM and Adobe form INCLUDE: for some reason there is no link for them in the D010INC table.
However, as your intention is to find text elements of a single form, and not mass searching, you can find out the INCLUDE manually.

*

*Find out Adobe form function module name. You can do this either manually (Test button in SFP tcode)

or via the FP_FUNCTION_MODULE_NAME FM. Resulting Adobe Form function module name should follow /1BCDWB/SM0000XXX pattern.

*Open this FM in SE37 and go to function group code (GoTo->Main program). There you will find something like this and there get the name of main INCLUDE, which holds the code.

*Then by forward navigation go to INCLUDE code and by simple Find of %textkey-name pattern you can observe all text elements which were utilized in the form.


text:
Q: use of $_GET to get value in same page in php? I am writing a code to perform action in php. When i started the page it shows the error below:
 Notice: Undefined index: action in D:\page.php on line 19 for the $action.

and when the action occurs it does not show for the $dev also. When i start the page there is no action  and no $dev on the page.
So the error shows. how can i fix the problem ?
<?php
$action = $_REQUEST['action'];
$dev =$_GET['dev'];
if ($action == "viewfootage"){

}

A: You need to check for the existence of $_REQUEST['action'] and $_GET['dev'] using the isset function
if(!isset($_REQUEST['action']))
    $action="";//or any value for which you capture the desired output

Same thing goes for $_GET['dev]
If you want to check for all variable in one line use logical OR operator
if(!isset($_REQUEST['action']||!isset($_GET['dev']))

A: Use
if(isset($_REQUEST['action']))
{
    $action = $_REQUEST['action'];
    $dev =$_GET['dev'];
    if ($action == "viewfootage"){

    }
}

A: Use this :
if(isset($_REQUEST['action']))
{
    $action = $_REQUEST['action'];
    $dev = $_GET['dev'];
    if ($action == "viewfootage"){

    }
}

Check whether the url consists of action and dev params


text:
Q: Merge multiple pdf pages into specific pdf page using pdftk I have merged.pdf file with 18 pages. I would like to merge into source.pdf file starting from page 46 and get final.pdf using PDFTK
I tried with this command, but it didn't work:
pdftk A=source.pdf B=merged.pdf cat A1-45 B1-18 A64 output final.pdf

Any idea?

A: Only a little correction of your original proposal is needed:
pdftk A=source.pdf B=merged.pdf cat A1-45 B A46-end output final.pdf
You don't have to write "B1-18" to refer to the whole document. You can just use "B" to indicate an entire PDF. BTW, you can also use "end" if you want to refer to the last page, e.g. "B1-end"
"A64" in your example means "catenate page 64 of source document" but - if I understand it correctly - you want to put those 18 pages inside larger document and you don't want to lose any page of any of those two documents, right?
Then you need to catenate first 45 pages of the source document (which translates to "A1-45"), then 18 pages of the merged document ("B"), and finally all the pages from page 46 to the end of the source document ("A46-end").


text:
Q: Laravel one session per user I'm trying to figure out how to only allow one session per user.
So if someone tries to log in when he already logged in his user account, the first session will be destroyed and will be logged out to allow the current session only.
I'm following this: How to keep single session per user in Laravel . But i don't know where I should put these lines of codes:
/**
 * Swap a user session with a current one
 *
 * @param \App\User $user
 * @return boolean
 */
protected function swapUserSession($user)
{
    if (!($user instanceof \App\User)) {
        return false;
    }

    $new_session_id = Session::getId(); //get new session_id after user sign in
    $last_session = Session::getHandler()->read($user->last_session_id); // retrive last session

    if ($last_session) {
        Session::getHandler()->destroy($user->last_session_id);
    }

    $user->last_session_id = $new_session_id;
    $user->save();

    return true;
}

I'm currently using Laravel 5.1, so The only controller I can find for the Auth is AuthController.php but it says to put it on the LoginController.php

A: If you're using the file driver you can add the following method to App\Http\Controllers\Auth\AuthController.php (tested in Laravel 5.2)
/**
 * Only allow one concurrent session per user
 *
 * @param  Request  $request
 * @param  User  $user
 * @return Response
 */
protected function authenticated(Request $request, User $user)
{
    Session::put('user_id', $user->id);

    $files = array_diff(scandir(storage_path('framework/sessions')), array('.', '..', '.gitignore'));

    foreach ($files as $file) {
        $filepath = storage_path('framework/sessions/' . $file);
        $session = unserialize(file_get_contents($filepath));

        if ($session['user_id'] === $user->id && $session['_token'] !== Session::get('_token')) {
            unlink($filepath);
        }
    }

    return redirect()->intended($this->redirectPath());
}

A: If you're running off of the latest laravel 5.3.15 or higher I would recommend checking out the following link I've posted about this issue I've ran into. Took me some time to figure out but I did and the fix is really simple.
First (assuming you've installed laravel 5.3 cleanly):
Get sessions table up and running-
Go to the session configuration file stored at config/session.php and scroll down to the driver configuration.
By default it should be set to 'file'.
Change this setting to 'database'. (Provided you want to store sessions in a database)
In your console, in the project directory, perform:
php artisan session:table

php artisan migrate

Then in the following link scroll down to the last comment and follow the steps to fix the session issue.
https://github.com/laravel/framework/issues/15821


text:
Q: JQuery UI Slider - 'value' not setting starting position of handle I would expect the following code to start my slider at '30' in it's range of 0-250, but yet it is not.
$(function() {
  $( "#slider" ).slider({
  value: 30,
  min: 0,
  max: 250,
  step: 1,
  slide: function(event, ui){
    $("#edit-varprice").val(ui.value + ".00");
  }
  });
});

Image : http://gallery.twardnw.com/var/albums/Misc/Screen%20shot%202012-04-03%20at%203.06.59%20PM.png?m=1333490924

A: Its working fine for me. See jsFiddle Demo.
Perhaps you are missing something else or doing something in other parts of your code, can you post full code?

A: try removing the value from the options u chose, and adding it later using:
$( "#slider" ).slider( "option", "value", 40 );

A: Could you lower your max to 50 and see if the slider handle is offset, if so then its working just fine. In the image it looks like its slightly offset. 30/250 is only 12% and may be deceiving.


text:
Q: Restart forced when set for delay This has now happened three times:
Windows tells me a restart is needed in order to install an update.
I change the restart time to the day after tomorrow (and set a time as well).
When trying to shutdown, the laptop tells me there are now three options: sleep, update and restart, or update and shutdown. I didn't ask for that, I just told it to delay the restart. There is no 'shutdown' option.
So, not wanting to wait for the update to happen at that moment, I choose 'sleep'.
Next day, I open the laptop, it goes immediately into the update process. You know, the one that I had set for the next day?
Why is that happening? Why is Windows completely ignoring my settings???
How can I change this behaviour?
Laptop is an ASUS K53S.
Thanks in advance.

A: The system gives you the option to delay the restart to a set time OR the next system shutdown. You can change your prefered time of the restart in case  the time it proposes it to you is inconvenient, but since you weren't using your computer anymore the system had no reason to assume the update would be of any inconvenience to you.


text:
Q: Android : Check 3G or Wifi network is ON or Available or not on android Device How to check that network is available or not on android device programmatically, which throws a message or toast message when we are trying to connect with a network such as Wifi & 3G.

A: final ConnectivityManager connMgr = (ConnectivityManager)
    this.getSystemService(Context.CONNECTIVITY_SERVICE);

    final android.net.NetworkInfo wifi =
    connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    final android.net.NetworkInfo mobile =
    connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if( wifi.isAvailable() && wifi.getDetailedState() == DetailedState.CONNECTED){
        Toast.makeText(this, "Wifi" , Toast.LENGTH_LONG).show();
    }
    else if( mobile.isAvailable() && mobile.getDetailedState() == DetailedState.CONNECTED ){
        Toast.makeText(this, "Mobile 3G " , Toast.LENGTH_LONG).show();
    }
    else
    {
        Toast.makeText(this, "No Network " , Toast.LENGTH_LONG).show();
    }

this code check if you are with wifi or 3g or nothing , in the case of wifi on but not connected to a net or 3g have signal problem it detect this details, with DetailedStates

A: You can use this method to check whether your internet connection is 2G, 3G or 4G:
public String getNetworkClass(Context context) {
    TelephonyManager mTelephonyManager = (TelephonyManager)
            context.getSystemService(Context.TELEPHONY_SERVICE);
    int networkType = mTelephonyManager.getNetworkType();
    switch (networkType) {
        case TelephonyManager.NETWORK_TYPE_GPRS:
        case TelephonyManager.NETWORK_TYPE_EDGE:
        case TelephonyManager.NETWORK_TYPE_CDMA:
        case TelephonyManager.NETWORK_TYPE_1xRTT:
        case TelephonyManager.NETWORK_TYPE_IDEN:
            return "2G";
        case TelephonyManager.NETWORK_TYPE_UMTS:
        case TelephonyManager.NETWORK_TYPE_EVDO_0:
        case TelephonyManager.NETWORK_TYPE_EVDO_A:
        case TelephonyManager.NETWORK_TYPE_HSDPA:
        case TelephonyManager.NETWORK_TYPE_HSUPA:
        case TelephonyManager.NETWORK_TYPE_HSPA:
        case TelephonyManager.NETWORK_TYPE_EVDO_B:
        case TelephonyManager.NETWORK_TYPE_EHRPD:
        case TelephonyManager.NETWORK_TYPE_HSPAP:
            return "3G";
        case TelephonyManager.NETWORK_TYPE_LTE:
            return "4G";
        default:
            return "Unknown";
    }
}

And using following method you can check if internet is available or not, and get whether you are accessing the internet via a mobile network or WiFi:
public String getNetworkType(Context context){
    String networkType = null;
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
    if (activeNetwork != null) { // connected to the internet
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                networkType = "WiFi";
        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            networkType = "Mobile";
        }
    } else {
        // not connected to the internet
    }
    return networkType;
}

A: TO check whether network i.e 3G or WiFi is available or not we can use below methods to verify before starting our activities.
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

//For 3G check
boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
            .isConnectedOrConnecting();
//For WiFi Check
boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            .isConnectedOrConnecting();

System.out.println(is3g + " net " + isWifi);

if (!is3g && !isWifi)
{
Toast.makeText(getApplicationContext(),"Please make sure your Network Connection is ON ",Toast.LENGTH_LONG).show();
}
 else
{
        " Your method what you want to do "
}

Hope this will help someone.

A: This work for me
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
String name networkInfo.getTypeName();

A: Rahul Baradia's answer includes manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) and it's deprecated.
Below is an improved solution for the latest Android SDK.
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
        boolean is3gEnabled = false;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Network[] networks = connManager.getAllNetworks();
            for(Network network: networks)
            {
                NetworkInfo info = connManager.getNetworkInfo(network);
                if(info!=null) {
                    if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                        is3gEnabled = true;
                        break;
                    }
                }
            }
        }
        else
        {
            NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if(mMobile!=null)
                is3gEnabled = true;
        }

A: Use the following code as NetworkChecker.java & reuse it in your code:
package das.soumyadip.util;

import android.net.ConnectivityManager;
import android.util.Log;

public class NetworkChecker {
    private final static String TAG = "NwtworkChecker";

    public static boolean isNetworkConnected(
            final ConnectivityManager connectivityManager) {
        boolean val = false;

        Log.d(TAG, "Checking for Mobile Internet Network");
        final android.net.NetworkInfo mobile = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobile.isAvailable() && mobile.isConnected()) {
            Log.i(TAG, "Found Mobile Internet Network");
            val = true;
        } else {
            Log.e(TAG, "Mobile Internet Network not Found");
        }

        Log.d(TAG, "Checking for WI-FI Network");
        final android.net.NetworkInfo wifi = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifi.isAvailable() && wifi.isConnected()) {
            Log.i(TAG, "Found WI-FI Network");
            val = true;
        } else {
            Log.e(TAG, "WI-FI Network not Found");
        }

        return val;
    }
}

A:         // TODO Auto-generated method stub
        ConnectivityManager connMgr =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        final android.net.NetworkInfo mobile = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobile.isAvailable() && mobile.isConnected()) {
            Log.i(TAG, "Found Mobile Internet Network");
            val = true;
        }
        // Checks the user prefs and the network connection. Based on the result, decides
        // whether
        // to refresh the display or keep the current display.
        // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
        if (WIFI.equals(sPref) && networkInfo != null
                && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            // If device has its Wi-Fi connection, sets refreshDisplay
            // to true. This causes the display to be refreshed when the user
            // returns to the app.
            refreshDisplay = true;
            Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();

            // If the setting is ANY network and there is a network connection
            // (which by process of elimination would be mobile), sets refreshDisplay to true.
        }

}
        else if (ANY.equals(sPref) && networkInfo != null) {
            refreshDisplay = true;

            // Otherwise, the app can't download content--either because there is no network
            // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there
            // is no Wi-Fi connection.
            // Sets refreshDisplay to false.
        } else {
            refreshDisplay = false;
            Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
        }

A: We can use ConnectivityManager Class for any information related to network.
It also notifies applications when network connectivity changes. Get an instance  of this class by calling
The primary responsibilities of this class are to:
*

*Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)

*Send broadcast intents when network connectivity changes

*Attempt to "fail over" to another network when connectivity to a network
  is lost

*Provide an API that allows applications to query the coarse-grained or fine-grained
  state of the available networks

*Provide an API that allows applications to request and select networks for their data
  traffic

GetNetworkInfo function return status information about a particular network type.This method requires the caller to hold the permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

     /**
     * Checks the type of data connection that is currently available on the device.
     *
     * @return ConnectivityManager.TYPE_* as a type of internet connection on the
     *This method does not support multiple connected networks
     *             of the same type.
     * device. Returns -1 in case of error or none of
     * ConnectivityManager.TYPE_* is found.
     **/

--
public static int getDataConnectionType(Context ctx) {

        ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager != null && connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null) {
            if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()) {
                return ConnectivityManager.TYPE_MOBILE;
            } else if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
                return ConnectivityManager.TYPE_WIFI;
            } else
                return -1;
        } else
            return -1;
    }

A: public boolean isInternetAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) { // connected to the internet
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
            // connected to wifi
            return true;

        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            // connected to the mobile provider's data plan
            return true;
        }
    } else {
        // not connected to the internet
        return false;
    }
    return false;
}

A: in none of the code above i see a check for whether getNetworkInfo() returned null, which happens according to the docs when the requested network type is not supported. this suggests that on devices without 3g the app will crash with null pointer exception.


text:
Q: Kde Plasma Returning to Login Screen Each Time I'm a new arch user. I do know arch is for people who already know what they're doing but I'm here to learn (have good enough prior experience with ubuntu,fedora).
So I set arch up properly (partitioning, installing base system).
Then i went ahead and installed`
pacman -S xorg-server xorg-server-utils xorg-xinit

Then I went ahead and installed plasma using pacman (the entire packages).
everything was A-Ok until i started plasma using
systemctl start sddm.service

The plasma desktop started but whenever I entered my password, it keeps returning to the login screen. I don't know what went wrong, x11 is working as it should since well plasma started properly.
Did I miss something somewhere?
Here are extra details:
Using a BIOS/Mbr system
Using the nvidia drivers (370.X.X)
4GB Ddr3 ram
1 gb Nvidia Geforce (Don't remember which but it's new)
Intel i5 4th Gen proccessor


text:
Q: How do you manage .vcproj files in source control which are changed by multiple developers? We use Subversion as our source control system and store the VisualStudio project files (vcproj) in the source control system as is normal I think. With Subversion we don't use any form of file locking, so if two developers are working on the same project at the same time and both add files to the project, or change settings, the second one to commit has to merge the changes.
How do you merge these changes?
The vcproj files are just text files so it is possible to edit them by hand but they are not very amenable to hand editing, especially by junior developers.
The ways I can think of are

*

*Get the latest version from svn and re-add all local changes manually

*Edit the file by hand to resolve any conflicts from an automatic merge

*Implement some form of locking scheme to prevent simultaneous changes

*Have an agreement between developers so they do not make simultaneous changes

Currently we are using the first option of re-adding all changes manually but this is time consuming and I was wondering if there is a better way.
With source files the automatic merge feature works most of the time and we don't get  many conflicts.

A: I've found that option 2 (edit the files by hand) generally works fairly well, as long as you're using a good diff tool (I use WinMerge).  The main problem I've run into is that Visual Studio will sometimes reorder the file.  But, if you have a good diff/merge tool then it should be able to differentiate between changed content and moved content.  That can help a lot.

A: You might find Project: Merge or Tools for SLN file useful

A: This is a tough problem and I think a weakness in the Visual Studio architecture.  The way we found round it was to not have the proj files in source control at all and to have a build script that handled the configuration settings.
The alternative was very messy and we could not guarantee consistent builds or environments between developers.  This led to a huge number of downstream integration problems and eventually we took the draconian step of removing the project files from source control.
The developers environments could still become misaligned but it showed up when they tried to build things themselves.

A: Using TFS here, but I don't think it makes a difference.
We also don't lock, and sometimes have to deal with merging project files.  I've never found it to be that complex or much of an issue.  Rarely do we ever experience issues that can't be merged automatically, and the manual merge process is pretty much trivial.
There's only one caveat to this:  Check in often!  If you make major changes to the project structure and don't check them in immediately those changes can start compounding the complexity of later merges.  If I make a major change to the structure of a project, I usually give everybody a heads up.  I'll ask them all to check in their current work, and then take care of the merge myself.

A: I found this recently: http://www.codeproject.com/KB/macros/vcproj_formatter.aspx
If you run this tool on a vcproj file and on a modified version of it then you can merge them together easily with your favorite text merge tool, and in addition the result is a more compact pretty vcproj file.

A: Options 1 and 2 are not mutually exclusive - if the developer is junior level, let them use option 1 (re-get the project file and re-do the changes) if that's more comfortable for them.  For more senior developers, option 2 (merge using a merge tool) is perfectly fine.
I think this is a situation that currently has no magic bullet - sometimes merging is a pain.

A: We use a diff tool (WinMerge) to merge changes. The project files are (for the most part) really straight-forward XML. The key here, though, is that there never should be any surprises when merging, because good communication is part of the bed-rock of effective source control.
Simultaneous changes to the project are perfectly fine as long as people communicate.


text:
Q: How to DM everyone in a Discord server with discord.py? I am currently trying to get my bot to DM all members of a server when the command :dmall is sent, but it doesn't appear to work.
My code:
@bot.command()
@commands.is_owner()
async def dmall(ctx,*,message):
    for mem in ctx.guild.members:
        await ctx.message.delete()
        try:
            await mem.send(message)
            await ctx.send(f'Sent dm to: {mem.name}')
        except:
             print('User dm closed')

@dmall.error
async def dmall_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send('sorry comrade, you arent allowed to do that')

A: It's impossible to know for certain without a traceback, but this is likely erroring when you're unable to send a DM to a member. This can happen if the member has set their privacy settings not to allow DMs from the server's members or has the bot blocked.
You should remove the catch-all exception handler, which is bad practice, exhibited by this specific instance of inability to determine the actual specific issue, and check the traceback.


text:
Q: How to get public key in .cer or .crt formats I have created self-signed SSL certificate using OpenSSL as follow:
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365

This gave me certificate and private key in .pem file. I need to provide my public key to my clients in .cer or .crt format. Is there any way to get public key in .cer/.crt formats?
What I have already tried:
1. Generating public key in .pem format and trying to convert it to .cer or .crt [Didn't work]
To extract public key in .pem file [worked fine]:
`openssl x509 -pubkey -noout -in signer-cert.pem  > signer-public-key-test.pem`

To convert it from .pem for .cer format
openssl x509 -inform PEM -in signer-public-key-test.pem -outform DER -out signer-public-key-test.cer
I get this error:
unable to load certificate
140067363030680:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: TRUSTED CERTIFICATE

2. Converting my certificate to .cer (which I did fine) and trying to export public key using windows certificate export wizard as instructions given here
It didn't work either. I couldn't enable the option to export keys and the final output, when opened in notepad++ was garbage.
So my question is, is there any way to generate the certificate from scratch and have the public key in .cer or .crt file. OR generating the certificate in .pem format and later extracting public keys to .crt or .cer
Any help is deeply appreciated.

A: Since .cer and .crt usually mean "DER or PEM-DER X.509 certificate" I don't know what you mean by having the public key in that format.
If you mean you want a DER encoded SubjectPublicKeyInfo representing the public key, the second stage of your pipeline would be
openssl asn1parse -noout -out some.file

You can remove the intermediate with
openssl x509 -in signer-cert.pem -noout -pubkey |
    openssl asn1parse -noout -out signer-public-key-test.der

(Newline added to remove scrollbar)
Or, skip the certificate middleman altogether:
openssl rsa -in key.pem -pubout -outform der -out signer-public-key-test.der

Seems pretty weird that you want that particular format, though.


text:
Q: How to change the value of each pixel in an image in python? in order to make a filter for an image softwares change the value of pixels in an image .
when i tried this code
file = open("hey.jpg" , "rb") #opening file

x = file.read() #reading from file

for i in range(len(x)):
    print(x[i]) #cordinate of each pixel

file.close() #closing file

i knew it was ouputing the informations of each pixel by the output because no value was above 255 or lower then 0 .
example of ouput from my image:
240 -> R
255 -> G
0   -> B

i want to change the value for each one and save it in a new image
i tried the following code but it doesn't work
file = open("hey.jpg" , "rb") #opening file

x = file.read() #reading from file

file.close() #closing file

file = open("new.jpg" , "wb") #the new image

for i in range(len(x)): #writing the new data with filter

    if x[i] !=255: #pixels RGB cant be 256
        file.write(bytes(x[i] + 1)) #bytes because when doig write(x[i]+1) it gives mes an error that a bytee object is required not int
    else: #if it is 255 then do nothing
        file.write(bytes(x[i]))

file.close()#closing the new image

no need to read this:
PS:
windows 10 , python3.8 .
i tried to make everything simplified .
by doesn't work i mean that there was no errors but OS can't decode it and output an image
i don't want to use any third party library like PIL .
this code copy the binary data of an image and make a new one sucessfully .
file = open("hey.jpg" , "rb") #opening file

x = file.read() #reading from file

file.close() #closing file

file = open("new.jpg" , "wb")

file.write(x)

file.close()

A: i knew it was ouputing the informations of each pixel by the output because no value was above 255 or lower then 0
Cause of this behavior is different than being "informations of each pixel" - you did simply accessed individual bytes of your file and 1 byte value is always from 0x00 (inclusive) to 0xFF (inclusive). Result will be similar if you do this on file of other type (for example text one).
this code copy the binary data of an image and make a new one sucessfully .
Your code simply copied content of file into another file. Note that it will work regardless of file type.
i don't want to use any third party library like PIL
Do as you wish, but keep in mind that without "any third party library" you must implement processing of every image format yourself from scratch.

A: JPEG, PNG and most image file formats don't work like that. They have headers at the start with metadata in, like the date you took the picture, your camera model, your GPS coordinates, the image height, its width and copyright information. After that, they normally store the pixels in a heavily optimised, compressed format so you can't alter the pixels without first decompressing the data. You can then edit them and write them back, with new headers and recompressed. So you would be well advised to use a library.
If you really, really don't want to use a Python library, you could use ImageMagick (a command-line tool) in the Terminal to convert your image into pure RGB pixels. So, if your image is called input.jpg, you could run this in Terminal:
magick input.jpg -depth 8 RGB:pixels.dat

And then if your image was 640x480 pixels, your file called pixels.dat will just be exactly 640x480x3 bytes long with no headers or metadata or compression. You could then process this exactly as you initially envisaged. Afterwards, you could make it back into a JPEG or PNG with:
magick -depth 8 -size 640x480 RGB:pixels.dat output.jpg

Notice how you have to tell ImageMagick the height and width of the image for the return journey from RGB bytes to JPEG, because there is no header at the start of the file saying its height and width.


text:
Q: ISML to lit-html I'm having difficulties with rewriting ISML-Templates to lit-html.
e.g.
<isset name="Variable" value="${pdict.variable}" scope="page" />

How does the isml tag <isset> work for lit-html?

A: Lit-html speaks regular HTML. You can define any custom element you want, but <isset> is neither a standard nor a custom element. Meaning, <isset> element doesn't work with lit-html per-se, rather, lit-html takes your template and updates the DOM efficiently with it. If you have some other code on the page which is parsing the rendered <isset> elements, that's fine, you can use lit-html to render them.
lit-html will render nodes as you write them, although it will transform that self-closing tag to a normal tag.

(async function() {

  const { render, html } = await import("https://unpkg.com/lit?module");

  function issets(items) {
    return items.map(({ name, value }) => html`<isset name="${name}" value="${value}"/>`);
  }

  render(issets([
    { name: 'a', value: 1 },
    { name: 'b', value: 2 }
  ]), document.querySelector('output'));

  console.log(document.querySelector('output').innerHTML)

})();
<output></output>

Rendered output:
<!----><!----><isset name="a" value="1"></isset><!----><!----><isset name="b" value="2"></isset><!---->


text:
Q: In Sunshine (2007) what is this flashing face about? During watching of Sunshine (2007) I've noticed flashing face (approximately 49'39"), when crew members were moving on the Icarus I board:

What is it about?

A:
The flashing images were of the Icarus I crew members. While searching
  Icarus I, Searle comes across the photo of the crew members wearing
  Hawaiian shirts (similar to the photo of the Icarus II crew members,
  who were wearing Santa hats).
The similar photos of the two crews hint that what caused the Icarus I
  from accomplishing its mission is what is happening to the crew of the
  Icarus II.

Source: http://www.imdb.com/title/tt0448134/faq#.2.1.6


text:
Q: Selenium Nunit addin install exception I don't have enough rep to comment, so I am posting a question here. I read this question Get list of failing tests from Nunit. I am trying to implement the nunit addin, I used this code:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using NUnit.Core.Extensibility;

namespace NunitAddin
{
    [NUnitAddinAttribute(Type = ExtensionType.Core,
       Name = "addin",
       Description = "addin")]
    public class NunitAddin : IAddin
    {
        public bool Install(IExtensionHost host)
        {
            IExtensionPoint listeners = host.GetExtensionPoint("EventListeners");
            if (listeners == null)
                return false;

            listeners.Install(this);
            return true;
        }
        public void TestStarted(NUnit.Core.TestName testName)
        {
        }

        public void TestFinished(NUnit.Core.TestResult result)
        {

        }
        public void RunStarted(NUnit.Core.TestName testName)
        {
        }

        public void RunFinished(NUnit.Core.TestResult result)
        {
        }

        public void UnhandledException(Exception exception)
        {
        }

        public void TestOutput(NUnit.Core.TestOutput testOutput)
        {
        }

    }
}

But when I call it using
var addin = new NunitAddin.NunitAddin();
var a = addin.Install(CoreExtensions.Host);

I get an error

NunitAddin.NunitAddin is not {0} extension point

on
 listeners.Install(this);

Does anyone know how to solve this problem?

A: Never mind, issue solved. Just a stupid mistake, I had NunitAddin : IAddin instead of NunitAddin : IAddin; EventListener


text:
Q: How to call javascript function on click of button in ribbon I have a button in the ribbon. It has got ID.
I tried like
var mybtn= document.getElementById('btnId');
mybtn.onclick=myfun;

function myfun()
{
 ---------
 ---------
}

But it didnt work. Please suggest.

A: Try this.
jQuery("#btnId").click(function(){

myfun();

});

function myfun()
{
    //Here is your code...
}

A: *

*Simplest method is to add a mouse event onclick="myfun()" into element that has id: "btnId"

*By using jQuery:
$("#btnId").click(function(){
        //do the code here
 });


text:
Q: How can I log which processes create handles to a specific file? I am aware of Sysinternals Process Explorer which gives me a list processes having a handle to a specific file. But procexp.exe is not the right tool, as I think it might miss transient processes. Also there is no logging option.
So to keep it short: How can I log/monitor which processes are accessing a file over a period of time (e.g. 2 weeks)?


text:
Q: How to get email Id of authenticated user? My azure web app is authenticated by Microsoft Account login. I enabled it through Azure portal with changing authentication/authorization settings of web app.This does not need any change in web app code. And authentication part is working fine.
Now I want the email Id of the user who gets authenticated before accessing the web app.
I tried to read User.Identity as System.Security.Claims.ClaimsPrincipal. But this is coming as null.
How to access the email Id of authenticated user?

A: Go to your webapp and click Authentication / Authorization.Under Authentication providers, click on Microsoft Account. Click on wl.basic & wl.emails to enable them.

Then go to ExternalLoginCallback and add the following code:
var identity = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
var emailClaim = identity.Identity.FindFirst(ClaimTypes.Email);
var email = emailClaim.Value;

The code result:

A: I am now able to get authenticated user email, even though my asp.net mvc app was initially "No Authentication" app. I enabled MS authentication from the Azure portal for my web app. Now I fetch user email from System.Security.Claims.ClaimsPrincipal.Current.Claims object. It is automatically set by MS authentication flow.


text:
Q: Sql count : taking count of rows joining 2 tables Lets say i have 2 tables Master and slave .
Master table contains master_name and master_id , Slave table has Slave_id, slave_name and master_id.
sample data.
master_id Master_name  Master_status      slave_id  slave_name  master_id status
1         x               online              1          a          1       online
2         y               online              2          b          1       online
3         z               offline             3          c          2       offline
                                              4          d          3       offline
                                              5          e          3       online

the expected result i m trying to obtain is,
master_id  no_of_slave
   1             2
   2             0

i want to get the no: of online slaves each online masters have.
sorry for the late edit.

A: Use LEFT JOIN like this one:
SELECT m.master_id
     , count(s.slave_id) AS no_of_slave
FROM master m
LEFT JOIN slave s
     ON m.master_id = s.master_id
GROUP BY m.master_id;

Result:
╔═══════════╦═════════════╗
║ MASTER_ID ║ NO_OF_SLAVE ║
╠═══════════╬═════════════╣
║         1 ║           2 ║
║         2 ║           1 ║
║         3 ║           2 ║
╚═══════════╩═════════════╝

See this SQLFiddle

A: Use the below query:
Select m.master_id, count(s.master_id) as no_of_slave
       FROM master m
            JOIN slave s
            ON m.master_id = s.master_id
            GROUP By m.master_id;

A: select
    a.master_id,
    count(b.slave_id)
from
    master a,
    slave b
where
     a.master_id=b.master_id
group by
     a.master_id

A: select    master_id, count(1)
from      Slave
group by  master_id
order by  master_id

will just give you masters that have slaves, and you don't even need to join with master if tables are big

A: You can use this. This will work.
select m.master_id,(select count(*) from slave s where s.master_id = m.master_id) as no_of_slave from master m

A:   SELECT master_id, count(*) AS no_of_slave
    FROM slave
GROUP BY master_id
ORDER BY master_id;

A: You're not interested in master names so a join is not required, you have all necessary info in the Slave table:
select master_id, count(slave_id) as no_of_slave
from Slave
group by master_id
order by master_id --remove this line, if ordering of master ids is not important
;

If a given master id is not in this result, this means it has no slaves.


text:
Q: JQuery - Iterate through textboxes and save values to Javascript object I have a button when clicked it iterates through some html elements by class and saves the value to a javascript object. There are 5 html elements per row. How can I save the value of each rows textbox to a corresponding key in the javascript object. The javascript object has the following keys Qty, Length, Breadth, Height, Mass, Description

$.each($('.myClass'), function(index, value) {
  var obj = {
    "Qty": $(this).val(),
    "Length": $(this).val(),
    "Breadth": $(this).val(),
    "Height": $(this).val(),
    "Mass": $(this).val(),
    "Description": $(this).val(),
    "VolWeight": ""
  };
  console.log(obj);
});

    @*<input id="txtQty" class="form-control" placeholder="Quantity" type="text" value="1" />*@

      <input type="number" class="js-result form-control input-group-quantity-counter-control myClass" value="1" id="txtQty4" data-rule-digits="true">

    @*<input id="txtLength" class="form-control" placeholder="Length (cm)" type="number" value="1" />*@

      <input type="number" class="js-result form-control input-group-quantity-counter-control myClass" value="1" id="txtLength4" data-rule-digits="true" max="600" data-msg="Max length 600cm">

    @*<input id="txtBreadth" class="form-control" placeholder="Breath (cm)" type="number" value="1" />*@

      <input type="number" class="js-result form-control input-group-quantity-counter-control myClass" value="1" id="txtBreadth4" data-rule-digits="true" max="250" data-msg="Max length 250cm">

    @*<input id="txtHeight" class="form-control" placeholder="Height (cm)" type="number" value="1" />*@

      <input type="number" class="js-result form-control input-group-quantity-counter-control myClass" value="1" id="txtHeight4" data-rule-digits="true" max="250" data-msg="Max length 250cm">

    @*<input id="txtMass" class="form-control" placeholder="Mass (kg)" type="number" value="1" />*@

      <input type="number" class="js-result form-control input-group-quantity-counter-control myClass" value="1" id="txtMass4" data-rule-digits="true">

    <select class="js-select2-custom custom-select myClass" size="1" id="txtDescription4" style="opacity: 0;" data-hs-select2-options='{ "minimumResultsForSearch": "Infinity","placeholder": "Load Type" }'>
      <option value="Boxes">Boxes</option>
      <option value="Envelop">Envelop</option>
      <option value="Pallet">Pallet</option>
    </select>

A: You need an object per row, not an object per input.
Loop over the rows and create a new object for each row instance, then loop over the inputs in that row to set the key/values. A name on each input will help for the keys
Following uses map() to return an array of objects

const res = $('.row').map(function(){
    // object for this row
    const obj = {};
    // loop over relevant inputs in this row
    $(this).find('input.myClass').each(function(i,el){
         // set key/value of object for this input
         obj[el.name] = el.value;
    })
    return obj
}).get()

console.log(res)

 Qty <input name="Qty" type="text" class="myClass" value="3">
 Length  <input name="Length" type="text" class="myClass" value="4">

 Qty <input name="Qty" type="text" class="myClass" value="5">
 Length  <input name="Length" type="text" class="myClass" value="6">


text:
Q: React-google-maps render directions I am working with the react-google-maps package https://github.com/tomchentw/react-google-maps to make a request to the google maps javascript API directions service https://developers.google.com/maps/documentation/javascript/examples/directions-simple. I am getting the response back from the API as expected and can log it to the browser but I can not figure out how to get the polyline to render in the map component.
This line of code
   directionsDisplay.setMap(map);
was returning an error  of

"InvalidValueError: setMap: not an instance of Map  directions".

So I commented it out because it seems that the map is set by passing the handleMapLoad() to the GoogleMap component through refs. Some guidance on how to display the polyline would be much appreciated.
    /*global google*/
    import React, { Component } from "react";
    import { withGoogleMap, GoogleMap } from "react-google-maps";

    const GettingStartedGoogleMap = withGoogleMap(props => (
      <GoogleMap
        ref={props.onMapLoad}
        defaultZoom={5}
        defaultCenter={{lat: 41.85, lng: -117.65}}
      >
      </GoogleMap>
    ));

    export default class GettingStartedExample extends Component {
      handleMapLoad = this.handleMapLoad.bind(this);

      handleMapLoad(map) {
        this.mapComponent = map;
        if (map) {
          console.log(map.getZoom());
        }
        const directionsService = new google.maps.DirectionsService();
        const directionsDisplay = new google.maps.DirectionsRenderer();

        // directionsDisplay.setMap(map);

        const makeRequest = function() {
          calculateAndDisplayRoute(directionsService, directionsDisplay);
        };
        function calculateAndDisplayRoute(directionsService, directionsDisplay) {
           directionsService.route({
             origin: 'San Francisco',
             destination: 'Portland',
             travelMode: 'DRIVING'
          }, function(response, status) {
            if (status === 'OK') {
              directionsDisplay.setDirections(response);
              console.log(response)
            } else {
              window.alert('Directions request failed due to ' + status);
            }
          });
        }
        makeRequest();
      }
      render() {
        return (
          <div style={{height: `500px`}}>
            <GettingStartedGoogleMap
              containerElement={<div style={{ height: `100%` }} />}
              mapElement={<div style={{ height: `100%` }} />}
              onMapLoad={this.handleMapLoad}
            />

         );
       }
     }

A: You can use react-google-maps Polyline component to render direction. It gives us additional styling prop options. It is a way better approach than using the DirectionRender component. Here are the steps you must follow to render directions as Polyline on your Google Map:

*

*Use google maps direction service and extract overview_path from it like this;
overview_path is an array of objects containing Lat and Lng.

...
DirectionsService.route({
   origin: 'San Francisco',
   destination: 'Portland',
   travelMode: google.maps.TravelMode.DRIVING,
  },
    (result, status) => {
      if (status === google.maps.DirectionsStatus.OK) {
        const overViewCoords = result.routes[0].overview_path;
          this.setState({
            lineCoordinates: overViewCoords,
          });
      } else {
         console.warn(`error fetching directions ${status}`);
      }
    });

*

*Then pass these coordinates as the path prop of the <Polyline /> Component;

...
<GoogleMap
    ref={props.onMapLoad}
    defaultZoom={5}
    defaultCenter={{lat: 41.85, lng: -117.65}}
  >
  <Polyline
        path={this.state.lineCoordinates}
        geodesic={false}
        options={{
            strokeColor: '#38B44F',
            strokeOpacity: 1,
            strokeWeight: 7,
        }}
    />
</GoogleMap>

PS. import Polyline from react-google-maps first:
import { Polyline } from 'react-google-maps';

A: A very simple and direct way to render directions in React using waypoints too
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { withScriptjs } from "react-google-maps";

import  Map from './components/Map';

function App() {

  const MapLoader = withScriptjs(Map);

  return (

  <MapLoader
      googleMapURL="https://maps.googleapis.com/maps/api/js?key=Key"
      loadingElement={<div style={{ height: `100%` }} />}
  />

  );
}

export default App;

And in your Map.js file
/*global google*/
import React, { Component } from "react";
import {
    withGoogleMap,
    withScriptjs,
    GoogleMap,
    DirectionsRenderer
} from "react-google-maps";
class Map extends Component {
    state = {
        directions: null,

};

componentDidMount() {
    const directionsService = new google.maps.DirectionsService();

    const origin = { lat: 6.5244, lng:  3.3792 };
    const destination = { lat: 6.4667, lng:  3.4500};

    directionsService.route(
        {
            origin: origin,
            destination: destination,
            travelMode: google.maps.TravelMode.DRIVING,
            waypoints: [
                {
                    location: new google.maps.LatLng(6.4698,  3.5852)
                },
                {
                    location: new google.maps.LatLng(6.6018,3.3515)
                }
            ]
        },
        (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                console.log(result)
                this.setState({
                    directions: result
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        }
    );
}

render() {
    const GoogleMapExample = withGoogleMap(props => (
        <GoogleMap
            defaultCenter={{ lat: 6.5244, lng:  3.3792 }}
            defaultZoom={13}
        >
            <DirectionsRenderer
                directions={this.state.directions}
            />
        </GoogleMap>
    ));

    return (

            <GoogleMapExample
                containerElement={<div style={{ height: `500px`, width: "500px" }} />}
                mapElement={<div style={{ height: `100%` }} />}
            />

       );
    }
}

export default Map;


text:
Q: Android drawBitmap paint i am trying to show bullets when the user touched the screen
i am making the bullet here
public Projectile(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        paint = new Paint();
        bulletBitmap = BitmapFactory.decodeResource(context.getResources(),
                                                    R.drawable.bullet);
    }

    public interface ProjectileListener {
        public void onProjectileChanged(float delta, float angle);
    }

    public void setProjectileListener(ProjectileListener l) {
        listener = l;
    }

    public void setProjectileDirection(int x, int y, int size){
        pos = new Rect(x, y, size, size);
        invalidate();
    }

    protected void onDraw(Canvas c) {
        c.drawBitmap(bulletBitmap, pos, pos, paint);
        super.onDraw(c);
    }

and call it here
Projectile p = new Projectile(TowerAnimation.this);
                        p.setProjectileDirection(x, y, 50);
                        projectiles.add(p);
                        Canvas c = null;
                        p.onDraw(c);

however i am getting errors on this line
c.drawBitmap(bulletBitmap, pos, pos, paint);

did i make anything wrong with the drawBitmap?
thanks

A: In the following code:
Projectile p = new Projectile(TowerAnimation.this);
                    p.setProjectileDirection(x, y, 50);
                    projectiles.add(p);
                    Canvas c = null;    <------------------ here
                    p.onDraw(c);        <------------------ NPE

You are setting c to null and passing it to onDraw(). This is what's happening in your onDraw():
protected void onDraw(Canvas c) {
    null.drawBitmap(bulletBitmap, pos, pos, paint);    <--------- NPE
    super.onDraw(c);
}

Edit 1:
I'm not sure what you are trying to do with your code. Check the class BulletsOnScreen. To use it, you will need to add it as a View to some layout. For example, If you have a LinearLayout, you can use the addView() method:
myLinearLayout.addView(new BulletsOnScreen(this));

public class BulletsOnScreen extends View {

    Bitmap bullet;

    boolean touched;

    float xValue, yValue;

    public BulletsOnScreen(Context context) {

        super(context);

        setFocusable(true);

        bullet = BitmapFactory.decodeResource(context.getResources(),
                                                R.drawable.bullet);

        touched = false;

    }

    protected void onDraw(Canvas canvas) {

        if (touched) {

            canvas.drawBitmap(bullet, xValue,
            yValue, null);

            touched = false;

        }
    }

    public boolean onTouchEvent(MotionEvent event) {

    xValue = event.getX();
    yValue = event.getY();

            touched = true;
            invalidate();
    }


text:
Q: Layout Plugin Admin Pages: Use BootStrap? When you make your plugin admin pages, ie 'My Plugin Settings' page and etc. do you use bootstrap in them?
What is the convention for this and what do most in the industry use to lay out their plugin admin pages?
I am considering using it simply to use rows and columns so the layout is responsive. But maybe WordPress has its own existing classes? If thats the case I want to use that because I want to maintain standards and consistency with other plugins.
Any advice on what you use in plugins for layout and what is the standard?
*Edit: I can successfully import the BootStrap js css files but they change the whole dashboards styling - even for other pages like 'Add New Page' and other plugins settings pages. Is there any way to stop this? Other than going through the Bootstrap CSS file and removing everything related to body, etc.?

A: Wordpress has a Settings API that allows you to register and create default admin-style inputs. It also takes care of loading and saving these settings in your database. The API is fairly verbose, but its documentation covers everything you need to know about it.
If you value sticking to the WP standards/conventions, I would suggest using it instead of injecting foreign CSS (even if it is something as widely used as bootstrap) and possibly messing up unexpected parts of your admin panel.
If you need more control over the way your admin page looks, just hand-craft those few lines of CSS or copy them over from bootstrap if you feel really lazy.

A: I have manage that this way and it seems it's gonna work. I have just use again the scripts that I have used for theme to save some memory on server.
/*
 *  Bootstrap Styles and scripts
 */
wp_register_style( 'bootstrap.min', 'http://domain.cz/wp-content/themes/theme-name/css/bootstrap.min.css' );
wp_enqueue_style('bootstrap.min');
//Bootstrap Scripts
wp_register_script( 'bootstrap.min', 'http://domain.cz/wp-content/themes/theme-name/js/bootstrap.min.js' );
wp_enqueue_script('bootstrap.min');
//Google Jquery
wp_register_script( 'jquery.min', 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js' );
wp_enqueue_script('jquery.min');

A: I used less to wrap Bootstrap css within custom div bootstrap-wrapper:
1 - Download Bootstrap Source from the download page, and extract.
2 - Inside bootstrap-3.3.7/less/ folder, create bootstrap-wrapper.less, and add the following code:
.bootstrap-wrapper {
    @import "bootstrap.less";
}

3 - Install less: npm install -g less
4 - From terminal, compile less files to get the css file:
cd bootstrap-3.3.7/less/
lessc bootstrap-wrapper.less bootstrap-wrapper.css

5 - Copy the file to your WordPress plugin (or theme), and enqueue it:
wp_enqueue_style('csbk_bs_css', plugins_url( '/css/bootstrap-wrapper.css', __FILE__ ));

6 - Inside your plugin page:
<div class="bootstrap-wrapper">
    <button class="btn btn-primary">Click me</button>
</div>

Reference: Using Bootstrap in Wordpress Admin Panel


text:
Q: 'Add Foreign Key Property to..' checkbox disabled for 0..1 to 1 relationships On the model-first approach in the designer, if I create a relationship where the cardinality on one end of the relationship is '0..1' and '1' on the other, the designer disables the 'Add Foreign Key Property to..' checkbox.
For example, say that I had an Order entity and an OrderQuantity entity, where the OrderQuantity entity simply stipulates the initial amount of Order entities available, but doesn't have to be specified. Thus an Order can have 0 or 1 OrderQuantity, and an OrderQuantity will always have 1 Order.
The same applies if I am trying to make an entity refer to previous and newer versions of itself (i.e. a node in a list).
Defining this relationship, the designer will not allow me to add foreign key properties at all, and I have to rely on the navigation methods (which are generated fine).
Has anyone else experienced this?

A: change the target framework of your solution to. .Net Framework 4.0


text:
Q: Why a parameter of an Emacs lisp function is not evaluated? I want to define a list of accumulators with Emacs Lisp and write the following code, but I got a error saying that initV is a void variable. It seems initV is not evaluated in the function define-accum. Where is I make a mistake? (I just want to know why although I know there is other ways to reach my target.)
(defun define-accum (name initV)
  (defalias name (lambda (v) (+ v initV))))

(setq accums '((myadd1 . 1)
               (myadd2 . 2)))

(dolist (a accums)
  (define-accum (car a) (cdr a)))

(message "result = %d" (+ (myadd1 1) (myadd2 1)))

A: You need to use backquotes properly.  This would work for you, for instance:
(defun define-accum (name initV)
  (defalias name `(lambda (v) (+ v ,initV))))

See here for an explanation

A: Apart from using backquotes, you can activate lexical binding (if you're using Emacs 24 or newer).  For example, if I put your code in a .el file and put this on the first line:
;; -*- lexical-binding: t -*-

then I get the output:
result = 5

This works because the lambda function in define-accum will reference the initV in the environment where it's being defined (thus picking the variable in the argument list), and create a closure over this variable.  With dynamic binding (the default), the function would look for initV in the environment where it's being called.

A: To add a little to what others have said -

*

*If the variable (initV) is never actually used as a variable, so that in fact its value at the time the accumulator is defined is all that is needed, then there is no need for the lexical closure that encapsulates that variable and its value.  In that case, the approach described by @juanleon is sufficient: it uses only the value at definition time - the variable does not exist when the function is invoked (as you discovered).

*On the other hand, the lexical-closure approach lets the function be byte-compiled.  In the backquote approach, the function is simply represented at runtime by a list that represents a lambda form.  If the lambda form represents costly code then it can make sense to use the lexical-closure approach, even though (in this case) the variable is not really needed (as a variable).

*But you can always explicitly byte-compile the function (e.g. ##NAME## in your define-accum.  That will take care of the inefficiency mentioned in #2, above.


text:
Q: ECMAScript: What does `status` mean in Syntax-Directed Operations? In https://tc39.es/ecma262/#sec-algorithm-conventions-syntax-directed-operations, There is a description like this

Syntax-directed operations are invoked with a parse node and, optionally, other parameters by using the conventions on steps 1, 3, and 4 in the following algorithm:

*

*Let status be SyntaxDirectedOperation of SomeNonTerminal.

*Let someParseNode be the parse of some source text.

*Perform SyntaxDirectedOperation of someParseNode.

*Perform SyntaxDirectedOperation of someParseNode with argument "value".

*

*What does status in this algorithm mean? It's not used in the algorithm anymore.

*What does the algorithm mean? It seems weird.

A: That's just an example, it's not a real algorithm, and it's not necessarily a complete example (hence not using status after the first step). For a real algorithm, look at the section containing actual Syntax-Directed Operations, such as function name inference:

8.4.1 Static Semantics: HasName
...

*

*Let expr be the ParenthesizedExpression that is covered by CoverParenthesizedExpressionAndArrowParameterList.

*If IsFunctionDefinition of expr is false, return false.

*Return HasName of expr.

The status in the example is like expr in the above, a temporary variable (if you will) for the algorithm. It's just that the example doesn't use status again (it probably should, it would be a better example).

A:
What does status in this algorithm mean?

It's just a variable introduced by that step, like in any other "Let x be …".

What does the algorithm mean? It seems weird.

It means nothing. It's an example algorithm in the "algorithm conventions" section explaining how algorithm steps are meant to be understood in the rest of the spec.


text:
Q: How to save current user data using react-redux? I create simple MERN app. I use passport in authentication.   I have home, login, register secret and submit page have. only loginned users can see secret , home and submit pages and only not loginned users can see login and register page. I send data using axios backend. User login,register was succesfully but after loginned users get user data many time after. I dont know how to fix this. My backend doesnt have error. It work well.
--------------  Secret page --------------
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Redirect } from "react-router";
import { user_ } from "../actions/register_action";

const Secret =  ()=>{
    const dispatch = useDispatch();

    const user = useSelector( state => state.user );

    useEffect( ()=>{
       dispatch( user_ );
    },[] );

    console.log(user);

    if(user === null) return <Redirect to = "/login" />
    else
    return (

You've Discovered My Secret!

Jack Bauer is my hero.

                Log Out
                Submit a Secret

    );
}
export default Secret;

--------------  actions --------------
import { fail, user, USER_LOGIN_FAIL, USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS,
     USER_REGISTER_FAIL, USER_REGISTER_REQUEST, USER_REGISTER_SUCCESS
     } from "../constants/all";
import axios from "axios";

const user_Register = (email, password) => async (dispatch) =>{
    dispatch({ type: USER_REGISTER_REQUEST });
    try {
        const {data} = await axios( {
            method: "POST",
            data: {
                "username": email,
                "password": password
            },
            withCredentials: true,
            url: "http://localhost:3001/register"
        });

        dispatch({ type: USER_REGISTER_SUCCESS, payload: data });

    } catch (error) {
        dispatch({type: USER_REGISTER_FAIL, error: error.message});
    }
}

const user_Login = (email, password) => async (dispatch) =>{
    dispatch({ type: USER_LOGIN_REQUEST });
    try {
        const {data} = await axios( {
            method: "POST",
            data: {
                username: email,
                password: password
            },
            withCredentials: true,
            url: "http://localhost:3001/login"
        });
        dispatch({ type: USER_LOGIN_SUCCESS, payload: data });

    } catch (error) {
        dispatch({type: USER_LOGIN_FAIL, error: error.message});
    }
}

const user_ = async (dispatch) => {
    try{
        const {data} = await axios({
            method: "GET",
            withCredentials: true,
            url: 'http://localhost:3001'
        });
        if(data.isAuth){
            dispatch({type:user, payload:data});
        }
        else{
            dispatch({type: fail});
        }
    }
    catch (error){

    }
}

export {user_Register, user_Login, user_};

Who have better idea? Thanks a lot!

A: Can you try re-writing your user_ action creator to be a function that returns a function:
const user_ = () => async (dispatch) => {
  try {
    const { data } = await axios({
      method: "GET",
      withCredentials: true,
      url: "http://localhost:3001",
    });
    if (data.isAuth) {
      dispatch({ type: user, payload: data });
    } else {
      dispatch({ type: fail });
    }
  } catch (error) {}
};

And then in your Secret component's useEffect, call the user_ action creator to create the action:
useEffect(() => {
  dispatch(user_());
}, []);

I'm not positive this is the issue, but it does seem like something that should be done either way.