text:
Q: Spotfire : Syntax issue or Window functions not allowed? I am using Data functions in Spotfire.
I have the sqldf package installed.
Here is the query:
#Package to run sqls
library(sqldf)
#Input data frame
op1 <- sqldf("SELECT Prod_parnt,prodct_grop,year,month,week,
count(distinct id) as prd_cnt,
Sum(Count(distinct id))
over (partition by modlty,prodct_grop order by year,month,week
rows between 12 preceding and current row) as cumu_prd_cnt,
avg(rate) as sal_rate
FROM ip1
group by Prod_parnt,prodct_grop,year,month,week")

The error I am facing:
"TIBCO Spotfire Statistics Services returned an error: 'Error: error in statement: near "(": syntax error'."
Now the point to note here is that when I remove the Window function statement i.e cumu_prd_cnt field; the code works fine.
Need your help.


text:
Q: Ionic 3 page reference in app.component I have recently upgraded to ionic 3 implementing the IonicPageModule for navigation. The push and setRoot works for all navigating however i am stuck at the trying to reference the pages in the app.component.ts
Normally i would reference the page from the import like so
this.rootPage = user ? ProgramsPage : LoginPage;

Where LoginPage and ProgramPage are declared in the app.module.ts
However in the new angular 4 / ionic 3 setup references to the "pages" are referenced with strings without an import in the related page.ts and seemly integrated with the navCtrl's push and set
I have tried
import { LoginPageModule } from '../pages/login/login.module';

But that does not make sense.
I figured the whole point of creating modules per page was to firstly enalble lazy loading but also minimize the import code on pages without having to create a config export class.
And the thing is you cannot declare the LoginPage twice and seeing as though it is already declared as a module through the IonicPageModule one cannot add that export class again.
So just wondering how do you reference a ionic 3 page module when you want to apply logic?

A: I came across an article that implemented close to what you really wanted; though it talked more about cloud functions but at the beginning it tried to solve your  problem in a very fashionable way. Take a look https://javebratt.com/firebase-cloud-functions-profile/

A: if your pages are being declared as:
/* imports and stuff here ... */

@IonicPage()
@Component({
  selector: 'page-user',
  templateUrl: 'user.html'
})
export class UserPage { /* constructor, your code & else ... */ }

or generated using the ionic-cli by running: ionic g page NewAppPage
you will be able to use the string page name instead of using the page object (that also requires you to import the page).
Take a look at https://www.javascripttuts.com/ionic-3-new-pages-lazy-loading/ , it may help you understand a little bit more about lazy loading and pages inside the app component.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why return value of some methods such as: add(E), remove(Object), addAll,... is boolean in Collection FrameWork? I'm a stupid student. I have a question that is the title.
I think when I do this, return boolean or not has no affect on me:
List<String> lst = new ArrayList<String>();
lst.add("whatever");
lst.remove("whatever");

And here is remove method(Which overrides from Collection< E > interface) of Arraylist Class in the API:
public boolean remove(Object o) {
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
}

I think if in Collection< E > interface, designers of the framework write public void remove(Object o); is ok but they have to have a certain purpose and I don't understand. Return boolean for what? Please tell me

A: In the case of remove:
It exactly tells you whether any object was removed from your collection or it wasn't.
In the case of add:
It's helpful in collections like Set, because it returns true if a new element added to the set, and it returns false, if the object is already in the collection.
From HashSet:
public boolean add(E e) {
    return (this.map.put(e, PRESENT) == null);
  }

A: At times, the client code might not know if the object to be removed is part of the collection. This client code would certainly like to know the effect of the remove operation. Hence, the design decision to return a boolean.
-- edit
For example,
Suppose, a synchronized collection is shared between two threads. One populates it and the other removes objects from it. The removing thread would like to know if the removal was successful.

A: remove(o) return false if o was not found in the collection.


text:
Q: Is BroadcastReceiver asynchronous enough to make this work Wanted to stop a thread doing some downloads.
The code below work fine when i only have the stopNow = true; and no blocking occur.
I create the boolean stopNow = false; as a field in my IntentService.
Since stopNow only work when the connection is ongoing in the while loop
but it does not work if f.ex connection stales and start to block.
I wanted to add this code to really stop the blocking.
if(socket != null){
    socket.shutdownOutput();
    socket.shutdownInput();
}

The question is if this is asynchronous so if the execution is ongoing in the
while loop the stopNow = true; will stop it and i can put a sleep(5000) after the stopNow = true;  and then the if(socket != null) will be true only if the stopNow had no effect.
hope you follow me..
BroadcastReceiver  that are located inside the run():
private class MyIncomingListener extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent.getAction().equals(Consts.COM_CARLSBERG_STOPOUTGOING)) {
            String b = intent.getStringExtra(Consts.COM_CARLSBERG_BATCHUUID);
            if(b != null){
                if(b.equals(batch.batchUuid)){
                    stopNow = true;
                    // sleep(5000) wait for stopNow to take effect
                    // if socket=null then stopNow did it's job
                    // if socket is alive then there is blocking to unblock
                try{
                    if(socket != null){
                        socket.shutdownOutput();
                        socket.shutdownInput();
                    }
                } catch (Exception e) {}
               }
            }
        }
    }
}

A: this is actually working good so far
    stopNow = true;

try{
    if(socket != null){
        socket.shutdownOutput();
        socket.shutdownInput();
    }
} catch (Exception e) {}

A:

public final void stop ()
Since: API Level 1
This method is deprecated.
because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.

Requests the receiver Thread to stop and throw ThreadDeath. The Thread is resumed if it was suspended and awakened if it was sleeping, so that it can proceed to throw ThreadDeath.

 try {
                     int waited = 0;
                     while(_active && (waited < _splashTime)) {
                         sleep(100);
                         if(_active) {
                             waited += 100;
                         }
                     }
                 } catch(InterruptedException e) {
                     // do nothing
                 } finally {
                     finish();
                     Intent intent= new Intent(SplashActivity.this,LoginViewController.class);
                     startActivity(intent);

                     stop();
                 }


text:
Q: Blocking HTML and Javascript from being displayed on my site I am working on this new social networking site. One of it's various functions is posting. You can post to Facebook and my site, or Twitter and my site. That being said, I couldn't help but try and post HTML as I was testing sql injection. When I did, I noticed that there where ways to manipulate the site to, for instance, using a  element to completely screw up the CSS design, or redirect a user to another site using javascript. That being said, I want to make my site a safe environment for my users... not a site that is used to distribute computer viruses, porn, and other things that might make someone tend to stay off of my site. When I searched this topic, I found ways to "strip" the HTML out of the $post variable before submitting it to the database. However, I would just like to make it so you can post any text, including HTML and Javascript, without the browser interpreting it as "run this..." code: I want to display it as plane text. I've seen it on Facebook, and when I looked at it the source code of a post, it showed <, /, and > as regular text. I tried "dissecting" Facebook's source code, but found nothing. I have tried using tags such as
 and , but because of the lack of ability to style and control them, I gave up and went back to just allowing HTML. Please, anyone who knows how to do this, please help me out.
Thanks in advance,
TP

A: There's a function to "escape" html special characters. This will change

Some dangerous html

Into:
<p>Some dangerous html</p>
<script>window.location.replace('http://pornography.com');</script>

Which the browser will display as plain text (i.e.
Some ...).
Incidentally, this is will have happened to the text in this very post. Which is probably for the best.

A: You could use the function strip_tags() to filter the input. If you see that the text has changed then it means the users tries to enter html data. You either reject the input or you keep the filtered version.

A: I guess what you want is just removing links and javascript. You can do it with regular expressions
Regular expression for parsing links from a webpage?
php regular expressions resources

A: To show the < and > etc. as text, use
$output = htmlentities($string, ENT_QUOTES);

This will ensure any html code is displayed as text and not as pure html.
http://php.net/manual/en/function.htmlentities.php


text:
Q: Tension In circular motion In the below question is given 2 scenarios in which we have to find the tension in two particular cases, A ball is held at rest in position A by two light cords.the horizontal cord is now cut  and the ball swings to the position B . what is the ratio of the tension in the cord in position B to that in position A ?

Now I can understand what the solutions says at A but at point B, it balances $T=Mgcosx$ for some reason, now shouldn't it be $Tcosx=mg$ because when u balance T in that direction at point B there is also a centrifugal force outwards which is not perpendicular to this, whilst when we balance the vertical component of tension, the centrifugal force is perpendicular to it and hence has no components.

A: I may be misunderstanding your question but I still may be able to assist so here goes, and this is my first ever answer on this site, so please forgive me if I either tell you how to suck eggs, or express things in terms unfamiliar.
Here goes:
When the ball moves to the right and reaches zero velocity, there are two forces at work, and the system is not in equilibrium.
One force is due to gravity = $Mg$ (straight down).
The other force is due to the string. By virtue of the definition of a string is that the length of the string cannot change, then when working the vector diagram there can be no component of the resultant force in the direction of the string, i.e. the resultant force must be purely perpendicular (at right angles) to the string. This is how the ball will move, again, the system is not in equilibrium.
As such, the resultant force and the string tension force must form a right angle triangle, with the Gravity force Mg as the hypotenuse. From there you can see that the relationship between the Gravity force Mg and the string Tension T are defined by their adjacency to angle $x$ in the form $ T=Mg cos (x)$.
To come at this from the other angle, what if the answer were indeed  $ T cos (x) = Mg$?
This would mean on our free body diagram the spring tension would instead be the hypotenuse, with gravity and the resultant force (accelerating the ball) as the right angle triangles.
If you were to draw this, you would quickly notice that the resultant force would have a component parallel to the string. As such the resultant acceleration of the ball act to slacken the string, even though gravity was the force making it accelerate - this is a contradiction obviously.
I hope this has helped in some way; happy to answer any further questions.


text:
Q: MYSQL statement can't figure out whats wrong I have created this join statement for a student schedule printout, i am new to sql and php and cannot figure out what i have done incorrectly. If anyone could help i would greatly appreciate it.. Thanks in advance...(p.s. i am sorry if this is a really basic question)...
mysql_select_db($database_newconn, $newconn);
$query_Recordset1 = "SELECT a.student_id AS "Student ID", f.name AS "Course Name", g.name AS "Lesson Name", g.date AS "Lesson Date", g.start_time AS "Lesson Start Time", g.end_time AS "Lesson End Time", CONCAT( h.first_name,' ', h.last_name) AS "Lesson Tutor" FROM student_table a JOIN enrollement_schedule_table b ON(a.id = b.student_id) JOIN course_table f ON(f.id = b.course_id) JOIN student_attendance_slot_table c ON(c.student_id = a.id) JOIN lesson_table g ON(g.id = c.lesson_id) JOIN tutor_table d ON(d.id = g.tutor_id) JOIN staff_table h ON(h.id = d.staff_id)";
$Recordset1 = mysql_query($query_Recordset1, $newconn) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);

A: You have a quoting issue. Get rid of the quotes around your column aliases and use ticks
$query_Recordset1 = "
    SELECT a.student_id AS `Student ID`,
        f.name AS `Course Name`,
        g.name AS `Lesson Name`,
        g.date AS `Lesson Date`,
        g.start_time AS `Lesson Start Time`,
        g.end_time AS `Lesson End Time`,
        CONCAT( h.first_name,' ', h.last_name) AS `Lesson Tutor`
        FROM student_table a
        JOIN enrollement_schedule_table b ON(a.id = b.student_id)
        JOIN course_table f ON(f.id = b.course_id)
        JOIN student_attendance_slot_table c ON(c.student_id = a.id)
        JOIN lesson_table g ON(g.id = c.lesson_id)
        JOIN tutor_table d ON(d.id = g.tutor_id)
        JOIN staff_table h ON(h.id = d.staff_id)";

A: You need to use back ticks for the fields in the query instead of double quotes. Check this:
SELECT
a.student_id AS `Student ID`
, f.name AS `Course Name`
, g.name AS `Lesson Name`
, g.date AS `Lesson Date`
, g.start_time AS `Lesson Start Time`
, g.end_time AS `Lesson End Time`
, CONCAT(h.first_name, ' ', h.last_name) AS `Lesson Tutor`
FROM
student_table a
JOIN enrollement_schedule_table b
ON (a.id = b.student_id)
JOIN course_table f
ON (f.id = b.course_id)
JOIN student_attendance_slot_table c
ON (c.student_id = a.id)
JOIN lesson_table g
ON (g.id = c.lesson_id)
JOIN tutor_table d
ON (d.id = g.tutor_id)
JOIN staff_table h
ON (h.id = d.staff_id) ;


text:
Q: BuildConfig file in android - Purpose and Possibilities Android has a flag called DEBUG in BuildConfig.java. Can someone please explain how is this file created? What is the purpose of having an auto-generated file with a single variable in it?
Is it possible to have something besides DEBUG flag inside this class? What if I want a configuration other than development and release configuration? How can I achieve it?

A: BuildConfig.java is generated automatically by Android build tools, and is placed into the gen folder.


text:
Q: How to make an image fade out without affecting the opacity of a simultaneous bright glow effect EDIT:
Thanks to tavkomann's help, I got the effects working now as they should. I have also resolved the issue I crossed out below by setting the padding of each image's container to 0px. Hope this helps fellow coders!
There is just one issue that remains: even though the images do conform to their respective containers in proper alignment, they still do not span the entire width of each; as a result, there is just a strip of space left over on each side.
Updated code:
#main-imgs {
    margin-top: 70px;
}

/* container for each image */

#main-imgs .img-column {
    display: inline-block;      /* conform container to image size */
    overflow: hidden;           /* avoid image-border overlap */

    max-height: 215px;
    padding: 0px;               /* fit image within border */

    border-width: 8px;
    border-radius: 15%;

    border-style: double;
    border-color: #290B01;

box-shadow: 0px 0px 0px 0px black;
    transition: all .6s ease-in-out;
}

/* container hover event */

#main-imgs .img-column:hover {
    box-shadow: 0px 0px 30px 0px white;
    transition: all .6s ease-in-out;
}

/* image */

#main-imgs img {
    vertical-align: middle;    /* rid of space beneath image */
    opacity: 1.0;
    transition: all .6s ease-in-out;
}

/* image hover event */

#main-imgs img:hover {
    opacity: 0.2;
    transition: all .6s ease-in-out;
}

ORIGINAL:
I'm trying to make an image fade out and glow at the same time whenever you hover over it against a black background.
The problem is that when it fades out, its opacity decreases, and this affects all attributes, including box-shadow.
As a result, the opacity of the glow effect decreases and extinguishes the glow. So far, the image fades in and out when you hover over and away from it, respectively. I have included the CSS code below.
#main-imgs img {
  max-height: 220px;

  border-width: 8px;
  border-radius: 15%;

  border-style: double;
  border-color: #290B01;

  opacity: 1.0;
  transition: all .6s ease-in-out;
}

#main-imgs img:hover {
  opacity: 0.2;
  transition: all .6s ease-in-out;
}

I have two possible (concurrent) solutions in mind, but have yet to find a way to implement either:

*

*create an "underlay," a div under the image that casts its own unadulterated glow

*use something other than the hover pseudo-class and the opacity attribute to simulate and isolate the fade effect (e.g. use jQuery).

A: I will show an implementation for this solution:

create an "underlay," a div under the image that casts its own unadulterated glow

First of all, we need to create a structure for the "underlay". This is simply a parent container:

Now, just add the border and the border-radius to the parent container instead of the image. In order for the container to adapt to the size of the image, we have to use display: inline-block. We also need to set overflow: hidden so that the image fits to the border-radius of the container. Last but not least, we should use vertical-align: middle for the image, so there is not a space at the bottom.
Finally, this leads us to the following code example in which both, the fade out and the glow effect, work correctly:

body {
  background-color: #000;
}

.img {
  display: inline-block;
  border: 8px double #290B01;
  border-radius: 15%;
  overflow: hidden;
}

.img > img {
  max-height: 220px;
  opacity: 1.0;
  transition: all .6s ease-in-out;
  vertical-align: middle;
}

.img > img:hover {
  opacity: 0.2;
  transition: all .6s ease-in-out;
}


text:
Q: How to get rid of special char '(u' I am using Salt with jinja2 "regex_search" and I try to extract some digits (release version) from the archive file name. Then use the value to create a symlink, that contains it. I've tried different combinations using "list", "join" and other filters to get rid of this Unicode char, but without success.
Example:
"release_info" variable gets value "release-name-0.2345.577_20190101_1030.tar.gz" and I need to get only digits between the dots.
Here is the corresponding part of the sls file:
symlink to current release {{ release_info }}:
  file.symlink:
    - name: /home/{{ component.software['component_name'] }}/latest
    - target: /home/{{ component.software['component_name'] }}/{{ release_info |regex_search('(\d+\.\d+\.\d+)') }}
    - user: support
    - group: support`enter code here`

The expected result is "/home/support/0.2345.577", but I have "/home/support/(u'0.2345.577',)"
If I try to pipe "yaml" or "json" filter like:
{{ release_info |regex_search('(\d+\.\d+\.\d+)') | yaml }}

I've got:
/home/support/[0.2345.577]

which is not what I am looking for.
PS
I've got it, but seems to me as not a got approach. Just workaround.
{{ release_info |regex_search('(\d+\.\d+\.\d+)') |yaml |replace('[','') |replace(']','') }}

A: Hello Todor and Welcome to Stack Overflow!
I have tried the example that you have posted and here is how to achieve what you want

Note: I have changed the regex pattern a little in order to support any other possibilities that could have more digits e.g 0.1.2.3.4 and so on, but of course you can use your pattern as long as it works for you as expected.

Solution 1:
{{ release_info | regex_search("(\d(\.\d+){1,})") | first }}

The result before using first:
('0.2345.577', '.577')

The result after using first:
0.2345.577

Solution 2:
{{ release_info | regex_search("(\d\.\d+\.\d+)") | first }}

The result before using first:
('0.2345.577',)

The result after using first:
0.2345.577

first is a built-in filter in jinja that can return the first item in a sequence. you can check List of built-in filters for more information about the other filters


text:
Q: Substring of string is not working the way i want I have this code here:
String line1 = "part1, part2, part3, part4";

and i  want to extract part 2.
so i tried this:
String extractedPart = line1.substring(line1.indexOf(","), line1.indexOf(",", line1.indexOf"," +1)));

System.out.println(extractedPart);

But it's not printing out anything.
Can someone help me with that?

A: why don't you use split method
String[] split = line1.split(",");
System.out.println(split[1]);

output
 part2

A: String extractedPart = line1.substring(line1.indexOf(",") + 1, line1.indexOf(",", line1.indexOf(",") + 1));

A: substing returns the string that starts with character in the index, so you'll need to add 1 in order to avoid the comma.
String extractedPart = line1.substring(line1.indexOf(",") + 1, line1.indexOf(",", line1.indexOf(",") +1));

will output
 part2

note that the space is still there. you can avoid it by trimming


text:
Q: Image not displaying in view. from database In my laravel project I tried to load images from database. But it displays the broken link. But when I inspect the image it shows the link. But when i clicked the link it shows 404 error.....
this is my codes
this is the code of view
.............
@extends('layouts.app')

@section('content')

    Add Posts

Posts

                Image
                Title

                @foreach ($posts as $post)

                        image) }}">
                        {{ $post->title }}

                @endforeach

@endsection

.............
and this is the code of controller
public function store(CreatePostsRequest $request)
{
    //Upload the image

    $image = $request->image->store('public/img');
    //create the post
    Post::create([
        'title' => $request->title,
        'description' => $request->description,
        'content' => $request->content,
        'image' => $image
    ]);
    //flash a message with seasson

    session()->flash('success','Post created successfully');
    //redirect user

    return redirect(route('posts.index'));

}

and i linked the storage to the public folder. But still its not working

A: You need to give the absolute path and not use {{ asset... }}. Try something like this:
image}}">


text:
Q: How to avoid RFC1918 A record, leaking on the external network? How to avoid RFC1918 A record, leaking on the external network ?
I can use the view to achieve my request ,but when the dns record more and more in the management will become very troublesome.
I wonder if there is a simpler approach.
Thanks in advance.

A: I can think of the following ways to solve the problem of private IPs leakage:

*

*Use DNS views to split the zones into two zones: one for private records allowed for local clients only and the other one for public records. If you don't like this option, you can look next.

*Use a dedicated DNS server for private records used and accessible only by local clients, and use another different DNS server for public records used by other clients. This can be enforced by a firewall.

*Use only one single view without using any private addresses. Turn all your servers IPs to public in DNS zone. Local clients will use public IPs in this case. This requires two things: no need to hide any name from your DNS, and doing the right routing/NATing configuration within your network.

I can not recommend any single solution. This depends on your setup and the available options you have.


text:
Q: Are you using Parallel Extensions? I hope this is not a misuse of stackoverflow; recently I've seen some great questions here on Parallel Extensions, and it got my interest piqued.
My question:
Are you using Parallel Extensions, and if so, how?
My name is Stephen Toub and I'm on the Parallel Computing Platform team at Microsoft.  We're the group responsible for Parallel Extensions.  I'm always interested in hearing about how developers are utilizing Parallel Extensions (e.g. Parallel.For, PLINQ, ConcurrentDictionary, etc.), positive experiences you've had, negative experiences you've had, feature requests for the future, and so on.
If you'd be willing to share such information, please do, either here as a response to this question or to me privately through email at stoub at microsoft dot com.
I'm very much looking forward to hearing from you.
Thanks in advance!

A: I'm using the TPL for doing nested Parallel.ForEach calls. Because I access dictionaries from these calls I have to use ConcurrentDictionary. Although it's nice, I have a few issues:

*

*The delegates inside of ForEach don't do much work so I don't get much parallelism. The system seems to spend most of its time joining threads. It would be nice if there was a way to figure out why it's not getting better concurrency and improve it.

*The inner ForEach iterations are over ConcurrentDictionary instances, which would cause the system to spend much of its time enumerators for the dictionary if I didn't add an enumerator cache.

*Many of my ConcurrentDictionary instances are actually sets, but there is no ConcurrentSet so I had to implement my own with a ConcurrentDictionary.

*ConcurrentDictionary does not support object initialization syntax so I can't say var dict = new ConcurrentDictionary<char, int> { { 'A', 65 } }; which also means I can't assign ConcurrentDictionary literals to class members.

*There are some places where I have to lookup a key in a ConcurrentDictionary and call an expensive function to create a value if it doesn't exist. It would be nice if there were an overload of GetOrAdd that takes an addValueFactory so that the value can be computed only if the key doesn't exist. This can be simulated with .AddOrUpdate(key, addValueFactory, (k, v) => v) but that adds the overhead of an extra delegate call to every lookup.

A: I haven't used it extensively yet, but I've definitely kept my ear to its uses and look for opportunities in our code base to put it to use (unfortunately, we're .NET-2.0 bound on many of our projects still for the time being).  One little gem I came up with myself was a unique word counter.  I think this is the fastest and most concise implementation I can come up with - if someone can make it better, that would be awesomeness:
private static readonly char[] delimiters = { ' ', '.', ',', ';', '\'', '-', ':', '!', '?', '(', ')', '<', '>', '=', '*', '/', '[', ']', '{', '}', '\\', '"', '\r', '\n' };
private static readonly Func<string, string> theWord = Word;
private static readonly Func<IGrouping<string, string>, KeyValuePair<string, int>> theNewWordCount = NewWordCount;
private static readonly Func<KeyValuePair<string, int>, int> theCount = Count;

private static void Main(string[] args)
{
    foreach (var wordCount in File.ReadAllText(args.Length > 0 ? args[0] : @"C:\DEV\CountUniqueWords\CountUniqueWords\Program.cs")
        .Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
        .AsParallel()
        .GroupBy(theWord, StringComparer.OrdinalIgnoreCase)
        .Select(theNewWordCount)
        .OrderByDescending(theCount))
    {
        Console.WriteLine(
            "Word: \""
            + wordCount.Key
            + "\" Count: "
            + wordCount.Value);
    }

    Console.ReadLine();
}

private static string Word(string word)
{
    return word;
}

private static KeyValuePair<string, int> NewWordCount(IGrouping<string, string> wordCount)
{
    return new KeyValuePair<string, int>(
        wordCount.Key,
        wordCount.Count());
}

private static int Count(KeyValuePair<string, int> wordCount)
{
    return wordCount.Value;
}

A: I have been using it on my project MetaSharp. I have a MSBuild based compile pipeline for DSLs and one stage types is a Many to Many stage. The M:M stage uses .AsParallel.ForAll(...).
Here's the snippet:
protected sealed override IEnumerable<IContext> Process()
{
    if (this.Input.Count() > 1)
    {
        this.Input
            .AsParallel<IContext>()
            .ForAll(this.Process);
    }
    else if (this.Input.Any())
    {
        this.Process(this.Input.Single());
    }

    return this.Input.ToArray();
}

A: We don't use it extensively, but it has certainly come in handy.
I was able to reduce the running time of a few of our longer-running unit tests to about 1/3 their original time just by wrapping some of the more time-intensive steps in a Parallel.Invoke() call.
I also love using the parallel libraries for testing thread-safety. I've caught and reported a couple of threading issues with Ninject with code something like this:
var repositoryTypes = from a in CoreAssemblies
                    from t in a.GetTypes()
                    where t.Name.EndsWith("Repository")
                    select t;
repositoryTypes.ToList().AsParallel().ForAll(
    repositoryType => _kernel.Get(repositoryType));

In our actual production code, we use some parallel extensions to run some integration actions that are supposed to run every few minutes, and which consist mostly of pulling data from web services. This takes special advantage of parallelism because of the high latency inherent in web connections, and allows our jobs to all finish running before they're supposed to fire again.

A: I am using a ConcurrentDictionary that stores 100 million+ items. My application uses around 8 GB of memory at that moment. The ConcurrentDictionary then decides it wants to grow on another Add. And it wants to grow a LOT apparently (some internal prima algorithm) as it runs out of memory. This is on x64 with 32GB of memory.
Therefore I would like a boolean to block automatic regrow/rehash of a (concurrent)dictionary. I would then Initialize the dictionary at creation with a fixed set of buckets (this is not the same as a fixed capacity!). And it would become a little slower over time as there are more and more items in a bucket. But this would prevent rehashing and getting out of memory too quickly and unnecessarily.


text:
Q: Decomposition of holomorphic function that takes real values on an open set on the real line I am reading Henri Cartan's Elementary Theory of Analytic Functions of One or Several Complex Variables. Exercise 10 on p.77 is related to Schwarz reflection principle:

Let $D$ be a connected open set, which is symmetrical with respect to the real axis and has non-empty intersection $I$ with it. Any holomorphic function $f(z)$ in $D$ can be expressed uniquely in the form
  $$f(z)=g(z)+ih(z)\ \text{ for all } z\in D,$$
  where $g$ and $h$ are holomorphic functions in $D$ which take real values in $I$. Show that...

The actual statements that he wanted the readers to show are omitted here. What I don't understand is the existence of $g$ and $h$.
If I pick a point $x\in I$, then within a small disc centered at $x$ inside $D$, the function $f$ has a power series representation $\sum_{n=0}^\infty a_n(z-x)^n$. So, I guess we may take $g(z)=\sum_{n=0}^\infty\operatorname{Re}(a_n)(z-x)^n$ and $h$ can be defined similarly. But why do they have analytic continuations to the whole region $D$? Why do their analytic continuations remain real-valued on the whole of $I$?
Perhaps the existence of $g$ and $h$ are proved in some other way?

A: Hint: Consider $g(z)=\frac{f(z)+\overline{f(\overline{z})}}{2}$.


text:
Q: jquery append svg element, unable to append more than one element I am trying to use JQuery to append some svg elements. Code as shown below.
$("#save_edits").click(function() {

    var img = document.createElementNS('http://www.w3.org/2000/svg','image');
        img.setAttributeNS('http://www.w3.org/1999/xlink','href','./img/exclamation-mark.png');
        img.setAttributeNS(null,'x','-7');
        img.setAttributeNS(null,'y','-35');
        img.setAttributeNS(null,'height','15');
        img.setAttributeNS(null,'width','15');

    if(id==" Shipping"){
        $('svg>g').first().append(img);
        $('svg>g:eq(2)').append(img);
        $('svg>g:eq(3)').append(img);
        $('svg>g:eq(4)').append(img);
    }
});

However, only the last append works successfully $('svg>g:eq(4)').append(img);, and not all the previous. Does anyone know why previous ones were override and how to prevent it from occurring?
Answer:
Ok, seems like I figured out eventually. Basically need to recreate the img element again for each append.
child = ["svg>g:eq(2)","svg>g:eq(3)","svg>g:eq(4)"]

if(id==" Shipping"){
    child.forEach(function(e){
        var img = document.createElementNS('http://www.w3.org/2000/svg','image');
            img.setAttributeNS('http://www.w3.org/1999/xlink','href','./img/exclamation-mark.png');
            img.setAttributeNS(null,'x','-7');
            img.setAttributeNS(null,'y','-35');
            img.setAttributeNS(null,'height','15');
            img.setAttributeNS(null,'width','15');

        $(e).append(img);
    })


text:
Q: Regular Expression to capture U+XXXX (or \uXXXX) characters in Java I've been trying to create PDF using PDFBox and it fails with errors like,

java.lang.IllegalArgumentException: U+0083 is not available in this font's encoding: WinAnsiEncoding

I wanted to know if there is a way I could capture such elements using a Regular Expression, I've tried using,
(\\[a-z]00[0-9][0-9])

Which seems to work fine if I validate is using a RegexTool (like RegexBuddy) but doesn't work in Java! I've tried using Java Patterns and Matcher but no success. What I've done with Pattern Matcher is as follows,
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MatcherFindStartEndExample {

public static void main(String[] args) {

    String text    =
            "IMTECH Ã\u0083¢Ã\u0082Â\u0080Ã\u0093Â\u0083 " +
            "ERCC Ã\u0099¢à PLANNED ";

    String patternString = "(\\[a-z]00[0-9][0-9])";

    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(text);

    int count = 0;
    while(matcher.find()) {
        count++;
        System.out.println("found: " + count + " : "
                + matcher.start() + " - " + matcher.end());
    }
  }
}

The text I have right now appears something like,

IMTECH Ã\u0083¢Ã\u0082Â\u0080Ã\u0093Â\u0083 ERCC Ã\u0099¢à PLANNED

Thank you

A: I'm not sure exactly what you're trying to do here, but "\u0083" is a Java escape sequence representing one character, not six characters.  It will not be matched by the regular expression "..0083", but it will be matched by ".".
Also, "\\" represents one character in a Java string, the backslash;  in a regular expression, that single backslash escapes the following character.  In your case "\\[" matches a literal opening square bracket character.
But all of that may be irrelevant, since the presence of sequences like ¢ suggests you are mishandling UTF-8 data.  In particular, it looks like someone has forced every byte to a char value, instead of properly decoding the bytes using a Charset.  And then the same mistake was applied a second time to the new, incorrect String.
Working backwards, these characters:
ERCC Ã\u0099¢

correspond to these hexadecimal byte values:
45 52 43 43 20 c3 99 c2 a2

If, instead of forcing each byte value to be a char, you decode them as UTF-8 bytes, you get the string "ERCC Ù¢".  If we again treat each char as a byte value, we get:
45 52 43 43 20 d9 a2

and if we once again decode those bytes using UTF-8, we get "ERCC ٢", which I am guessing refers to ERCC2.
If you fix the code which is extracting the text, you can match that string with something like Pattern.compile("ERCC\\s*\\d+", Pattern.UNICODE_CHARACTER_CLASS).

A: I'm assuming that you want to match for literally "\u0083", and not the unicode character that it represents.
Try (\\\\u00[0-9][0-9]).

A: Your patternString searches literally for a text instead a character.
You can search for a list of characters like this:
String patternString = "[\u0083|\u0082|\u0080]";

or for a list like this:
String patternString = "[\u0080-\u0090]";

A: This regex will find all backslash + u + 4 digits
String patternString = "[\\\\]+[u]+\\d{4}";

Output:

found: 1 : 8 - 14
found: 2 : 17 - 23
found: 3 : 24 - 30
found: 4 : 31 - 37
found: 5 : 38 - 44
found: 6 : 51 - 57


text:
Q: Why HTML  does not work at first? I am creating a text editor with HTML and I want to change font color.
<input id="fore-color" type="color" value="#ffffff" onchange="changeWithArgs('foreColor', this.value)">

When I open it on Chrome, at first it can't implement a color till I choose one of basic colors. After that it starts to work normally,but how can I choose my prefered color at once?
Issue is provided in photo. Also it can't change color | solid property.
Please help. Thanks in advance.

A: You have to select the color from basic color or custom colors. But by default whatever color you mentioned in the value attr will be the default one selected once the page is loaded.

A: actually when you are selecting color then the right most bar is set at black(as black triangle is set to that).... You have to change the placement of black colored triangle besides the right most bar to change the color

A: You have to specify the type of input in HTML; for example, type="text" type="checkbox" etc. There is no value"color" for the type attribute of an input.


text:
Q: How can I add map-reduce function to mongodb for reuse? I was wondering if there was a way you could save JavaScript functions that are used on mongodb. This way you can reuse these functions whenever you need to.

A: Yes, there is now a way to store JavaScript functions on the server for reuse. You just have to store them in a special collection that each database has called system.js. Doing it looks like this:

db.system.js.save({
       _id : "myAddFunction" ,
       value : function (x, y){ return x + y; }    } );

Make sure you first select the database you want to save the function with use <database> command in the mongo shell.
Here is a function that I added to my system.js that checks if a collection attribute is unique:
db.system.js.save({
      _id : "allDifferent" ,
      value : function (collection,field) {
                 var m = function() { emit(this.field, 1); }
                 var r = function(key, emits) {
                               var n = 0; emits.forEach(function(v) { n += v; }); return n;
                         }
                 var result = db.collection.mapReduce(m, r, { out: "namecounts" });
                 var allDifferent= (db.namecounts.count( { value: { $gt: 1 } } ) == 0)
                 db.namecounts.drop();
                 return allDifferent;
              }
      });

In the mongo shell, you should use db.loadServerScripts() to load all the scripts saved in the system.js collection for the current database.
Once loaded, you can invoke the functions directly in the shell, as in the following example:

allDifferent(sample_collection, name)

Also you can list the functions you have saved with

db.system.js.distinct("_id");


text:
Q: Java Trie Hang Up Creating and testing a Java Trie class, and my main class is hanging up for whatever reason, and running the program never terminates.
import java.util.*;

public class Trie<T> {
private  Node<T> root;

private int count;

public Trie(T rootContent){
    root= new Node<T>(rootContent);
    count=0;
}
public void insert(T[] content){
    Node<T> current=root;
    if(content !=null){
        if(content.length==0){
            current.setFlag(true);
        }
        for(int i=0; i<content.length;i++){
            Node<T> child=current.getChild(content[i]);
            if(child!=null){
                current=child;
            }
            else{
                current=current.addChildren(content[i]);
            }
            if(i==content.length-1){
                if(current.isLast()){
                    current.setFlag(true);
                    count++;
                }
            }
        }
    }
}

public boolean search(T[] content){
    Node<T> current=root;
    for(int i=0;i<content.length;i++){
        if(current.getChild(content[i])==null){
            return false;
        }
        else{
            current=current.getChild(content[i]);
        }
    }
    if(current.isLast()){
        return true;
    }
    else{
        return false;
    }

}

public int getCount(){
    return count;
}

public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("number entries: ");
    sb.append(count);
    return sb.toString();
}
private static class Node<T>{
    private T content;

    private boolean endFlag;

    public List<Node<T>> children=new ArrayList<Node<T>>();

    public Node(T content){
        this.content=content;
        this.endFlag=false;
        this.children=new ArrayList<Node<T>>();
    }

    public T getContent(){
        return content;
    }

    public Node<T> addChildren(T content){
        Node<T> t=new Node<T>(content);
        children.add(t);
        return t;
    }

    public Node<T> getChild(T content){
        if(children!=null){
            for(Node<T> t : children){
                if(t.getContent().equals(content)){
                    return t;
                }
            }
        }
        return null;
    }

    public void setFlag(boolean endFlag){
        this.endFlag=endFlag;
    }

    public boolean isLast(){
        return endFlag;
    }

}
public static void main(String[] args) {

        Trie file1=new Trie("");
        Trie file2=new Trie("");
        if(args.length==0 || args[0]==null){
            System.out.println("Please give a valid command file");
        }
        else{
        try{
        Scanner reader1 = new Scanner(new FileInputStream(args[2]));
        Scanner reader2 = new Scanner(new FileInputStream(args[3]));
        String d=args[0];
        String n=args[1];
        int depth=Integer.parseInt(d);
        int numberOfStrings=Integer.parseInt(n);
        while(reader1.hasNext());{
            String[] ary=reader1.next().split("");
            file1.insert(ary);
        }
        while(reader2.hasNext());{
            String[] ary=reader1.next().split("");
            file2.insert(ary);
        }
        reader1.close();
        reader2.close();
        System.out.print(file1);
        System.out.print(file2);
    }
        catch(Exception e){

    }
}

}
}

I think the insert operation is where things are hangning up, the text files are nothing more than random strings "dog
god
dog
act
cata
asfdoh
aosifdh
oawrhi "

A: Looking at these lines shows the issue:
    while(reader1.hasNext());{
        String[] ary=reader1.next().split("");
        file1.insert(ary);
    }
    while(reader2.hasNext());{
        String[] ary=reader1.next().split("");
        file2.insert(ary);
    }

There should not be a semi-colon after while(reader2.hasNext()) or while(reader1.hasNext()) because this terminates the loop. I'm not actually sure why the semi colon here causes it to hang, but for some reason it does. I'm sure somebody will be able to help us both out here, but removing the semi-colons will fix the issue. It's strange, however, that the code is compilable.
Are you using an IDE? If you are, in the future you should attempt to debug your code within the IDE before asking for help on here. Saves everybody's time, and it's a good (read: necessary) skill to have.
Also for further reference, you have parameterised the type of Trie, but not specified a type when instantiating it.
Trie file1=new Trie("");

should be
Trie<String> file1=new Trie<String>("");


text:
Q: Add javascript raw file (that is not a module) to build I have separated the following file using code splitting to be able to change it in the own build on the fly (without recompiling):
// app/src/env.ts

window.process.env.API_HOST = 'http://localhost:8000'
window.process.env.NODE_ENV = 'development'

But my generated JS file looks like this:
// app/build/env.bundle.js

"use strict";
(self["webpackChunkmypackage"] = self["webpackChunkmypackage"] || []).push([[338],{

/***/ 7100:
/***/ (() => {

window.process.env.API_HOST = 'http://localhost:8000';
window.process.env.NODE_ENV = 'development';

/***/ })

}]);
//# sourceMappingURL=env.bundle.js.map

Is it possible to keep the original raw format for this particular file with some loader?

A: I solved it using the CopyPlugin of webpack. Create your raw javascript file in your project and then make webpack place it in the top level of the build:
    plugins: [
      new CopyPlugin({
        patterns: [
          // copy "src/env.js" to top level of build ("build/env.js")
          { from: './src/env.js', to: '.' },
        ]
      })
    ],

Add the file manually to your html entrypoint of your SPA:

  <meta charset="utf-8">
  <title>Your app</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

    Enabling JavaScript is required to run this app.


text:
Q: How can I use jest on React using npm? My application is made using create react app and npm. In the jest's official documentation, https://jestjs.io/docs/tutorial-react , they only have information about testing CRA apps using yarn. Does this mean we cannot use jest to test our React app using npm?

A: You can use jest with CRA, in fact it's already built-in to CRA.
Try run npm test
Read more details here https://create-react-app.dev/docs/running-tests


text:
Q: Can't access mod_wsgi hosted python (bottle.py) app Here is my Problem:
I wrote a bottle.py application and runs it on my pc with the internal bottle.py webserver. Now i want to upload my application to my server and would like to run it there with apache2 + mod_wsgi I have created the following Files :
/etc/apache2/sites-enabled/000-default
...

WSGIDaemonProcess web user=www-data group=www-data processes=1 threads=5
WSGIScriptAlias /dem /var/www/vhosts/test.de/rbdemo/app.wsgi
WSGIProcessGroup web

<Directory /var/www/vhosts/test.de/rbdemo>
    WSGIApplicationGroup %{GLOBAL}
    Order deny,allow
    Allow from all
</Directory>

/var/www/vhosts/test.de/rbdemo/app.wsgi
import sys, os

sys.path = ['/var/www/vhosts/test.de/rbdemo'] + sys.path
os.chdir(os.path.dirname(__file__))

from web import default_app # This loads your application

application = default_app()

And in my application:
/var/www/vhosts/test.de/rbdemo/web.py
from bottle import TEMPLATE_PATH, request, redirect, route, hook, run, default_app, jinja2_template as template, static_file

...

if __name__ == '__main__':
    run(reloader=True)

Apache LOG
Fatal Python error: PyEval_AcquireThread: NULL new thread state
[Wed Mar 27 17:26:47 2013] [notice] child pid 10124 exit signal Aborted (6)
Fatal Python error: PyEval_AcquireThread: NULL new thread state
[Wed Mar 27 17:29:13 2013] [notice] child pid 18003 exit signal Aborted (6)
Fatal Python error: PyEval_AcquireThread: NULL new thread state
[Wed Mar 27 17:30:47 2013] [notice] child pid 10126 exit signal Aborted (6)
Fatal Python error: PyEval_AcquireThread: NULL new thread state
[Wed Mar 27 17:32:32 2013] [notice] child pid 21774 exit signal Aborted (6)
Fatal Python error: PyEval_AcquireThread: NULL new thread state
[Wed Mar 27 17:32:37 2013] [notice] child pid 21779 exit signal Aborted (6)
[Wed Mar 27 17:59:17 2013] [error] [client 118.139.160.196] client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /w00tw00t.at.ISC.SANS.DFind:)

But if I want to access my application (demo.test.de) I get a 403 Forbidden Error...
Any Ideas ?
Thank you.


text:
Q: RabbitMQ and EC2: Clusters can't join I'm trying to create a RabbitMQ cluster.
The instances have been set up identically (They've been installed identically), they can resolve eachother's hostnames (Both with digand rabbitmqclt resolve_hostname) and their cookie hash is the same.
I'm wondering whether or not there are more steps to setting up a RabbitMQ cluster when in EC2.
I'm running RabbitMQ 3.9.13 and Ubuntu 20.04
Thank you all in advance
-brej

A: Basically, it should be sufficient, make sure to declare all these settings the config file of RabbitMQ, this way, each time it start, it will be able to reconnect to the cluster when needed.


text:
Q: Update PointF Value Using Extension Method in C# I'm creating an application that displays "old school" sprites. The location of each sprite is held in a PointF variable.
I would like to update each sprite's position based on a supplied angle and speed.
I have created an extension method over to the PointF class so that this logic is self contained and accessible throughout the application.
The extension method looks like this:
public static class MyExtensions
{
    public static PointF Translate(this PointF point, double angle, double speed)
    {
        point.X += (float)(Math.Sin(angle / 57.2958) * speed);
        point.Y += (float)(Math.Cos(angle / 57.2958) * speed);
        return point;
    }
}

Currently, the client code that consumes the extended PointF class looks like this:
position = position.Translate(angle, speed);

This works just fine, but I would like to go one step further and completely encapsulate the position update within the extension method. In that case, the client code should work like this:
position.Translate(angle, speed);

To do this, it feels as though I should be passing the existing position value by ref into the method call, but I can't figure out the syntax to do this.
Is this even possible? If so, I would appreciate some guidance...


text:
Q: How to solve 'TypeError: Cannot read property 'secure_url' of null' in React I am using Cloudinary to upload images, then display the image and the URL. My images are uploading but I am getting cannot display either the image or the URL because I am getting a TypeError in my if (response.body.secure_url !== ''. I've researched and read that it's because maybe I'm  accessing a property of an object that is null
App.js
this.state = {
      uploadedFile: null,
      uploadedFileCloudinaryUrl: ''
    };
  }

  onImageDrop(files) {
    this.setState({
      uploadedFile: files[0]
    });

    this.handleImageUpload(files[0]);
  }

  handleImageUpload(file) {
    let upload = request.post(CLOUDINARY_UPLOAD_URL)
                     .field('upload_preset', CLOUDINARY_UPLOAD_PRESET)
                     .field('file', file);

    upload.end((err, response) => {
      if (err) {
        console.error(err);
      }

      if (response.body.secure_url !== '') {
        this.setState({
          uploadedFileCloudinaryUrl: response.body.secure_url
        });
      }
    });
  }

  render() {
    return (

      <Dropzone
        onDrop={this.onImageDrop.bind(this)}
        accept="image/*"
        multiple={false}>
        {({getRootProps, getInputProps}) => {
      return (

          <input {...getInputProps()} />
          {

Try dropping some files here, or click to select files to upload.

          }

      )
  }}
</Dropzone>

        {this.state.uploadedFileCloudinaryUrl === '' ? null :

{this.state.uploadedFile.name}

}

    )
  }

A: To deal with null or undefined, you could change conditional to:
if ( response.body.secure_url && response.body.secure_url !== '' )
This checks to make sure the secure URL exists with some truthy value before determining whether or not it is not equal to the empty string (because technically null is not equal to the empty string so the existing condition does not check everything you are interested in).

A: Here is a sample code in React on how to use it with upload:
https://codesandbox.io/embed/jq4wl1xjv


text:
Q: Struts2 increment a previous set  value I'm working on JSPs with Struts2, I have to iterate on two lists, and change the background code of each
 printed.
My JSP snippet:
<s:set var="counter" value="0" scope="page" />
<s:iterator value="listaContoCapitale" status="i">
    <s:iterator value="utilizzi" status="j">

    <s:if test="#counter == 0 || #counter % 2 == 0">
        <s:set var="trclass" value="'rigaSfondo1'" scope="page" />
    </s:if>
    <s:else>
        <s:set var="trclass" value="''" scope="page" />
    </s:else>

        ....tds

    </s:iterator>
    <s:set var="counter" value="here i have to change its value (increment it by1)" />
</s:iterator>

I need to increment my counter every step on the inner loop. Is there a way to increment my counter value by a simple struts tag? I know I could use Java scriptlet but I rather keep the JSP clear if possible.

A: You aren't required to create a reference variable just use #i.index or #i.count inside the iterator. It's already incremented by the iterator tag itself.

Note that "count" is 1-based, "index" is 0-based.

Always check the docs.
If you still need your own counter
<s:set var="counter" value="0"/>

increment
<s:set var="counter" value="%{#counter+1}"/>

A: You Can Use this easy Way to Do this struts2 increment
<s:set var="count" value="1"/>
<s:iterator value="yourlisthere">

<s:property value="#count" /><s:property/>

<s:set var="counter" value="%{#count+1}"/>
<s:set var="count" value="%{#counter}"/>
</s:iterator>

jsp struts2


text:
Q: How to check for Platform Encryption Does anybody know how to check if Platform Encryption is enabled in a given org? Ideally without using the metadata API.
I don't need to know if a user/permset has access to "View Encrypted Data", I simply have to change some functionality if data is Encrypted (no where clause on some standard fields, for example).
Can't find any docs to that effect... yet

A: I assume there are couple of Objects that will have some Entry if the platform encryption is enabled .
The Two Objects that I would look are TenantSecret and TenantUsageEntitlement
system.debug('$$$'+[SELECT AmountUsed,EndDate FROM TenantUsageEntitlement]);

I have no access to org with Platform Encryption Enabled else I would verify this .I assume TenantSecret object appears only once Platform encryption is enabled
If you want at Object level to see Platform Encyrption is enabled check in describe Object for is encrypted boolean documented here .

A: I was actually able to find the perfect solution.
sObjectType.Contact.fields.Name.isEncrypted()
That solved it. :)

A: know ideally you didn't want to use metadata API but.. Could you attempt to create an encrypted field with the metadata api.
If this call fails it should return an error message that encryption is not available.  If the call succeeds then you need to rollback the creation via another call but you will know that the org feature is enabled.  Not pretty..

A: You can definitely check if encryption is enabled for a particular field, even if that field lives within an org that doesn't have Platform Encryption provisioned.
The only trickiness is that when Platform Encryption isn't provisioned onto an org, calling Apex Describe on an sObject won't return the IsEncrypted field as part of its result.
You can work around this by checking for both null and false in your Apex code.
Here's a short example of a Visualforce page that utilizes Apex to generate a list of every field associated with the Account sObject, and it's encryptability. You can do something similar in your code to branch based on whether encryption is available for a particular field.
<apex:page >

</apex:page>

This would output something like this:

Id — Encrypted: false
IsDeleted — Encrypted: false
MasterRecordId — Encrypted: false
Name — Encrypted: true
Type — Encrypted: false
ParentId — Encrypted: false
BillingStreet — Encrypted: false
BillingCity — Encrypted: false
BillingState — Encrypted: false
BillingPostalCode — Encrypted: false
BillingCountry — Encrypted: false
BillingLatitude — Encrypted: false
BillingLongitude — Encrypted: false
BillingGeocodeAccuracy — Encrypted: false
BillingAddress — Encrypted: false
ShippingStreet — Encrypted: false
ShippingCity — Encrypted: false
ShippingState — Encrypted: false
ShippingPostalCode — Encrypted: false
ShippingCountry — Encrypted: false
ShippingLatitude — Encrypted: false
ShippingLongitude — Encrypted: false
ShippingGeocodeAccuracy — Encrypted: false
ShippingAddress — Encrypted: false
Phone — Encrypted: false
Fax — Encrypted: false
AccountNumber — Encrypted: false
Website — Encrypted: false
PhotoUrl — Encrypted: false
Sic — Encrypted: false
Industry — Encrypted: false
AnnualRevenue — Encrypted: false
NumberOfEmployees — Encrypted: false
Ownership — Encrypted: false
TickerSymbol — Encrypted: false
Description — Encrypted: false
Rating — Encrypted: false
Site — Encrypted: false
OwnerId — Encrypted: false
CreatedDate — Encrypted: false
CreatedById — Encrypted: false
LastModifiedDate — Encrypted: false
LastModifiedById — Encrypted: false
SystemModstamp — Encrypted: false
LastActivityDate — Encrypted: false
LastViewedDate — Encrypted: false
LastReferencedDate — Encrypted: false
Jigsaw — Encrypted: false
JigsawCompanyId — Encrypted: false
CleanStatus — Encrypted: false
AccountSource — Encrypted: false
DunsNumber — Encrypted: false
Tradestyle — Encrypted: false
NaicsCode — Encrypted: false
NaicsDesc — Encrypted: false
YearStarted — Encrypted: false
SicDesc — Encrypted: false
DandbCompanyId — Encrypted: false
BRHdjkSmZB__CustomerPriority__c — Encrypted: false
BRHdjkSmZB__SLA__c — Encrypted: false
BRHdjkSmZB__Active__c — Encrypted: false
BRHdjkSmZB__NumberofLocations__c — Encrypted: false
BRHdjkSmZB__UpsellOpportunity__c — Encrypted: false
BRHdjkSmZB__SLASerialNumber__c — Encrypted: false
BRHdjkSmZB__SLAExpirationDate__c — Encrypted: false
BRHdjkSmZB__Encrypted_Text__c — Encrypted: true
BRHdjkSmZB__Encrypted_Text_1__c — Encrypted: true
BRHdjkSmZB__Encrypted_Text_2__c — Encrypted: true
BRHdjkSmZB__Encrypted_Text_3__c — Encrypted: true
BRHdjkSmZB__Encrypted_Text_4__c — Encrypted: true
BRHdjkSmZB__Encrypted_Text_5__c — Encrypted: true
BRHdjkSmZB__Encrypted_Text_6__c — Encrypted: true
BRHdjkSmZB__Encrypted_Text_7__c — Encrypted: true
BRHdjkSmZB__Encrypted_Text_8__c — Encrypted: true
BRHdjkSmZB__Encrypted_Text_9__c — Encrypted: true

A: Another way to check "no where clause" is to use sObjectType.Contact.fields.Name.isFilterAble().


text:
Q: Sharper Google Maps Circles for mobile devices I'm building an android app that uses a webview to show a google maps canvas (javascript api v3). (Using a webview to do this for reasons). I am adding some circles to this map, on specific locations, from a database.
The problem is; the circles are not as sharp as on a "regular" screen.
See this screenshot: http://imgdump.nl/hosted/7ce8360c83a3889cdc30abfbb7d3cd72.png
I tried scaling and zooming using css, with different but unsatisfying results.
Is there a way to render these circles for mobile screens with a higher pixel density? Or any other solutions for this problem?
Thanks,
Stef


text:
Q: What format i should convert the frames to to be used in openCV In my App, i open the native android camera and i render the preview on a TextureView, and what i want to do next is, to take each frame from the camera and perform some processing and operations using OpenCV library.
I also referred to some posts here Android decode Bitmap from Camera Preview ,
how to get RGB values of bitmap in android , How to capture preview image frames from Camera Application in Android Programming?
but i donot know to which format i should convert the retrieved frames especially that i want to use it in opeCV as i said earlier, also which format yields good performance, should i convert them into YUV, JPEG or NV21?
update
the reason why i want to use native android camera and then convert the frames retrieved from the camera to another format applicable to openCV is,when i used CvCameraViewListener2, there are always a black area surrounds the camera preview as shown below in the picture and i could not get rid of it so i decided to use the native android camera instead
image:

A: If your activity implements OpenCV's CameraBridgeViewBase.CvCameraViewListener2, it will also implement the onCameraFrame method which comes with a CvCameraViewFrame parameter.
You can get your image in grayscale or RGBA format from that. This guy does it in this tutorial. This tutorial is about integrating native C++ OpenCV code, but if you do not need to do that, just pay attention to the part where he works on his MainActivity.
EDIT: If you have access to your preview frame's data as a byte array, have you tried simply putting that data into a mat?
Mat foo = new Mat(height, width, type); //type is probably CvType.CV_8UC1
foo.put(0, 0, data);


text:
Q: Android: How can I pass a time value from one activity to another? I have two Time values in one of my activity and I have set the time to current time like this:
StartTime.setToNow();
EndTime.setToNow();

I want to pass the values of StartTime and EndTime to another activity, but all I am getting is year 1970 ... something something which is obviously wrong.
I am passing the data with an Intent like this:
 Intent intent1 = new Intent (Localisation.this, Quiz.class);
 intent1.putExtra("StartTime", StartTime.second);
 intent1.putExtra("EndTime", EndTime.gmtoff);
 startActivity(intent1);

Can you tell me how to do it correctly?

A: Instead of java.util.Calendar I recommend you to use third part libraries for different actions with date or time objects.
For example Joda Time.
DateTime object from this library implements Serializable so you can pass value like this
DateTime dt = new DateTime();
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("date", dt);
startActivity(i);

And second Activity
Intent i = getIntent();
DateTime dt = (DateTime) i.getSerializableExtra("date");

With Joda Time library you can get the differences between two time objects and many other things.

A: An example based on some of the comments that were added to the original question:
First Activity:
Date date = StartTime;

Intent launch = new Intent(ActivityOne.this, ActivityTwo.class);
Bundle extras = new Bundle();
extras.putLong("start_time", date.getTime());
launch.putExtras(extras);

Second Activity:
Bundle extras = getIntent().getExtras();
Date date = new Date(extras.getLong("start_time"));


text:
Q: Count hidden elements regardless of parent visibility I need to count hidden elements regardless of parent visibility.
I have this code:

In this example I get 3 items, so is correct.
But with this code:

I get 4 elements! because parent is a hidden element, but I need to get 3.
Any ideas?

A: You can use filter function to filter out elements that have display property set as none:
var hidden_items = $('#parent-2 .item').filter(function(){
 return $(this).css('display') == "none"
}).length;

Working Snippet:

$(function(){
var hidden_items = $('#parent-2 .item').filter(function(){
 return $(this).css('display') == "none"

 }).length;
 alert (hidden_items);
});

A: That is because, When a parent element is hidden the children elements of it will also be hidden. That is the natural behavior. If you still want to get the elements regardless of its parent display property then use .filter with its callBack function.
var hidden_items = $('#parent-2 .item').filter(function(){
 return this.style.display == "none"
}).length;

DEMO


text:
Q: copy folder permission to another server I have the next problem, i have 2 servers (debian) and each one have install tomcat.
The first server (192.168.0.100) have installed tomcat with their default permissions in every folder (and that's ok).
But , in my second server (192.168.0.101), someone here put chmod 777 –R to every folder in tomcat, and I don't know how to restore to the original permissions in every folder.
So, my question is, it's possible copy the permissions tomcat's folders from the first server (192.168.0.100) and then set that permissions in tomcat's folders of the second server (192.168.0.101) ??
Regards

A: Yes, it is possible. You can either copy the folder with scp -pr, preserving permissions and replace it with the old one, or, if the contents, but not the files differ, you can copy it (preserving permissions) and clone permissions:
chmod -R --reference REMOTEFOLDER LOCALFOLDER
chown -R --reference REMOTEFOLDER LOCALFOLDER

The following answer could also be helpful: https://unix.stackexchange.com/a/20646


text:
Q: My global Components are not available I am new to vuex so i might have only a really dumb mistake.
I am trying to make a reactive Router, for that i used the store from vuex and since i have multiple Components i used a selfwritten Plugin to make them all global. My problem is that the store, where all the routes are saved,and all other components dont have access to the components i set global. I get the following Errormessage:

Uncaught ReferenceError: Home is not defined

my Plugin to make the components global
componentPlugin.js:
import List from "./components/List.vue";
import MainMenu from "./components/MainMenu.vue";
import Test from "./views/Test.vue";
import About from "./views/About.vue";
import Menu from "./views/Menu.vue";
import Home from "./views/Home.vue";

export default {
  install(Vue) {
    Vue.component("List", List);
    Vue.component("MainMenu", MainMenu);
    Vue.component("Test", Test);
    Vue.component("About", About);
    Vue.component("Menu", Menu);
    Vue.component("Home", Home);
  }
};

my store.js:
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    projects: [{ id: 0, title: "Create new Project", compRate: 0 }],
    globalid: 1,
    projectname: "",
    routes: [
      {
        path: "/home",
        name: "home",
        component: Home
      },
      {
        path: "/about",
        name: "about",
        component: About
      },
      {
        path: "/menu",
        name: "menu",
        component: Menu
      }
    ],
    reloaded: 0
  },
  mutations: {
    newProject: (state, project) => {
      state.projects.push({
        id: project.id,
        title: project.title,
        compRate: project.compRate
      });
    },
    delProject: (state, id) => {
      state.projects.forEach(e => {
        if (id === e.id) {
          state.projects.splice(state.projects.indexOf(e), 1);
        }
      });
    },
    newName: (state, name) => {
      state.projectname = name;
    },
    newRoute: state => {
      state.reloaded++;
    }
  },
  actions: {
    newProject: ({ commit, state }, project) => {
      commit("newProject", {
        id: state.globalid,
        title: project.title,
        compRate: project.compRate
      });
      state.globalid++;
    },
    delProject: ({ commit }, id) => {
      commit("delProject", id);
    },
    newRoute: ({ commit }) => {
      commit("newRoute");
    }
  },
  getters: {
    getProjectNumber(state) {
      return state.projects.length;
    },
    getReloaded(state) {
      return state.reloaded;
    }
  }
});

My main.js:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

import storePlugin from "./storePlugin";
Vue.use(storePlugin);

import componentPlugin from "./componentPlugin.js";
Vue.use(componentPlugin);

import "./registerServiceWorker.js";
import App from "./App.vue";
import router from "./router.js";
import store from "./store.js";

import BootstrapVue from "bootstrap-vue";
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap-vue/dist/bootstrap-vue.css";
Vue.use(BootstrapVue);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

The storePlugin is just to make the store global
storePlugin:
import store from "./store";
export default {
  store,
  install(Vue) {
    Vue.prototype.$myStore = store;
  }
};

I am using Vue v2.5.17 and vue-router 2.0.
If you need more information, just ask but im pretty sure that this is all that matters.

A: When you call
import storePlugin from "./storePlugin";
Vue.use(storePlugin);

in main.js your Vue instance doesn't know about the componentPlugin and what it does because it's called after storePlugin (in storePlugin you import the store so there is where I suspect you get the ReferenceError)
Try this:

main.js

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

import componentPlugin from "./componentPlugin.js";
Vue.use(componentPlugin);

import storePlugin from "./storePlugin";
Vue.use(storePlugin);

import "./registerServiceWorker.js";
import App from "./App.vue";
import router from "./router.js";
import store from "./store.js";

import BootstrapVue from "bootstrap-vue";
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap-vue/dist/bootstrap-vue.css";
Vue.use(BootstrapVue);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

store.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    projects: [{ id: 0, title: "Create new Project", compRate: 0 }],
    globalid: 1,
    projectname: "",
    routes: [
      {
        path: "/home",
        name: "home",
        component: Vue.component('Home')
      },
      {
        path: "/about",
        name: "about",
        component: Vue.component('About')
      },
      {
        path: "/menu",
        name: "menu",
        component: Vue.component('Menu')
      }
    ],
    reloaded: 0
  },
  mutations: {
    newProject: (state, project) => {
      state.projects.push({
        id: project.id,
        title: project.title,
        compRate: project.compRate
      });
    },
    delProject: (state, id) => {
      state.projects.forEach(e => {
        if (id === e.id) {
          state.projects.splice(state.projects.indexOf(e), 1);
        }
      });
    },
    newName: (state, name) => {
      state.projectname = name;
    },
    newRoute: state => {
      state.reloaded++;
    }
  },
  actions: {
    newProject: ({ commit, state }, project) => {
      commit("newProject", {
        id: state.globalid,
        title: project.title,
        compRate: project.compRate
      });
      state.globalid++;
    },
    delProject: ({ commit }, id) => {
      commit("delProject", id);
    },
    newRoute: ({ commit }) => {
      commit("newRoute");
    }
  },
  getters: {
    getProjectNumber(state) {
      return state.projects.length;
    },
    getReloaded(state) {
      return state.reloaded;
    }
  }
});

If you want to use the router in vuex I recommend vuex-router-sync


text:
Q: Как сделать, чтобы при смене радиокнопки прошлое значение убиралось и прибавлялось новое При выборе другого radiobutton прошлый выбранный вычитывался из цены
На примере кофе машины:
XAML
<StackPanel Grid.Row="1" Grid.Column="0" Margin="0,0,6,0">
                    <Label Content="Выберите размер стаканчика"
                           FontFamily="Comic Sans Ms"
                           FontSize="18">
                        <Label.Effect>
                            <DropShadowEffect/>
                        </Label.Effect>
                    </Label>

                    <StackPanel>
                        <RadioButton Content="Маленький 0.3"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 FontStyle="Italic"
                                 Height="25"
                                 GroupName="CupSize"
                                 BorderBrush="Black"
                                 Background="#FF4C2B2B"
                                 Click="rb_mincup"
                                 x:Name="smallcup"
                                 Checked="smallcup_Checked"
                                 />

                        <RadioButton Content="Средний 0.5"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 Height="25"
                                 FontStyle="Italic"
                                 GroupName="CupSize"
                                 Background="#FF4C2B2B"
                                 BorderBrush="Black"
                                 Click="rb_05cup"
                                 x:Name="middlecup"
                                 />
                        <RadioButton Content="Большой 0.7"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 Height="25"
                                 FontStyle="Italic"
                                 GroupName="CupSize"
                                 Background="#FF4C2B2B"
                                 BorderBrush="Black"
                                     x:Name="bigcuo07"
                                 Click="rb_bigcup"
                                 />
                        <RadioButton Content="Очень большой 1.0"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 Height="25"
                                 FontStyle="Italic"
                                 GroupName="CupSize"
                                 Background="#FF4C2B2B"
                                 BorderBrush="Black"
                                 Click="rb_verybigcup"
                                 />
                    </StackPanel>

                    <Label Content="Выберите напиток"
                           FontFamily="Comic Sans Ms"
                           FontSize="18">
                        <Label.Effect>
                            <DropShadowEffect/>
                        </Label.Effect>
                    </Label>
                    <StackPanel>
                        <RadioButton Content="Экспрессо"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 FontStyle="Italic"
                                 GroupName="TypeDrink"
                                 BorderBrush="Black"
                                 Background="#FF4C2B2B"
                                 Height="25" Checked="RadioButton_Checked"/>
                        <RadioButton Content="Американо"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 FontStyle="Italic"
                                 GroupName="TypeDrink"
                                 Background="#FF4C2B2B"
                                 BorderBrush="Black"
                                 Height="25" Checked="RadioButton_Checked_1"/>
                        <RadioButton Content="Капучино"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 FontStyle="Italic"
                                 GroupName="TypeDrink"
                                 Background="#FF4C2B2B"
                                 BorderBrush="Black"
                                 Height="25" Checked="RadioButton_Checked_2"/>
                        <RadioButton Content="Маккиато"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 FontStyle="Italic"
                                 GroupName="TypeDrink"
                                 Background="#FF4C2B2B"
                                 BorderBrush="Black"
                                 Height="25" Checked="RadioButton_Checked_3"/>
                        <RadioButton Content="Латте"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 FontStyle="Italic"
                                 GroupName="TypeDrink"
                                 Background="#FF4C2B2B"
                                 BorderBrush="Black"
                                 Height="25" Checked="RadioButton_Checked_4"/>
                        <RadioButton Content="Раф"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 FontStyle="Italic"
                                 GroupName="TypeDrink"
                                 Background="#FF4C2B2B"
                                 BorderBrush="Black"
                                 Height="25" Checked="RadioButton_Checked_5"/>
                        <RadioButton Content="Чай"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 FontStyle="Italic"
                                 GroupName="TypeDrink"
                                 Background="#FF4C2B2B"
                                 BorderBrush="Black"
                                 Height="25" Checked="RadioButton_Checked_6"/>
                        <RadioButton Content="Сок"
                                 FontFamily="Comic Sans Ms"
                                 FontSize="14"
                                 FontStyle="Italic"
                                 GroupName="TypeDrink"
                                 Background="#FF4C2B2B"
                                 BorderBrush="Black"
                                 Height="25" Checked="RadioButton_Checked_7"/>
                    </StackPanel>
                    <StackPanel >
                        <Label Content="Количество сахара"
                           FontFamily="Comic Sans Ms"
                           FontSize="18">
                            <Label.Effect>
                                <DropShadowEffect/>
                            </Label.Effect>
                        </Label>
                        <StackPanel Orientation="Horizontal">
                            <Button Height="20"
                                Width="20"
                                Margin="20,0,0,0"
                                Background="Transparent"
                                BorderBrush="Black"
                                Content="--"
                                FontWeight="Bold"
                                Click="Btn_minusSugar"/>
                            <Label Content="0"
                               x:Name="countsugar"/>
                            <Button Height="20"
                                Width="20"
                                Margin="0,0,0,0"
                                BorderBrush="Black"
                                Background="Transparent"
                                Content="++"
                                FontWeight="Bold"
                                Click="Btn_plusSugar"/>
                        </StackPanel>
                    </StackPanel>
                </StackPanel>
<StackPanel Grid.Row="2" Grid.Column="0" HorizontalAlignment="Right">

            <TextBlock Text="Цена:  "
                       FontFamily="Comic sams MS"
                       FontSize="25"
                       FontStyle="Italic"
                       />

        </StackPanel>
        <StackPanel Grid.Row="2"
                    Grid.Column="1"
                    HorizontalAlignment="Left"
                    VerticalAlignment="Top">

                <TextBox Text="0"
                           FontSize="20"
                           FontFamily="comic sans ms"
                           x:Name="resultPrice"
                           FontStyle="Italic"
                           TextChanged="resultPrice_TextChanged"
                           Background="Transparent"
                           BorderBrush="Transparent"
                           IsReadOnly="True"/>

C#
 private void Btn_plusSugar(object sender, RoutedEventArgs e)
    {
        int _countSugar = Convert.ToInt32(countsugar.Content);
        _countSugar = _countSugar + 1;
        countsugar.Content = _countSugar;
        if (_countSugar >=5)
        {
            MessageBox.Show("Извините мы не кладем в кофе больше 5 сахара","Уведомление");
            _countSugar = 5;
        }
        countsugar.Content = _countSugar;
    }

    private void Btn_minusSugar(object sender, RoutedEventArgs e)
    {
        int _countSugar = Convert.ToInt32(countsugar.Content);
        _countSugar = _countSugar - 1;
        countsugar.Content = _countSugar;
        if (_countSugar < 0)
        {

            _countSugar = 0;
        }
        countsugar.Content = _countSugar;
    }

    private void RadioButton_Checked_1(object sender, RoutedEventArgs e)
    {
        int price = Convert.ToInt32(resultPrice.Text);
        price = price + 70;
        resultPrice.Text = price.ToString();
    }

    private void RadioButton_Checked_2(object sender, RoutedEventArgs e)
    {
        int price = Convert.ToInt32(resultPrice.Text);
        price = price + 80;
        resultPrice.Text = price.ToString();
    }

У меня только прибавление, а хотелось бы ещё чтобы прошлое выбранное вычитывалось из итоговой цены
Пример:
Я выбираю сначала маленький кофе (Цена 50)
Потом выбираю экспрессо (цена ставится 140)
Передумываю и выбираю Латте (у меня становится 260, а нужно чтобы было 170)

A: Не нужен здесь никакой код для того, чтобы понять и решить эту задачу.
Не нужно ничего вычитать. Просто текущую цену заменяете новой. Допустим, есть несколько категорий: основной продукт, сахар, молоко. Итоговая стоимость равна сумме стоимостей категорий. В каждой категории может быть выбрано только одно значение со своей стоимостью. Сделали новый выбор - подсчитали итоговую стоимость.

A: Вам надо проверить вы выбрали или нет элемент
private void checkBox_CheckedChanged(object sender, EventArgs e)
{
    CheckBox checkBox = (CheckBox)sender; // приводим отправителя к элементу типа CheckBox
    if (checkBox.Checked == true)
    {
        // выбрали экспрессо
        price += 70;
    }
    else
    {
       //  отказались от экспрессо
        price -= 70;
    }
}

кода вы снимаете флажок с элемента он становиться "checkBox.Checked == false" когда выбираете "checkBox.Checked == true"
если возникли вопросы напишите


text:
Q: Numerical analysis of parabolic obstacle problem I want to solve a parabolic obstacle problem, written as a variational inequality: For almost all $t\in [0,T]$
\begin{align*}
\langle u'(t), v - u(t)\rangle +a(u(t),v-u(t)) \geq \langle f(t),v-u(t)\rangle \quad \forall v \in K
\end{align*}
with $K = \{v \in H^1_0(\Omega) ~\vert ~ v \geq \chi ~ \text{ f.a.a }~ x \in \Omega\}$ and $u(0) = u_0$. Now we will discretize this inequality in time using, for instance, the explicit Euler Scheme. After this we need to solve an elliptic problem in each timestep. This will be done by a primal-dual-active-set method following Bartels book "Numerical methods for Nonlinear Partial Differential Equations". Can someone give me a hint or literature, how to prove the convergence of this "method" to a solution of the obstacle problem?
Thanks in advance, FFoDWindow

A: There's an overview of available schemes in chapter III of
Roland Glowinski, MR 737005 Numerical methods for nonlinear variational problems, ISBN: 0-387-12434-9.
(of which there is also reprint from 2008). The schemes are presented and a few references for their behaviour are given. In particular, this book references chapter 6 of
Roland Glowinski, Jacques-Louis Lions, and Raymond Trémolières, MR 1333916 Numerical analysis of variational inequalities, ISBN: 0-444-86199-8.
which might take you further, even though at a first glance I didn't see the explicit Euler method covered.


text:
Q: launch a system command via Javascript in Google Chrome I want to execute a local program on my computer via Javascript in Chrome. In Firefox, it can be done as follows
var file = Components.classes["@mozilla.org/file/local;1"]
    .createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(cmd);

var process = Components.classes["@mozilla.org/process/util;1"]
    .createInstance(Components.interfaces.nsIProcess);
process.init(file);

process.run(false, args, args.length);

Can you please any one help me to execute local program from chrome extension?
Thanks

A: You can't do this. Chrome's sandbox security model doesn't let you arbitrarily execute programs on the user's machine; that could be extremely dangerous. It would be theoretically possible to do this using NPAPI, but it's unlikely that such a plugin would be approved for the Chrome Web Store. If this is only for private use you could create a plugin using NPAPI and then do whatever you want, you just wouldn't be able to distribute the plugin through the Chrome Web Store.

A: You can call an jQuery ajax process in order to execute a php script, that can execute commands using exec(). Javascript is a client-side language, but you can use jQuery...
You can find out how in this link:
http://www.sitepoint.com/take-command-ajax/


text:
Q: \defaultfontfeatures in v2.4 of fontspec Why in the following example, lipsum text does not appear in blue color as described in the fontspec manual?
\documentclass{article}
\usepackage{lipsum}
\usepackage{fontspec}
\newfontfamily\myfont{Times New Roman}
\defaultfontfeatures[\myfont]{Color=blue}
\begin{document}
\myfont
\lipsum[1]
\end{document}

A: This is somehow strange but it seems that \defaultfontfeatures needs to be before \newfontfamily:
\documentclass{article}
\usepackage{lipsum}
\usepackage{fontspec}
\defaultfontfeatures[\myfont]{Scale=2}
\newfontfamily\myfont{Times New Roman}
\begin{document}
\myfont
\lipsum[1]
\end{document}


text:
Q: Controling how edges bend How do I obtain fine-grained control of edge-paths in a tikz-graph? I want to avoid "crossing" edges in larger graphs as well as too small distances in smaller graphs.
My idea was to introduce invisible nodes and connect the edges via these nodes:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows,graphs,matrix,positioning}

\begin{document}

\begin{tikzpicture}[>=stealth',
    font=\sffamily\small,
    every node/.style={align=center},
    skip loop left/.style={to path={-- ++(-#1,0)|- (\tikztotarget)}},
    skip loop right/.style={to path={-- ++(#1,0)|- (\tikztotarget)}},
    hv path/.style ={to path={-| (\tikztotarget)}},
   vh path/.style ={to path={|- (\tikztotarget)}},
]
\node[draw] (root) {{.}};
\node[draw, left of=root] (C) {{C}} ;
\node[below=of C] (bC) {};
\node[draw, left of=C] (B) {{B}} ;
\graph[use existing nodes] {
 root->[edge label=0, loop above]root;
 C->[edge label=1]root;
 C->[edge label=0, loop above]C;
 B->[edge label=0, loop above]B;
 B->[edge label=1]C;
 B--bC->[edge label=2, bend right]root;
};
\end{tikzpicture}
\end{document}

The result is, however, unsatisfying:

Not only would I now have to fine-tune the node position, there is also the problem of the edge shape.
Is there any solution that allows me to specify a minimum distance each edge must have from all nodes?

A: There are several ways of controlling edges.
You approach of invisible nodes can be improved by reducing the size of the node to zero. Then the ends of the edges will meet and the node will not need invisible space e.g. regarding the border of the picture. Define anywhere before the picture
\tikzset{invisible/.style={minimum width=0mm,inner sep=0mm,outer sep=0mm}}

and mark the node as invisible:
\node[below=of C,invisible] (bC) {};

Alternatively, use (bC.center) as begin and end point of edges instead of (bC). However, the node will still occupy space.
Basically, your invisible nodes should not be necessary most of the time. First, you can control to some extent how strong edges bend:
 B->[bend left=120]root;

So far the to[out=...,in=...] specification was always sufficient for my needs. E.g., the command
 \draw (C) to[out=-20,in=90,edge label=a,swap] (bC.center);

draws a line from C to bC, where the edge starts from C at -20 degrees (measured from the positive x-axis) and ends up at bC with an angle of 90 degrees (which is the top position).
 \draw[->] (C) to[out=-135,in=45,edge label=b,swap] (B);

draws a line from B to C, starting to the south-west and arriving from the north-east.
Here is the complete experimental code and its output.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows,graphs,matrix,positioning}
\begin{document}
\tikzset{invisible/.style={minimum width=0mm,inner sep=0mm,outer sep=0mm}}
\begin{tikzpicture}[>=stealth',
    font=\sffamily\small,
    every node/.style={align=center},
    skip loop left/.style={to path={-- ++(-#1,0)|- (\tikztotarget)}},
    skip loop right/.style={to path={-- ++(#1,0)|- (\tikztotarget)}},
    hv path/.style ={to path={-| (\tikztotarget)}},
   vh path/.style ={to path={|- (\tikztotarget)}},
]
\node[draw] (root) {{.}};
\node[draw, left of=root] (C) {{C}} ;
\node[below=of C,invisible] (bC) {};
\node[below=of C] (bC) {};
\node[draw, left of=C] (B) {{B}} ;
\graph[use existing nodes] {
 root->[edge label=0, loop above]root;
 C->[edge label=1]root;
 C->[edge label=0, loop above]C;
 B->[edge label=0, loop above]B;
 B->[edge label=1]C;
 B->[bend left=120]root;
 B--[bend right=40]bC.center->[edge label=2, bend right]root;
};
\draw (C) to[out=-20,in=90,edge label=a,swap] (bC.center);
\draw[->] (C) to[out=-135,in=45,edge label=b,swap] (B);
\end{tikzpicture}
\end{document}


text:
Q: Tests using Page Factory Design and Page Object Model opens two instances of the browser using Selenium and Java I have a test in Selenium WebDriver with Page Object Model, if I run the following test open two windows in the Chrome browser, first window is empty in a URL line. How I can opening only one with onet.pl URL?
I trying deleting initialize Chrome driver but will have null.exception error.
What am I doing wrong?
package Pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;

public class LoginPage {
    private WebDriver driver;
    //private WebDriverWait wait;

    public LoginPage() {
        this.driver = new ChromeDriver();
        //wait = new WebDriverWait(driver,10);
    }
    @FindBy(xpath="//div[@class='col-md-12']//form")
    private WebElement loginForm;

    @FindBy(id="username")
    private WebElement loginField;

    @FindBy(id="password")
    private WebElement passwordField;

    @FindBy(xpath="//button[@class='btn btn-multisport-default btn-multisport-large btn-full-width login-button']")
    private WebElement buttonLogin;
    public void open() {
        driver.get("https://onet.pl");
    }
    public void enterLogin() {
        String login = "vadim1234@test.pl";
        loginField.sendKeys(login);
    }
    public void enterPassword() {
        String password = "Benefit!";
        passwordField.sendKeys(password);
    }
    public void login() {

        buttonLogin.click();
    }
}

And test code:
import Pages.Dashboard;
import Pages.LoginPage;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;

import java.util.concurrent.TimeUnit;

public class LogIn {
    @Test
    public void correctLogin() {
        System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        loginPage.open();
        loginPage.enterLogin();
        loginPage.enterPassword();
        loginPage.login();
        driver.close();
        driver.quit();
        Dashboard dashboard = new Dashboard(driver);
        dashboard.getLoggedUser();
    }
}

A: From your test class as you are passing the reference of the driver:
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);

In LoginPage class, within the constructor, instead of:
public LoginPage() {
    this.driver = new ChromeDriver();
    //wait = new WebDriverWait(driver,10);
}

you need to do reuse the instance passed as follows:
public LoginPage(WebDriver loginPageDriver) {
    this.driver=loginPageDriver;
}

That would solve the issue of 2 browsers getting opened.

References
You can find a couple of relevant detailed discussions in:

*

*Selenium [Java] PageFactory Design : Where do I write my Assertions following Page Object Model


text:
Q: How do I transfer old Pokemon to Black/White with ONE Nintendo DS? I only have one Nintendo DS Lite. Most of my friends don't play games thus don't have a NDS. I want to transfer over some Pokemon such as Skitty, Delcatty, and a few others that I am not able to get. How can I get my old Pokemon over? I don't have my old GBA games sadly either. My Skitty (my favorite Pokemon...) is a shiny Skitty so it is important to me.

A: Sorry to tell you, but you can't. You need to use another Nintendo DS (or DSi, 3DS, anything). The guy at the Transfer Lab even tells you that you need another one.

A: From: http://bulbapedia.bulbagarden.net/wiki/Pok%C3%A9_Transfer:

Poké Transfer (Japanese: ポケシフター PokéShifter) is a feature in the Generation V games Pokémon Black and White and Pokémon Black and White 2. It is located in the Poké Transfer Lab on Route 15.
The Poké Transfer is a feature that allows Pokémon from any Generation IV game to be transferred to Pokémon Black and White, similar to Generation IV's Pal Park. It can be visited after the main storyline of the games has been completed and the player has obtained the National Pokédex.


text:
Q: Installing open-vm-tools in Ubuntu via Puppet; what's the lesser evil? In an ideal world, configuring puppet to install the open-vm-tools should be as simple as this:
class vm-tools {
    package { 'open-vm-tools':
        ensure => installed
    }
    package { 'open-vm-dkms':
        ensure => installed
    }
}

But, that opens up an ugly can of dependency creep; it installs X, which obviously doesn't belong on servers.  As of Ubuntu 10.04, these packages both end up recommending the open-vm-toolbox package of GUI tools:
# apt-cache depends open-vm-dkms
open-vm-dkms
  Depends: dkms
  Depends: make
  Suggests: open-vm-toolbox
  Recommends: open-vm-tools

# apt-cache depends open-vm-tools
open-vm-tools
  Depends: libc6
  Depends: libfuse2
  Depends: libgcc1
  Depends: libglib2.0-0
  Depends: libicu44
  Depends: libstdc++6
  Recommends: open-vm-source
  Recommends: open-vm-toolbox
  Recommends: ethtool
  Recommends: zerofree

Recommended packages are always installed by default.  It's clearly not desirable to install X dependencies by default when installing a package that is described as "CLI Tools".
The feature request against Debian was immediately rejected for this reason, but cooler heads did not prevail in Ubuntu.  It seems that within the last week, there's some recognition that this was an ill-advised change, but that's of no help until the next LTS release rolls around.
The behavior to install recommended packages is easily enough disabled on the command line with the --no-install-recommends option, but through puppet there's no support for doing this, and a tangled mess of tickets requesting that support haven't gone far in 3 years.
The other option is to just disable recommended packages throughout the whole system via apt.conf, which is a massive change to package behavior with impacts reaching further than I'd like.
I've resigned myself to doing it the lazy way;
exec { 'open-vm-tools install':
    command => '/usr/bin/apt-get install -y --no-install-recommends open-vm-dkms open-vm-tools',
    creates => '/usr/lib/open-vm-tools',
}

But this is clearly "doing it wrong".  Am I missing something that would make this all work the way it's supposed to, or is this the best hackish workaround to this issue?

A: Bug 1766 indicated that the aptitude provider installs recommended packages, while the apt provider does not.
If that's correct (I've not verified it myself), then the following may work more cleanly:
package { [ "open-vm-tools", "open-vm-dkms" ]:
  ensure   => installed,
  provider => apt,
}

Adapted from Puppet Type Reference, "package" section.

Edit after further investigation: since the apt provider is the default on Ubuntu and Debian, use the aptitude provider for these packages, and add a suitable ~/.aptitude/config for root.
package { [ "open-vm-tools", "open-vm-dkms" ]:
  ensure   => installed,
  provider => aptitude,
  require  => File["/root/.aptitude/config"];
}
file { "/root/.aptitude/config":
  ensure  => present,
  content => 'APT::Install-Recommends "0";';
}

Not perfect, but more concise than a giant exec line.

A: It looks like on 12.04, apt-get install open-vm-tools no longer installs X.
Ubuntu wiki on VMware Tools


text:
Q: I am getting fractional artifacts (pieces of metal) instead of whole ones. It seems that the edges are not continuous but they are My goal is to detect objects placed on a white surface. From there, count how many there are and calculate the area of each one.
It seems that this algorithm is detecting its edge but counting it as multiple objects.
original picture

picture after edge detection

part of the picture with problems

results

In short, I am using "canny" and "connected components" and I am getting fractional objects instead just a whole object.

A: Following code should do the job, you might need to tweak minItemArea and maxItemArea to filter objects.
import numpy as np
import cv2
import matplotlib.pyplot as plt

rgb = cv2.imread('/path/to/your/image/items_0001.png')
gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)

imh, imw = gray.shape

th = cv2.adaptiveThreshold(gray,255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV,21,5)

contours, hier = cv2.findContours(th.copy(),cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)

out_img = rgb.copy()
minItemArea = 50
maxItemArea = 4000

for i in range(len(contours)):
    if hier[0][i][3] != -1:
        continue

    x,y,w,h = cv2.boundingRect(contours[i])
    if minItemArea < w*h < maxItemArea:
        cv2.drawContours(out_img, [contours[i]], -1, 255, 1)

plt.imshow(out_img)