text:
Q: How can i make a task for each item in the listBox if i select more then one item? First this is the listBox selected index changed event:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (listBox1.SelectedItem != null)
            {
                label4.Text = listBox1.SelectedItem.ToString();
                string startTag = "Url: ";
                string endTag = " ---";
                int startTagWidth = startTag.Length;
                int endTagWidth = endTag.Length;
                int index = 0;
                index = label4.Text.IndexOf(startTag, index);
                int start = index + startTagWidth;
                index = label4.Text.IndexOf(endTag, start + 1);
                string g = label4.Text.Substring(start, index - start);
                label4.Text = g;
                mainUrl = g;
            }
        }

A: Solved it by adding this method:
private string GetUrl(object obj)
        {
            string startTag = "Url: ";
            string endTag = " ---";
            int startTagWidth = startTag.Length;
            int endTagWidth = endTag.Length;
            int index = 0;
            index = obj.ToString().IndexOf(startTag, index);
            int start = index + startTagWidth;
            index = obj.ToString().IndexOf(endTag, start + 1);
            string g = obj.ToString().Substring(start, index - start);
            mainUrl = g;
            return mainUrl;
        }

And using it in the DoWork event like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            object input = e.Argument;
            string f = GetUrl(input);
            this.Invoke(new MethodInvoker(delegate { label2.Text = "Website To Crawl: "; }));
            this.Invoke(new MethodInvoker(delegate { label4.Text = f; }));
            if (offlineOnline == true)
            {
                offlinecrawling(f, levelsToCrawl, e);
            }
            else
            {
                webCrawler(f, levelsToCrawl, e);
            }
        }


text:
Q: Why i need cancel tasks in this queue example? Well I am looking into python documentation for study for my work. I am new to python and also programming, I  also do not understand concepts of programming like async operations very well.
I usign Fedora 29 with Python 3.7.3 for try examples of queue and the lib asyncio.
Follow the example of queue and async operations below:
import asyncio
import random
import time

async def worker(name, queue):
    while True:
        # Get a "work item" out of the queue.
        sleep_for = await queue.get()

        # Sleep for the "sleep_for" seconds.
        await asyncio.sleep(sleep_for)

        # Notify the queue that the "work item" has been processed.
        queue.task_done()

        print(f'{name} has slept for {sleep_for:.2f} seconds')

async def main():
    # Create a queue that we will use to store our "workload".
    queue = asyncio.Queue()

    # Generate random timings and put them into the queue.
    total_sleep_time = 0
    for _ in range(20):
        sleep_for = random.uniform(0.05, 1.0)
        total_sleep_time += sleep_for
        queue.put_nowait(sleep_for)

    # Create three worker tasks to process the queue concurrently.
    tasks = []
    for i in range(3):
        task = asyncio.create_task(worker(f'worker-{i}', queue))
        tasks.append(task)

    # Wait until the queue is fully processed.
    started_at = time.monotonic()
    await queue.join()
    total_slept_for = time.monotonic() - started_at

    # Cancel our worker tasks.
    for task in tasks:
        task.cancel()
    # Wait until all worker tasks are cancelled.
    await asyncio.gather(*tasks, return_exceptions=True)

    print('====')
    print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')
    print(f'total expected sleep time: {total_sleep_time:.2f} seconds')

asyncio.run(main())

Why in this example I need cancel the tasks? Why I can exclude this part of code
# Cancel our worker tasks.
    for task in tasks:
        task.cancel()
    # Wait until all worker tasks are cancelled.
    await asyncio.gather(*tasks, return_exceptions=True)

and the example work fine?

A:
Why in this example i need cancel the tasks?

Because they will otherwise remain hanging indefinitely, waiting for a new item in the queue that will never arrive. In that particular example you are exiting the event loop anyway, so there's no harm from them "hanging", but if you did that as part of a utility function, you would create a coroutine leak.
In other words, canceling the workers tells them to exit because their services are no longer necessary, and is needed to ensure that resources associated with them get freed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I need to check if the 1st column of the last row in a file, matches with the 1st column of the next file & so on I have n number of files with sorted data, I need to check if the data in 1st column of the last row of File1 is matching with the data present in the 1st column of File2 and so on.
Once a match is found, the matched data from the 2nd file should be copied into the 1st file...the data from the 3rd file should be copied in the 2nd file when match is found between file2 and file3.
how can we solve this problem in unix?
For Example:
File1:
A1 apple
B1 banana
C1 Carrot

File2:
C1 Cabbage
C1 Cauliflower
D1 Doughnuts
E1 Egg

File3:
E1 Eggplant
F1 Fig

.... so on
Output:
File1
A1 apple
B1 banana
C1 Carrot
C1 Cabbage
C1 Cauliflower

File2:
D1 Doughnuts
E1 Egg
E1 Eggplant

File3:
F1 Fig

A: I suggest the following : each line must end with a line break and no empty lines at the end of files.
#!/bin/bash
if [ $(tail -n 1 $1 | awk '{ print $1 }' ) == $(head -n 1 $2 | awk '{ print $1 }') ]
then
    cat $2 >> $1
    rm $2
else if [ $(head -n 1 $1 | awk '{ print $1 }') == $(tail -n 1 $2
        | awk '{ print $1}') ]
    then
        cat  $1 >> $2
        rm $1
    fi
fi


text:
Q: Make the UIWebview fill screen How do I make the content in the UIWebView fill the whole screen? The UIWebView fills the iphones width correctly, however I need to doubletap the image in the UIWebview to make it stretch out to the bounds.
Help much appriciated!

A: Try setting scalesPageToFit to YES on your UIWebView.


text:
Q: JavaFx Stylesheet in the same folder Not found My Project TreeView is like this:
project
      - src
          -package
                 -javafx.java, style.css
I tried this  piece of code as well as just directly putting in style.css
    scene.getStylesheets().add("../src/package/style.css");

A: Try do it this way:
    scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());


text:
Q: How to publish Codenarc report for Gradle project in Jenkins? I am trying to generate Codenarc reports for my Gradle Groovy project and publish them in Jenkins.
I successfully configured my Gradle project to produce Codenarc reports with:
build.gradle
apply plugin: 'codenarc'
...
dependencies {
    codenarc 'org.codenarc:CodeNarc:0.21'
    ...
}
codenarc {
    configFile = file('config/codenarc/codenarc.groovy')
    // sourceSets = [project.sourceSets.main] // run codenarc on production sources only
    ignoreFailures = true // Let the build finish even though there are code warnings
    reportFormat = 'xml'
    reportsDir = new File("build/reports/codenarc")
}

config/codenarc/codenarc.groovy
// Read and choose rules here: http://codenarc.sourceforge.net/codenarc-rule-index.html
ruleset {
    ruleset('rulesets/basic.xml')
}

I also set up a job on Jenkins with the Violations plugin, but when the Violations report is generated it does not show the actual code violations. It just shows statistics, and a blank page if I press the groovy file with violations.
I have Grails projects with the Codenarc plugin, which shows up with full code snippets in the violations report, so I am guessing there is something wrong with my Codenarc setup in Gradle?
Any help or suggestions are very welcome!
Edit:
If relevant, the resulting Codenarc XML looks like this:
<?xml version='1.0'?>
<CodeNarc url='http://www.codenarc.org' version='0.21'>
    <Report timestamp='07-10-2014 15:31:18'/>
    <Project title=''>
        <SourceDirectory>src\groovy</SourceDirectory>
    </Project>
    <PackageSummary totalFiles='124' filesWithViolations='118' priority1='0' priority2='156'
                    priority3='143'></PackageSummary>
    <Package path='testmodel' totalFiles='124' filesWithViolations='118' priority1='0' priority2='156'
             priority3='143'></Package>
    <Package path='testmodel/begivenheder' totalFiles='31' filesWithViolations='30' priority1='0' priority2='32'
             priority3='17'>
        <File name='AbstraktTest.groovy'>
            <Violation ruleName='ClassJavadoc' priority='2' lineNumber='5'>
                <SourceLine><![CDATA[@CompileStatic]]></SourceLine>
                <Message><![CDATA[Class testmodel.begivenheder.AbstraktAendring missing JavaDoc]]></Message>
            </Violation>
            ...
        </File>
    </Package>
    <Rules>
        <Rule name='AbcMetric'>
            <Description>
                <![CDATA[Checks the ABC size metric for methods/classes. A method (or "closure field") with an ABC score greater than the maxMethodAbcScore property (60) causes a violation. Likewise, a class that has an (average method) ABC score greater than the maxClassAverageMethodAbcScore property (60) causes a violation.]]></Description>
        </Rule>
        ...
    </Rules>
</CodeNarc>

A: Consider using HTML Publisher plugin
You can configure report parameters in job configuration Post-build Actions or if you are using pipeline, add these lines to your Jenkinsfile:
node('slaveName') {

    // git, build, test, stages omitted

    stage('Publish') {

        echo 'Publish Codenarc report'
        publishHTML(
                target: [
                        allowMissing         : false,
                        alwaysLinkToLastBuild: false,
                        keepAll              : true,
                        reportDir            : 'target/site',
                        reportFiles          : 'codenarc.html',
                        reportName           : "Codenarc Report"
                ]
        )
    }

}


text:
Q: Entity Framework: adding two model with relation same time to my database I am trying to add some data to my database using Entity Framework code-first approach.
This is my code:
Member member = new Member
                {
                     ...
                     Cards = new List<Card>() {new Card {  Number = model.CartBankNumber, RegisterTime = DateTime.Now, Status = CardStatus.Verifying }  },
                };
db.Member.Add(member);
await db.SaveChangesAsync();

This is my Member model class:
public class Member
{
    ...
    public Member()
    {
        Cards = new List<Card>();
    }

    [Display(Name = "Cards", ResourceType = typeof(Resources))]
    public virtual ICollection<Card> Cards{ get; set; }
}

And Card model class:
public class Card
{
    ...
    [Display(Name = "Id", ResourceType = typeof(Resources))]
    public int Id { get; set; }

    [ForeignKey("Member")]
    public string MemberId { get; set; }

    public virtual Member Member { get; set;}
}

Why is MemberId null?


text:
Q: Send data via '.getJson' in jQuery and retrive on 'PHP' File So i want to send a variable to my php page and output appropriate json there based on the data.
THis is what i did.I am new to jquery but have done php
                $(function() {

        $("#json-one").change(function() {

            var dropdown = $(this);
        var name=dropdown.val();
            $.getJSON("categories_php?name=",{ "name": name },
       function(data) {

            prompt(data.name);
                            var $jsontwo = $("#json-two");
                $jsontwo.append("<option>" + data.name + "</option>");

            });
        });

    });

on the php page for test i have not done much
    <?php
    $m=new Mongo();
    $db=$m->admin;
    $collection=$db->categories;
    $cur=$collection->find();
    $name['name']= $_REQUEST['name'];
    print_r(json_encode($name));

?>

A: You can use:
 $.getJSON("categories_php",{ name: name }, function() {
      //Some code
 });


text:
Q: Can't set bulk_create to a variable (Django) I'm using bulk_create to create multiple profiles:
def bulk_create_and_get(cls, profile_ids):
    tickets_to_create = []
    for profile_id in profile_ids:
        ticket = cls(profile_id=profile_id)
        tickets_to_create.append(ticket)

    cls.objects.bulk_create(tickets_to_create)

Were the cls is the Ticket Class model
Can I save my bulk_create to a variable and return it?
created_tickets = cls.objects.bulk_create(tickets_to_create)

Instead of querying for the tickets I just created?
created_tickets = cls.objects.filter(
            Q(profile_id__in=profile_ids) |
            Q(unregistered_profile_id__in=profile_ids)
          )

return created_tickets


text:
Q: How to create opportunity from an incoming mail in Odoo 11? In odoo 9 we can create opportunity from an incoming mail, but this feature is not available in Odoo 11, Any idea how can i achieve this functionality in Odoo 11.

A: Do you mean this one?
If yes, it will be not shown until option "Manually Assignation of Incoming Emails" checkmarked.

A: I found the answer, it's quite simple, Go to settings>email>aliases, select your email aliases, click edit and add default value as {'type': 'opportunity'}.


text:
Q: AVAudioPlayer playing overtime viewcont. loads [Swift] In my mainmenuviewcontroller in viewDidLoad, I tell it to play a background song. Problem is, when a user goes to another view and then goes back to the main menu, it starts playing the song again, and the two copies overlap. I tried to put this in the viewDidLoad but it didn't work
if themePlayer.playing == false {

themePlayer.prepareToPlay()

themePlayer.play()

}

It just kind of ignores the if condition and plays anyways. How can I fix this?

A: -viewDidLoad will only run when the view is initially loaded. Since your player is still playing the song when you navigate away from the mainmenuviewcontroller this indicates that the view controller is never being deallocated. Try putting the if condition in the -viewDidAppear or -viewWillAppear method.
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated);

    if themePlayer == nil {
        // Either it's the first time this view is loaded, or themePlayer was deallocated
        let soundURL = NSBundle.mainBundle().URLForResource("pres song", withExtension: "mp3")
        themePlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
        themePlayer.numberOfLoops = -1
        themePlayer.volume = 0.1
        themePlayer.prepareToPlay()
        themePlayer.play()
    }

    if themePlayer.playing == false {
            themePlayer.prepareToPlay()
            themePlayer.play()
        }
}

If in doubt in the future on if something is being called, use breakpoints and step through the code.


text:
Q: URL schema and open program my iPhone program use a URL schema and work successful, to do this is only fallow this tutorial. Ok, when the program start, i use the function
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;

And the launchOptions have all data that I need. This problem is solved. BUT, and when I use the URL schema and my program IS OPEN. Ok, the program open and show the last windows that was in it. But I want to go to another place.
The question: How can I know the program was reactivated from a web browser with a URL Schema? What function I have to use? I didn't found any that can solve it.

A: YES... The correct function is this!!!! (Thanks onnoweb)
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation

It's a little obscure, why not use "wasOpenedByURL". Bah.. I have to use all function in a object to know what it do.


text:
Q: Typeorm keep ViewEntity in sync I am trying to sync my views in production. My first thought was using migrations, but when I try the generate command it doesn't work as nicely as I expect. It wants to create the view and then insert the info about the view into the typeorm_meta table. The problem with that is that it doesn't drop the view before, so I got the error that the view already exists. If I add the drop view before creating them this works fine. But then I get the error that I don't have the permission to insert into typeorm_meta, but I have all rights on this database.
I also tried to add synchronize to every ViewEntity to just skip migrating views, but that doesn't work either.
Has anyone an Idea to get this working?
Thanks in advance.


text:
Q: Ajax/href to express route with res.render I have a problem with calling a route via ajax/href and rendering a view.
So I want to edit data in a TableView. If I click on the edit button, it should redirect me to my edit view with the id of the data as a parameter. I tried it with window.location.href and via an ajax call.
$('#EditButton').click(function(id){
    var url1 = '/edit' + '/' + id
    window.location.href = url1;
    // $.ajax({
    //     url: url1,
    //     type: 'GET',
    //     error: function (e) {
    //         console.log(e);
    //     },
    //     success: function(data) {
    //         console.log('req for edit was a success');
    //     }
    // })
})

My route in express looks like this:
app.get('/edit/:id', function(req, res) {
    var id = req.params.id;
    console.log('Params Received Id: ' + id);

    db.findData(id, function(data) {
        console.log('Retrieved from DB: ' + data);
        res.render('editData', {
            name: data.name,
            desc: data.desc,
        });
    });
});

With window.location.href it at least shows the editData view, but I cannot access the passed parameter (name, desc) via handlebars. With the ajax call it shows the view in the console, not the browser; I don't know if the
data is passed. Does someone have an idea what I am doing wrong?


text:
Q: In php cron syntax url i have two parameters passed but it gets one parameter this my url cron syntax
1.* 30 * * wget http://myappone.com/universitysaver/scripts /signUpForm3.php?userId=49crbrGzdPk3&value=1.99

*

*its gets only one argument that is first argument

*the second argument its not displayed

*iam using $_REQUEST['userId'];

*and $_REQUEST['value'];

*and another thing is iam changing the values first argument is value second argument is userId its displayes value but it not display userId

*30 * * wget http://myappone.com/universitysaver/scripts /signUpForm3.php?userId=49crbrGzdPk3&value=1.99

*its get only first argument the second argument  its not get

*i want to get two arguments how can i get

*please help me

*thanks for advance

A: In bash & is special character and tells the shell to put the process in the background, so nothing after the & is read. you need to escape your string
30 * * * * wget http://myappone.com/universitysaver/scripts /signUpForm3.php?userId=49crbrGzdPk3\&value=1.99

or
30 * * * * wget "http://myappone.com/universitysaver/scripts /signUpForm3.php?userId=49crbrGzdPk3&value=1.99"


text:
Q: Trying to read a file from master is not working on github action I have a js file like this
// test.js
exec(`git show master:src/path/to/my.json`, (err, stdout, stderr) => {
    if (err) {
        console.log('failed', stderr);
        return;
    }
    ....
}

and a script cmd
// package.json
scripts: {
    doIt: "node test.js"
}

Executing this in github action
...
   - name: Checkout
      uses: actions/checkout@v2.3.4
      with:
        fetch-depth: 0
    - name: DoIt
      run: yarn doIt
...

but getting error:
failed fatal: invalid object name master

Here is the github action output
* [new branch]          master                  -> origin/master

A: Considering the default naming branch has changed on GitHub, from master to main, check the one for the repository accessed by your GitHub action.
If the default branch is main, master would not exist.
Adding fetch-depth:0 is a good idea in order to fetch the all history (therefore all the branches), as seen in issue 438
But a workaround is: git show origin/master:src/path/to/my.json, as suggested in teh comments will work even if the master branch was not properly updated.


text:
Q: Show upload image progress Multipart In Fragment B, I have a submit button used to submit image to server. When submit button is clicked, it will return to Fragment A. I using Multipart to upload image to server, and the process is running on Thread so user can do other task while waiting image to upload.
Fragment B (when submit button is clicked)
 inner class SimpleThread() :Thread() {
            override fun run() {
                for (i in newList!!) {
                    val service = RetrofitFactory.makeRetrofitService()
                    GlobalScope.launch(Dispatchers.IO) {
                        val request2 = WebApi.createImage(
                            activity,File(i)
                        )
                    }
                }
            }

WebApi
suspend fun createImage(
        file: File?
    ): WebApiResponse.Image? {
        val image = file?.let {
            MultipartBody.Part.createFormData(
                "image",
                it.getName(),
                RequestBody.create(MediaType.parse("image/*"), it)
            )
        }

        return RetrofitFactory.apiCall(context) {
            RetrofitFactory.makeRetrofitService().submitImages(
              image
            )
        }
    }

RetrofitService
@Multipart
    @POST("create_image")
    fun submitImages(
        @Part image: MultipartBody.Part?
    ): Deferred<Response<WebApiResponse.Image>>

I am able to upload image to server, but how can I show a upload image progress on Fragment A ?
Any help is appreciated.

A: so after just a little bit of research I found two ways for you
1- if you are using RxJava I would suggest to follow the instructions and cautions in this link
display progress of multipart with retrofit using RxJava
2- if you are not using RxJava add a ProgressResponseBody to the retrofit builder that would look something like this:
public class ProgressRequestBody extends RequestBody {
private File mFile;
private String mPath;
private UploadCallbacks mListener;
private String content_type;

private static final int DEFAULT_BUFFER_SIZE = 2048;

public interface UploadCallbacks {
    void onProgressUpdate(int percentage);
    void onError();
    void onFinish();
}

for this one you should use this answer

A: I guess you can use WorkManaget or IntenService for showing the progress.
A sample to send via retrofit2
You can start the process in service. The service can send a new event.

A: Custom RequestBody
    public class FileProgressRequestBody extends RequestBody {

        public interface ProgressListener {
            void transferred(int size);
        }
        private RequestBody mRequestBody;

        protected ProgressListener listener;

        public FileProgressRequestBody(File file, String contentType, ProgressListener listener) {
            this.mRequestBody = RequestBody.create(MediaType.parse(contentType), file);
            this.listener = listener;
        }

        @Override
        public long contentLength() throws IOException{
            return mRequestBody.contentLength();
        }

        @Override
        public MediaType contentType() {
            return mRequestBody.contentType();
        }

        @Override
        public void writeTo(@NonNull BufferedSink sink) throws IOException {
            if (sink instanceof Buffer) {
                // Log Interceptor
                mRequestBody.writeTo(sink);
                return;
            }
            CountingSink countingSink = new CountingSink(sink);
            BufferedSink bufferedSink = Okio.buffer(countingSink);
            mRequestBody.writeTo(bufferedSink);
            bufferedSink.flush();
        }

        protected final class CountingSink extends ForwardingSink {
            private long bytesWritten = 0;

            public CountingSink(Sink delegate) {
                super(delegate);
            }

            @Override
            public void write(@NonNull Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                bytesWritten += byteCount;
                if (listener != null) {
                    long length = contentLength();
                    if (length != 0) {
                        listener.transferred(MathUtils.clamp((int) (bytesWritten * 100 / length), 0, 100));
                    }
                }
            }
        }
}

use MultipartBody.Part.createFormData("image", file.getName(), new FileProgressRequestBody(file, "image/*", youListener));


text:
Q: Would a "downcast if block" be a reasonable language feature? Consider the following "if cast":
class A     { public void f1() { ... } }
class B : A { public void f2() { ... } }

A a = foo(); // might return A or B

if ( a is B ) {
    //  Inside block, implicitly "redeclare" a as type B
    //  It's B, go for it
    a.f2();
    //  Wouldn't compile.
    a = new A();
}

We don't enter the block unless a is a B, therefore within the block, the compiler treats a exactly as if it had been declared as type B. You could assign null to it in the block if it's a reference type, but it would be a compile-time error to assign new A() to it, for example (thanks @ThomasEding for bringing up that question).
Anything that could break that assumption that a is B, could just as easily break the following legal C# as well:
if ( a is B ) {
    B b = a as B;

    b.f2();
}

The former looks to me like syntactic sugar for the latter.
Even if this feature makes sense, I'm sure Anders Hjelberg's lads have more useful features to implement. I'm just wondering if it's a worse idea than I think it is.
UPDATE A serious objection would be that the feature as described adds semantics without adding syntax: From one version of the language to the next, the meaning of the above block would change significantly. It would be more tolerable with a new keyword. But then you'd be adding a new keyword.
Update
A more redable version of this feature was implemented in C#7:
object object2 = new List<Test>();

if (object2 is Dictionary<String, int> foo)
{
    Console.WriteLine(foo.Keys);
}

A: Let's assume features start with 0 points, rather than with -100 points (due to costs associated with implementation, design, etc.).
This feature strikes me as confusing.  I've already declared that a is an A.  If I want to know the compile-time type of a, I only have to look in one place, at the declaration.  While I acknowledge that the implementation is relatively simple (use the code substitution you describe in your question), this also argues in favor of not implementing the feature; it's easy for coders to do it, too.
The truly horrifying thing is that the type of a variable can magically change immediately after a }.  C# very deliberately prevents this from happening (see Simple names are not so simple).  So, I absolutely hate any version of this feature that fails to introduce a new variable during the cast.
If you find yourself constantly casting your types so as to access members of derived classes, it makes me suspect you are misusing inheritance.  Personally, usually in code where I'm using such a conditional, I'm going to break out of my function if the cast fails.  So, my code would look more like this:
B myB = myA as B;
if (myB == null) return;

Which would, under some variant of your proposal, become this:
if (!(myA is B)) return;

or (introducing a new name)
if (!(myA to B myB)) return;

or, using declarative expressions (this is a variant on Jimmy Hoffa's answer)
if (!a.To(out B myB)) return;

With the exception of the approach using declarative expressions, all of these features require learning new C# syntax for a feature that is not at all painful to deal with.  The declarative expression approach is nice in that it is the general case of a specific feature; i.e. allowing coders to make use of an assignment and conditional using a single expression.
The only cost to the declarative expression approach is that it won't work universally; it only works if your special To method is implemented and visible in your current scope.  However, that's a price I'm willing to pay to avoid adding yet more syntax to the C# language; I won't bother using such an extension method unless I'm dealing with code which constantly requires it (and probably not even then).
In summary: This feature isn't needed quite often enough to justify adding new syntax to the language.  However, the more general feature, declarative expressions, may be worth the cost (which is why Microsoft is probably going to pay it).  It not only handles this case, but also handles the annoying two-statement TryParse case (and, like your proposal, makes for clean scope; the type is only in scope on the inside of the conditional).
Update: Declarative Expressions were cancelled.
Update 2: C# 7.0 is adding "out variables". This might be enough for my final example (if (!a.To(out B myB)) return;).  C# 7.0 is also adding "Is-expressions with patterns", which allows, if (!(o is int i)) return;.  This is basically the feature you asked for.

A: As a data point, the Ceylon language allows1 you to do this.
In Ceylon, you would write:
A a = ...
if (is B a) {
   // refer to 'a' as a 'B'
}

or
if (is B b = some_expression_returning_A ) {
   // refer to 'b' as a 'B'
}

There is also a variation of the switch statement that allows you to switch on types, in much the same way.  For example:
void switchOnEnumTypes(Foo|Bar|Baz var) {
    switch(var)
    case (is Foo) {
        print("FOO");
    }
    case (is Bar) {
        print("BAR");
    }
    case (is Baz) {
        print("BAZ");
    }
}

1 - Actually, it requires this, since Ceylon doesn't have an explicit type-cast.  The goal is to avoid core language constructs that can throw exceptions.  They do something similar to design out NPEs.

A: It's not that it's a bad idea, it's just that there's no point in elevating this to the point of language feature, not even syntactic sugar, you can very easily implement this yourself in C#:
public static class ExtensionMethods
{
    public static void AsIf<T>(this object target, Action<T> todo)
    {
        if (target is T) todo((T)target);
    }
}

a.AsIf(aAsB => {your code});

A: This can be done with the new is-expressions coming in C# 7
class A     { public void f1() { ... } }
class B : A { public void f2() { ... } }

A a = foo(); // might return A or B

if ( a is B b ) {
    b.f2();
}

A: I like the idea. It's also not dangerous if you take into consideration some cases.
Consider
if (a is B) {
    a.BMethod(); // OK
    a = new B(); // OK
    a.BMethod(); // OK
    a = null;    // Disallow? (Probably OK)
    a.BMethod(); // Disallow? (Probably OK)
    a = new A(); // Disallow? (Probably bad)
    a.BMethod(); // Disallow?
}

It certainly is possible to write your extension to fail to compile in such a case, but one would want clean error messages, need to define more restrictions (such as you could only assign a B to a inside the if-block), throw a runtime exception, or something else.
Consider multi-threaded code using a, and a gets reassigned inside the as-if block. This would be very hard to do properly in a direct C# translation (it's possible, but not very nice *). This feature wants to be done at the byte code level, where it is trivial to implement.
(*): You would need to assign to a temporary, then assign to the original a, then assign to the a_as_b compiler generated variable. Even still, I may be missing some important edge cases.

A: tl;dr: Concurrency Issues
When you write A a; you are effectively making the statement "a is a variable that can contain objects representable by the type A". By changing the variable's type to something lower in the food chain, you would potentially introduce concurrency issues.
For example
namespace AsIf
{
class A { public void FA() {} }
class B : A { public void FB() {} }
class C : A { public void FC() {} }

class Program
{
delegate void ActionOnA(ref A a);
static void AToC(ref A a) { Thread.Sleep(5000); a = new C(); }

void main()
{
A a = new B();

// Wait 5 seconds, change a to new C()
ActionOnA action = AToC;
action.BeginInvoke(ref a, (ar) => { action.EndInvoke(ref a, ar); }, null);

if(a is B)
{
// a is implicitly retyped as B for the rest of this block

// B.FB get called on a (an instance of B)
a.FB();
// Sleep 6 seconds
Thread.Sleep(6000);
// B.FB gets called on a (an instance of C)
a.FB();
// 'Undefined behaviour' most likely causing all kinds of crazy
}
}
}
}

This is slightly less likely to happen when you introduce b
// assume everything else is as before

void main()
{
A a = new B();

// Wait 5 seconds, change a to new C()
ActionOnA action = AToC;
action.BeginInvoke(ref a, (ar) => { action.EndInvoke(ref a, ar); }, null);

if(a is B)
{
// introduce b
B b = (B)a;

// B.FB get called on b (an instance of B)
b.FB();
// Sleep 6 seconds
Thread.Sleep(6000);
// B.FB gets called on b (an instance of B)
b.FB();
// Safe! (for now)
}
}

This is because B is an entirely different variable being used to hold the same object.
What the concurrent function is actually doing is assigning to the variable a which is not directly affecting the object a was holding. Because b now holds a reference to the object that was in a, a can get reassigned and nobody would care.
Of course this is an implementation detail. If the compiler were to secretly create a second variable for the asif block rather than just reinterpreting a as being of the type B, the result would be effectively the same as my second example. Whether such behaviour is expected, obvious or desired is a different matter entirely.
It's not an impossible feature, it's just one that's more work than it's worth really.

A: In Swift you write:
if let b = a as? B {
    ....
}

a as B would try to convert a to type B - which for object types would succeed if a actually belongs to class B which would need to be a subclass or superclass of A to ever succeed. Of course this would only change the type of the reference, not the type of the object behind it. And it would crash on purpose if the conversion fails.
a as? B is similar except it returns an "optional B"; the result is nil if the conversion fails.
if let b = a as? B evaluates a as? B. If the result is nil then the if is not executed. If the result is not nil then it assigns the reference to a non-optional b of type B and executes the if's body.

A: I've seen an AsIf extension method implemented as such:
private static void AsIf<TBase, TChild>(this TBase source, Action<TChild> action) where TChild : TBase
{
    if ((source is TChild) && (action != null))
    {
        action((TChild)source);
    }
}

The generic constraints make sure you're attempting to "as-if" something hierarchically allowable.

A: This is already a common feature in many programming languages. They are called sum types. Classes are an awkward way to simulate sum types in languages that lack them.
Sum types (also called variants and unions)  are the dual to product types (commonly called tuples).  Just as product types allow you to stick to types together to create a compound type that is composed of type 1 and type 2, sum types allow you to create a compound type that is either type 1 or type 2.
Here's how it works. Let's say we want to represent internet addresses. There are two ways to address a computer on the internet: using its IP address or its fully-qualified domain name (FQDN). The FQDN is a human-readable string, while the IP address is an integer between 0 and 2^32.
Since we want functions that can operate on either of these schemes, we create a sum type
type InternetAddress = IP of int | FQDN of string

Note that InternetAddress is really just a type alias for int + string. The identifiers IP and FQDN serve as labels (also called constructors or injections) for each "branch".
To create a value of type InternetAddress, we inject a value into the sum type
val my_address: InternetAddress = FQDN "mydomain.com"

To use a value of a sum type, we perform case analysis. The instance type of the value determines which "branch" of the expression we take:
case my_address of
     IP ip_address -> *branch 1*
     | FQDN host_name -> *branch 2*

In either branch, the underlying value of my_address binds to the declared variable. So in branch 1, we can use ip_address which has type int, and in branch 2 we can use host_name which has type string.
In my opinion, sum types are an indispensable feature of programming languages, and the fact that they are so scarce in today's mainstream languages has caused considerable confusion and errors over the years.


text:
Q: A rational function f(x) has the following power series representation for the interval $-3A rational function f(x) has the following power series representation for the interval $-3<x<3$. $f(x) = x - \frac{x^2}{3} + \frac{x^3}{3^2} +...$. Find a closed-form expression for f(x).
Now, I found that $f(x)=\sum_{n=1}^\infty (\frac{-1}{3})^{n-1}(x)^n$, but how do I continue from here.

A: If you need the terms
to have the same exponent
for everything,
just make it happen:
$\begin{array}\\
f(x)
&=\sum_{n=1}^\infty (\frac{-1}{3})^{n-1}(x)^n\\
&=x\sum_{n=1}^\infty (\frac{-1}{3})^{n-1}(x)^{n-1}
\qquad\text{(pull x out so exponents the same)}\\
&=x\sum_{n=0}^\infty (\frac{-1}{3})^{n}(x)^{n}
\qquad\text{(shift exponents)}\\
&=x\frac1{1-\frac{-x}{3}}\\
&=\frac{x}{1+\frac{x}{3}}\\
&=\frac{3x}{3+x}
\qquad\text{(this is optional)}\\
\end{array}
$


text:
Q: Rebooting a Remote Computer in C# I'm trying to reboot a remote computer by button click.
I have been checking multiple posts and i've tried numerous different Process.Start methods but none seem to work.
Most posts just say use this:
Process.Start("shutdown", "-r -f -m" + BxSD.Text + "-t 00");

But i've tried this and variations of it, but all that happens is the cmd window opens for a second then closes and nothing happens.
Any help is appreciated.
UPDATE: I found out that it could not reboot the device based on the hostname and can only reboot by IP address only.
The final iteration of my command is as follows:
Process.Start("cmd.exe", "/k SHUTDOWN /r /f /m \\" + BxSD.Text);
But now however, the cmd prompt window doesn't exit after sending the command.
Any thoughts?

A: This works for me:
Process process = new();
            ProcessStartInfo startInfo = new()
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                FileName = "cmd.exe",
                Arguments = $" ___your command here___ ",
                UseShellExecute = true,
                Verb = "runas"
            };
            process.StartInfo = startInfo;
            process.Start();


text:
Q: Is there any way to include Google Earth imagery within an OpenGL program? I'm building a program that uses weather simulation using OpenGL. I want to include Google Earth imagery  with zoom and pan. Is this possible? Or can it be done the other way round, including OpenGL graphics inside Google Earth? Thanks!

A: It's not possible with Google Earth, and even if you find a way to download the data from their servers, you probably violate the usage agreements. However, you can use the Nasa World Wind SDK to embed a similar technology in your simulation. It's open source, so even if your OpenGL code is not compatible, you can always use their streaming and preprocessing methods.

A: If you can tolerate lower resolution imagery of Earth, there's NASA's Blue Marble (free). It's airbrushed, pristine land imagery (no clouds). Google's Earth imagery has all kinds of blemishes, but lets you zoom in much farther. NASA's imagery, you find in long-shots of Earth in sci-fi movies.


text:
Q: How to go about a very basic computer vision algorithm I tried to utilize Open CV and another CCV libraries, both are open source material, but have huge source sizes, whereas my requirement is only to detect rectangular shapes in a larger image and extract them. I am forced to have a very small footprint of my app.
Lets say after loading images of any format (JPEG, PNG etc) in a bitmap array what should be the next move, assuming that rectangles allow little fault tolerance,angle correction, clear boundary line (but not monolithic in its body color) and can be any width/height.

A: If you really don't want to use OpenCV or another Computer Vision Library you can implement the algorithms necessary.
I'm not sure why your binary file would be super large. You'd only need to include the code for imgproc and core (I think, it's been a little while since I've used it).
You'll need to segment your image. Your foreground being the shapes you want to test and the background everything else. This isn't too bad if you know what color they are or what color the background is).
Compute the connected components in your foreground. This will extract pixels forming a blob. (a simple linear pass going from top left to bottom right and bottom right to top left will do this in 2N time).
Once you have the connected components you can compute the 0th 1st and 2nd central image moments for each. https://en.wikipedia.org/wiki/Image_moment is pretty good.
The 0th moment is the area of connected component. First moments are the centroid of the blob. The second moments can tell you the rotation of the object.  The Eigen values of the 2nd central moments covariance matrix will be proportional to the major and minor axis of your rectangle.
This will give you the information about your blob. I.E. its location the image and it's rotation.
To determine if that blob is a rectangle there are several methods.
You can use a Hough Transform see Rectangle detection with Hough transform
Or you can try to compute the expected compactness (Perimeter / area) of a rectangle with the Given Area and major (length) and minor (width) axis proportionality to the actual compactness of the blob.   If it's close enough then you have a rectangle like object. (depending on how close is close enough you may get things that are more oval than rectangular).
While these algorithms aren't particularly hard to implement it may be difficult to get all of them working perfectly together. It may be easier for you to find what parts of OpenCV you need to include in your binary and only include those portions.


text:
Q: FILTER_SANITIZE_NUMBER_INT does not convert string to int I thought that the filter_input(type, name, FILTER_SANITIZE_NUMBER_INT) will convert the string to int but it seems it does not.
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);

if (isset($id) && is_int($id))

Is there another clean but working way to do this?

A: You can always just cast it:
$id = (int) $_GET['id'];

A: You can convert a string to an integer in various ways:
$id = (int)$_GET['id']; // Like wogsland showed.
$id = intval($_GET['id']); // This works but is around twice as slow as (int).

Here are some tests that I found, comparing the two: Fastest way to convert string to integer in PHP

A: Casting to int via (int)$_GET['id'] seems to be the fastest option. You can also use is_numeric() to check if the string is numeric.
Beware that filter_var can return the boolean value false on failure, which will be evaluated as the integer 0.
You can read more about string conversion in the manual.
A warning from the manual:
Booleans, floating point numbers and strings can be converted but the behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice!


text:
Q: angularjs datepicker to set max date and min date dynamically I am using below date-picker plugin for angularjs which is made from pickadate.js
https://github.com/alongubkin/angular-datepicker
I am using this plugin twice on the page. Plugin have very good option max date and min date which will help us select between those date.
Example options
$scope.depOptions = {
    format: 'dd/mm/yyyy',
    min: minDate,
    max: maxDate,
    onClose: function(){
      $scope.arrOptions.min = $scope.depDate;
    }
  }

Now I want to make min date starting from selected. I tried $watch and also tried to onClose method provided by plugin but I could not do it. Kindly somebody help me.
http://plnkr.co/edit/QBFwqyUIJxtw1dltMDky?p=preview

A: It seems that the element's configuration once initialized cannot be changed. Try putting the arrival input in ngIf, so that it is always rendered anew when departure changes.


text:
Q: The range of the function $f : \mathbb R \to \mathbb R$, defined by $ f(x)=\frac{\sin\pi [x]}{s^{2}+5}$ is?
Let $[x]$ denote the greatest integer less than or equal to $x$ for
  any real number $x$. The range of the function $f : R → R$, defined by
  $ f(x)=\frac{\sin\pi [x]}{s^{2}+5}$:
A.$ (−1, 1)$
B. $[−1, 1]$
C. $\{−1, 1\} $
D. $\{0\}$

The numerator oscillates between $-1$ and $1$, and the denominator can take any positive value. So the range is within $(-1,1)$ ??
I don't know how to find out if the function touches $-1$ and $1$?
Is the answer (A)$(-1,1)$ ??
Any help will be appreciated!

A: The answer is found by the questioner already: Since $[x]$ is always an integer,
$$\sin \pi [x] = 0$$
for all $x\in \mathbb R$. Thus the range is $\{0\}$.


text:
Q: Why does BalloonTipTitle appear twice in toast notification on Windows 10 Anniversary (1607) Just noticed the title gets shown top and bottom of the toast now in a C# application I'm building. Anyone else see the same thing? In pre-anniversary Windows 10, the BalloonTipTitle only appeared in the top portion of the toast.
Not a big deal, but it looks silly.
I can't post pictures yet, but if I get any responses I'll upload pre and post-anniversary pictures of the toast behavior.
I think I'm getting downvoted because it wasn't really a question. So I'll rephrase:
Windows 10 Anniversary is putting the BalloonTipTitle at the top, and assembly: AssemblyTitle from AssemblyInfo.cs at the bottom of the toast.
What's the best way to manage this across different versions of Windows 10 and 7? I want my user to know my app caused the toast, but I don't want to duplicate information.
Here's some quick code in a Windows Forms Application that shows what I mean. If you change the BalloonTipTitle to match your solution name, you'll see the redundant title:
    static void Main()
    {
        NotifyIcon myNotifyIcon = new NotifyIcon();
        myNotifyIcon.BalloonTipIcon = ToolTipIcon.Warning;
        myNotifyIcon.BalloonTipText = "This is a test toast";
        myNotifyIcon.BalloonTipTitle = "Toast Title";
        myNotifyIcon.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
        myNotifyIcon.Visible = true;
        myNotifyIcon.ShowBalloonTip(10000);

        ContextMenuStrip contextMenu = new ContextMenuStrip();
        ToolStripMenuItem menuItemExit = new ToolStripMenuItem();
        menuItemExit.Text = "Exit";
        contextMenu.Items.Add(menuItemExit);
        menuItemExit.Click += delegate { myNotifyIcon.Visible = false; Application.Exit(); };

        myNotifyIcon.ContextMenuStrip = contextMenu;

        System.Timers.Timer myTimer = new System.Timers.Timer();
        myTimer.Interval = 20000;
        myTimer.Enabled = true;
        myTimer.Elapsed += delegate { myNotifyIcon.ShowBalloonTip(10000); };

        Application.Run();
    }

A: Decided to check the CurrentBuild registry key after checking for Windows 10. Anything greater than or equal to build 14393 (Anniversary), and I'll leave out the BalloonTipTitle
    bool AppNameInBaloon = false;

    string BuildString = ReadHKLMValue(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuild");

    int CurrentBuild;

    bool WasParsed = Int32.TryParse(BuildString, out CurrentBuild);

    if (WasParsed)
    {
        if (CurrentBuild >= 14393)
        {
            AppNameInBaloon = true;
        }
    }

private static string ReadHKLMValue(string regPath, string value)
    {
        RegistryKey localKey;

        if (Environment.Is64BitOperatingSystem)
        {
            localKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
        }
        else
        {
            localKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
        }

        string keyValue;

        try
        {
            keyValue = localKey.OpenSubKey(regPath).GetValue(value).ToString();
            return keyValue;
        }
        catch
        {
            keyValue = "";
        }

        return keyValue;
    }


text:
Q: Unable to download application,  could not be installed at this time I am getting this error when trying to install an app to a device. I've been dealing with code signing errors for the last 3 days, and now this.
My app is using a distribution certificate and mobile provisioning profile. It is uploaded to a build server where it is passed as a successful build with no code signing errors. The server generates an application download link which I am using on my device to download the app, where I am getting the error:
Unable to download application, <app-name> could not be installed at this time

*

*My app is using a valid distribution certificate

*My app is using a valid distribution provisioning profile

*The build server passed the app with no code signing errors

From what I understand, the app should be able to run on any device as it is using the distribution certificate and profile. Other apps that I've worked on work fine with this method. Does anyone have a clue why my app can't be installed?

A: Is your app build with a valid enterprise/in-house distribution profile/certificate?
If so: Attach the device to your mac and start xcode.
Then open the organizer (CMD + SHIFT + 2) and read the device's console while installing the app. Maybe that clears things out

A: Make sure your iOS version is compatible with the app you are installing.
I saw this issue happen when a user was installing an iOS 8 only app on an iOS 7 device.
Also, if you tried to install the application on iOS 7 and it failed due to being an incompatible version and then you upgraded to iOS 8, you will need to do the following:

*

*Download iExplorer (http://www.macroplant.com/iexplorer/)

*Plug your device

*Delete all the files in "Media > Downloads"

*Restart device

There's an iOS bug where it leaves behind the bundle ID and it will fail silently not allowing you to install the app after you upgrade.

A:
Most common causes of this issue:

*

*Device storage is full

*The provisioning profile is a developer provisioning profile

*The ad hoc distribution provisioning profile is corrupted and the device is having an issue with it.

*The device was restored from a backup and is causing a conflict for over-the-air
   distribution

*There was a network timeout

*Architecture settings of the build and the device are incompatible ( can sometimes happen when   "Build Active  Architecture Only" is on when building).

*Not Using Mobile Safari.

  To find out the exact cause of this issue:

*

*Connect the device with iMac.

*Open Organizer then choose devices.

*Choose your Connected device from sidebar.

*Choose Console inside the chosen device.

*Now install the app it will show the exact cause of problem

Reference

A: Had this problem lately and went nuts. Settings for iOS version, device type (iPhone, iPad) were correct... still the app wouldn't download/install.
A simple reboot fixed it!

A: Apple really needs to work on provisioning files.
In the docs, it says that the app must firstly be signed with the development provisioning profile and then the distribution provisioning profile upon archival of the file for distribution. However, I found it to work by using the development provisioning file for both the code signing and archival signing instead.
You really need to play around with the provisioning files and see which works for you.

A: For me this error occurred when i distributed my app as inHouse App,
The reason for the error was while exporting ipa file i used the option
save for Ad Hoc Deployment but it actually should be save for Enterprise Deployment
And also from iOS 10 you need to give some string for permission eg, For "Privacy - Camera Usage Description" add string as "This app requires access to the Camera."

A: Finally and after a lot of trouble I was able to fix this issue.
I'm working with Xamarin. The issue appeared after enabling push notifications for my app causing the provisioning profiles to become damaged.
I unchecked push notifications from entitlements.plist (doesn't disable push notifications)
I was cleaning the project and removing profiles all the way

A: You may be able to determine a problem with the .IPA by attempting to upload it to iTunes Connect and observing if it disallows the upload during validation (ignoring any errors regarding missing images/assets required for the store).
In my case, a Xamarin app that was deployed via HockeyApp was getting the error.  Since I wasn't developing the project in Xcode, I used the Application Loader to attempt to upload the IPA to iTunes Connect.  The validation failed, with an error regarding a missing required setting in the info.plist.  Once I addressed this, I re-deployed via HockeyApp and the app was able to run.
Instructions for Application Loader can be found here:  https://help.swiftic.com/hc/en-us/articles/201574452-Upload-Your-App-to-iTunes-Connect-using-the-Application-Loader

A: Well, I had this issue previously. I would follow the suggestions by @max_ first. But, as trivial as this might sound, make sure that the plist file associated with your .ipa has a proper case in its hyperlink for the ipa. It is case-sensitive.

A: In .plist file
do your URL tag include http://
If you fill in URL tag with "www.somelink.com/....." it will download but get message "Unable to download at this time"
You Should fill in "http://www.somelink.com/...."
also in Display-image & Full-Size Image

A: I think I've had a case just like yours with xcodebuild. You might want to check that the bundle identifiers are exactly the same (case-sensitive!) in you build settings and on Apple developer portal (and thus in the provisioning profile)
You will find a more detailed write up and more fix options here.

A: Sometimes you just need to delete all apps with has the same bundleId. In my case, I had an app which was installed from the code and after configuring CI I was not able to install builds from CI. The fix was just to delete an app which was installed from Xcode.

A: For those ones using dropbox for https download jus check that the link is the right one... I forgot to use the right format like this one https://dl.dropboxusercontent.com/s/xxxxxxxxxxxxx/appname.ipa
you should not use www.dropbox.com.......
I just changed this and it was working great

A: In our case, our distribution profile had expired. Check it in your Apple Developer/Member Center.

A: My app's code signing and provisioning profile was fine too. However I fixed the problem from occurring on iOS10 devices by removing it's embedded app extensions. They did not have valid certificates but were not detected as invalid until I disabled the auto-xcode management for their targets.

A: Just fix it by connect the phone with mac, and In xcode run the app
Guessing maybe there some bugs with the apple provisioning systems


text:
Q: Why can't Preview export some TIFFs to PNG? Some TIFFs can't be exported to PNG in Preview. What is preventing this and how do I correct it?

A: This happens when the image is in CMYK.
PNG does not support the CMYK color mode therefore Preview won't suggest it for the export.


text:
Q: Убрать атрибут обязательное заполнение поля при выполнении условия Как сделать так, чтобы в коде JS ниже сделать поля input необязательными к заполнению внутри if ? Я понимаю, что required - boolean, но запихнуть required = false внутри if не выходит.
document.querySelector("[name=prevdocid]")
    .addEventListener("change", function (e) {
        const input  = document.querySelector('[name="doc_series"]');
        const input2 = document.querySelector('[name="doc_number"]');
        const input3 = document.querySelector('[name="doc_date"]');

        input.disabled = !["1","2", "3", "4","5","6","7","8"].includes(this.value);

        if (input.disabled) {
            input.value = "";
        }
        input2.disabled = !["1","2", "3", "4","5","6","7","8"].includes(this.value);
        if (input2.disabled) {
            input2.value = "";
        }
        input3.disabled = !["1","2", "3", "4","5","6","7","8"].includes(this.value);
        if (input3.disabled) {
            input3.value = "";
        }
});

A: <!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title>HTML5</title>
 </head>
 <body>
<input class="input" required disabled type="text">
<button class="enableBtn">enable</button>
<script>
    const btn=document.querySelector('.enableBtn');
    btn.addEventListener('click',()=>{
        input=document.querySelector('.input');
        if (input.disabled) {
            input.removeAttribute('required');
            input.removeAttribute('disabled');
        }
    });
</script>
 </body>
</html>


text:
Q: Change name of zip when creating archive with distribution plugin in gradle Is there any way to configure distribution file name when creating archive using distribution plugin in gradle?
Here is my build.gradle (I'm using gradle 2.10) file:
apply plugin: 'distribution'
version '1.2'

distributions {
  custom {
    baseName = 'someName'
    contents {...}
  }
}

And calling the task customDistZip creates file: $buildDir/distributions/someName-1.2.zip I would like to have a file name configurd to: someName.zip (without version number).
My workaround for this is to create new task to rename the zip file after creation and use gradle finalizedBy feature:
task renameDist {
  doLast {
    new File("$buildDir/distributions/someName-${project.version}.zip")
            .renameTo("$buildDir/distributions/someName.zip")
  }
}
customDistZip.finalizedBy renameDist

But this don't look like elegant and nice solution.

A: You can either do:
customDistZip.setVersion('')

to set the version string used with baseName to empty or
customDistZip.setArchiveName('someName.zip')

to set the full archive filename, which skips basename alltogether.

A: Kotlin/Groovy:
distributions {
    ->distribution<- {
        distributionBaseName.set(->name<-)
    }
}


text:
Q: Navigate to root from child outlet angular? The issue is that I want navigate to app root from within a child route.
This is my structure:
export const rootRouterConfig: Routes = [
   { path: '', redirectTo: 'login', pathMatch: 'full' },
   { path: 'login', component: LoginComponent, canActivate: [AuthGuard] },
   { path: 'dashboard', component: DashboardComponent, resolve: { data: UserResolver},
     children: [
        { path: '', redirectTo: 'projects', pathMatch: 'full' },
        { path: 'projects', component: ProjectsComponent, resolve: { data: UserResolver}},
        { path: 'addproject', component: AddprojectComponent, resolve: { data: UserResolver}},
        { path: 'updateproject/:key', component: AddprojectComponent, resolve: { data: UserResolver}},
        { path: 'network', component: NetworkComponent, resolve: { data: UserResolver}},
        { path: 'figures', component: FiguresComponent, resolve: { data: UserResolver}},
        { path: 'user', component: UserComponent,  resolve: { data: UserResolver}}
     ]
   },
   { path: 'forgot', component: ForgotComponent },
];

This is the app.compenent.html:
<main>
    <router-outlet></router-outlet>
</main>

And this is the dashboard.component.ts:
<div class="dashboard-content-wrapper">
   <router-outlet></router-outlet>
</div>

I have a button in the UserComponent that I expect to navigate to the login page since it is root, but I can't get passed the dashboard component??
deleteProfile() {
    this.route.navigate(['/'])
}

A: RE:

Because it is not possible as I am inside the UserComponent that is a
  child of the DashboardComenent, so the click is happening inside a
  child outlet.

It should be possible. I do this all of the time.
Just be sure to specify the slash in the path so it is not relative to its current location.
So something like this:
this.router.navigate(['/login']);

A: you need to route relative to existing route.
this.route.navigate([ '../../' ], { relativeTo: this.route })


text:
Q: How to create an array of pointers with lock and check the pointer free or not? I have an array pointers.
Can I use mutex for lock and unlock? At the same time, Another thread run with the same and check matrix[h].
int **matrix;
matrix =new int[20];
for(int i=0; i<20; i++)
{
  matrix[i]= new int[20];
}

#pragma omp parallel for nowait
for(int h=0; h< 20; ++h)
{
   if(matrix[h].isfree()==true)
   {
     lock(matrix[h]);
     //do something...
     unlock(matrix[h]);
   }
   else
   {
     //that array matrix[h] is not free.
     skip++;
   }
}

A: You can use omp_lock_t mylock; for declaring the lock instead of pthread_mutex_t mylock; as you are using openmp. Then you can initialize the lock and use omp_set_lock(&mylock); to put a lock and omp_unset_lock(&mylock); to remove the lock. Have a look at this ->
stackoverflow.com/questions/2396430/how-to-use-lock-in-openmp

A: If your intention is never to block the thread it suffices to use std::atomic_bool .
Otherwise you should use std::lock_guard in combination with std::mutex .


text:
Q: ActiveX Control Dispose(true) is not called My C# ActiveX Control is hostet in IE 8. I want to execute code when the control is unloaded.
I tried the following:
...
public class ActiveXControl : Control
{
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            // Cleanup
        }
    }
}
...

But disposing is allways false (Called from finalizer). As I need to access managed objects I cannot use that one.
How can I get the cleanup code to be called when the Browser "unloads" the control?
I found the IOleObject::Close method, which is implemented by the Control class but AFAIK ther's no way of overriding its behavior.

A: I haven't done this, but as a suggestion to try: It might be possible to write a bit of javascript embedded in the html of on the web page that will call a method on your activeX control when the page is navigated away from. You could call your cleanup code from this method.

A: You could override OnHandleDestroyed(), called when IE destroys the control window.


text:
Q: Make a c# function non-private, mark it as final, or seal its declaring type I am maintaining some old C# code and cannot change its structure too much. I tried to reduce some existing compiler warnings in a safe manner. Certain functions gave me the following warning:

Warning   CS0108 'Function(string, string)' hides inherited member 'xyz.Function(string, string)'. Use the new keyword if hiding was intended.

I assume that hiding that inherited function was intentional as the software has been used successfully for a number of years now. I saw no harm in adding the "new" keyword to make this function declaration as
private new void Function(string parm1, string parm2)

The warning disappeared as expected, but this one appeared instead:

Warning   CA2222 Make 'Function(string, string)' non-private, mark it as final, or seal its declaring type. This method was originally defined in base class 'BaseClassName'.

Apart from suppressing this warning I am not sure what is the safest (i.e. non-behaviour changing) option available to me? I don't think that I should make this method non-private (which I assume means "public"). I am not sure how to make it final or sealed and whether or not doing so would be the right solution.

A: Unless there is access to this method via reflection, remove the "new" keyword and then rename it (changing any calling site too). The method is private anyway, so it should only be in use from the same class unless it is being passed by delegate (then the name doesn't matter) or if reflection is used to access it.
Under the assumption that the code is correct, any calling of this method is intentional. Although I would review them and check if there could be any mistake by which the calling sites were calling the wrong method.

Any change to the visibility of the method is problematic, so avoid doing that※. About making the class sealed, it is also a breaking change because there may exist third party code that inherits form the class, so avoid that too.
※: Reductions of visibility are worst because there may exist third party code that uses the member, so that's a breaking change. Increasing visibility (for example making a private method protected or public) may break the encapsulation of the type, exposing a member may allow third party code to mess with the state of the objects of that type, so be cautious.

A: You can ignore the warning - It's incorrectly being triggered. That said, private new is somewhat of a code smell, and may indicate a deeper problem.
See here for an explanation as to why it occurs. It's worried that someone will come along and override your new method.

If you must change the access modifier, either the method should be marked final or its type should be sealed to prevent the method from being overridden.

However, methods in C# are final by default. Marking a method as sealed (aka final in other languages) C# only prevents further overrides.
The warning would only be applicable if your new method were:
public/protected/internal virtual new void Function(string parm1, string parm2)

In which case the solution is to remove the virtual keyword


text:
Q: Get Lua string from C I'm trying to learn Lua and how to interface to and from C with it. My first attempt follows but has been simplified to include only the issue I'm seeing.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <linux/limits.h> /* For PATH_MAX */
#include <unistd.h>
#include <getopt.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

#define EXITF exit(EXIT_FAILURE)

lua_State* lua;

void stackDump(lua_State* lua)
{
    int i, t;
    int top = lua_gettop(lua);

    for (i = 1; i <= top; i++)
    {
        t = lua_type(lua, i);

        switch (t)
        {
            case LUA_TSTRING:
                printf("\"%s\"", lua_tostring(lua, i));
                break;

            case LUA_TBOOLEAN:
                printf(lua_toboolean(lua, i) ? "true" : "false");

            case LUA_TNUMBER:
                printf("%g", lua_tonumber(lua, i));
                break;

            default:
                printf("%s", lua_typename(lua, t));
                break;
        }

        if (i < top)
           printf(", ");
    }

    printf("\n");
}

int main(int argc, char** argv)
{
    int opt;
    char cfgFile[PATH_MAX];
    cfgFile[0] = 0;

    lua = luaL_newstate();
    luaL_openlibs(lua);

    stackDump(lua);

    while ((opt = getopt(argc, argv, "c:")) != -1)
    {
        switch (opt)
        {
            case 'c':
                strncpy(cfgFile, optarg, PATH_MAX);
                cfgFile[PATH_MAX - 1] = 0;
                break;
        }
    }

    if (cfgFile[0] == 0)
    {
        fprintf(stderr, "No cfg file specified\n");
        return EXIT_FAILURE;
    }

    printf("cfgFile = \"%s\"\n", cfgFile);

    if (luaL_loadfile(lua, cfgFile) != LUA_OK)
    {
        fprintf(stderr, "%s\n", lua_tostring(lua, -1));
        lua_pop(lua, 1);
        lua_close(lua);
        return EXIT_FAILURE;
    }

    stackDump(lua);

    lua_getglobal(lua, "program");

    stackDump(lua);

    if (lua_isstring(lua, -1) == 0)
    {
        fprintf(stderr, "`program` should be a string\n");
        lua_close(lua);
        return EXIT_FAILURE;
    }

    char execArg0[256];

    strncpy(execArg0, lua_tostring(lua, -1), 256);
    lua_pop(lua, 1);

    lua_close(lua);

    return EXIT_SUCCESS;
}

Lua script:
#!/usr/bin/env lua

program = "echo"

What I'm seeing when running this is:
$ ./wrapper2 -c wrapper2.lua

cfgFile = "wrapper2.lua"
function
function, nil
`program` should be a string

Note that the empty line is intentional; stackDump() tells us that the stack is empty at that point. It seems that the call to lua_getglobal(lua, "program") is pushing nil on the stack instead of the string "echo". Please could you help me work out why I'm seeing this?
As a side question: why is there a function pushed on the stack (presumably by luaL_loadfile())? I don't remember reading that functions are pushed on the stack automatically.

A: luaL_loadfile loads a Lua script but does not execute it and so does not define the global program. Use luaL_dofile instead.
luaL_loadfile compiles a Lua script and leaves the code as a Lua function on the stack.
luaL_dofile calls luaL_loadfile and then calls that function.
See the manual entries for luaL_loadfile and luaL_dofile.


text:
Q: jersey post 400: Bad Request simple register
i have passed a lot of time to solve a simple problem using rest, but i don't way i can't post data when i test in postman or advanced rest, this is my rest resource
@Path("/auth")
@Stateless
public class RestWs {

    @EJB
    private UserService userService;

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public void registerRest(Users u){
        Users users = new Users();
        users.setUsername(u.getUsername());
        users.setEmail(u.getEmail());
        users.setPassword(u.getUsername());
        userService.registerService(u);
    }

}

and this is my jpa
@Override
    public Users register(Users users) {
        em.persist(users);
        return users;
    }

and this is my entity
@Entity
public class Users implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)

    private Long id;
    private String username;
    private String email;
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "Users{" + "id=" + id + ", username=" + username + ", email=" + email + ", password=" + password + '}';
    }

}

i don't why i can't post data for register user , i need something else like parsing or ...., please help me, and thanks

A: just i need to add cross filter  and all work great
@Provider
public class CORSFilter implements ContainerResponseFilter{

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) throws IOException {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers",
                      "origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods",
                      "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }

}

and in web.xml
<init-param>
          <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
          <param-value>com.ress.CORSFilter</param-value>
        </init-param>

that's all


text:
Q: OSUmicro benchmarks and segmentation fault I have a three-node cluster, based on rhel 6.1
on every node i have two CPU and 4 GPU  Tesla M2090/
I use Openmpi 1.6.1, which works fine( system tested on GPU Linpak ver.).
And i install mvapich2 1.9 and i have the same problem.
I think that the trouble maybe in this test?!
Cuda ver 5.0
Infiniband - MEllanox.
Compiling of this bechmark was succesfull, and when i start point to point using only CPU (H to H) (both localhost and two nodes):

mpirun -np 2 ./osu_latency H H

it's work fine. But when i use the GPU(copy from CPU to GPU mem):

mpirun -np 2 ./osu_latency H D

the program crashes with segmentation fault(11).
I compile this benchmark, ver 3.7 from http://www.nersc.gov/assets/Trinity--NERSC-8-RFP/Benchmarks/Dec17/OMB-NERSC8.tar, using these parameters:

--prefix=/usr/local/bench/osu
  --enable-cuda --with-cuda=/usr/local/cuda-5.0 --with-cuda-include=/usr/local/cuda-5.0/include --with-cuda-libpath=/usr/local/cuda-5.0 CC=/usr/local/mpi/openmpi16/bin/mpicc

I try to run program with absolete path, but it has no effect.
Where is the problem?
Thank in Advance!


text:
Q: How to iterate over a map and match its key values with enum class members? I have a quick question.
Is there any trick to iterate through the keys of a map and use them to access an enumerate class items.
For example, lets say we have the Color class as defined below.
enum class Color {blue = 0, green = 1, yellow = 2};

unordered_map<string, string> mp {
  {"blue",""},
  {"green",""},
  {"yellow",""},
  {"red", ""}
 };

for (auto e: mp) {
   if(e.first.compare("blue") ==0) { // e.first == "blue"
       e.second = fGetVal(Color::blue);
    } else if (e.first.compare("green") ==0) {
       e.second = fGetVal(Color::green);
    } else if (e.first.compare("yellow") ==0) {
       e.second = fGetVal(Color::yellow);
    } else {
       cout<<"the requested color is not supported!"
    }
}

//  assume fGetVal() takes the enum class type as input and returns it value as a string

*

*Is there a better approach than using if/else-if to call method fGetVal?

*More specifically trying to use a variable name for accessing enum class elements something like Color::e.first

A: Are you trying to convert user input input a Color enum
enum class Color { blue = 0, green = 1, yellow = 2 };

unordered_map<string, Color> mp{
  {"blue",Color::blue},
  {"green",Color::green},
  {"yellow",Color::yellow},
};

string col = getUserInput();
auto find = mp.find(col);
if (find == mp.end()) {
    cout << "bad color";
}
else {
    auto encol = find->second;
}

A: A clean way to do is is to pre-cache the results of fGetVal() in a map and just do a simple lookup:
const unordered_map<string, string> colorStringsMap = {
 {"blue", fGetVal(Color::blue)},
 {"green", fGetVal(Color::green)},
 {"yellow", fGetVal(Color::yellow)},
};

int main() {
  unordered_map<string, string> mp {
    {"blue",""},
    {"green",""},
    {"yellow",""},
    {"red", ""}
   };

  for (auto& e: mp) {
    try {
      e.second = colorStringsMap.at(e.first);
    }
    catch(std::out_of_range) {
      cout <<"the requested color is not supported!";
    }
  }
}


text:
Q: Modal Pop-up not responding in Three.js I have been working with three.js to create visualization involving satellites revolving around Earth. Currently I have two satellites that have been included as sprites in a scene and I am using Raycaster to detect clicks on these sprites. As soon as one of the satellites is clicked, a modal pop up displaying satellite information comes up. So far so good!. Now this pop-up has a x button that should close the pop-up when clicked. However this seems to be not working. Even hover does not seem to respond. I was hoping if someone could throw a little bit of light on the matter. My initial guess is that the canvas of the three.js scene is acting as a hinder. I have the following code:
JAVASCRIPT
// Detecting clicks on Sprite
var modal = document.querySelector(".modal");
var closeButton = document.querySelector(".close-button");

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector3();

function toggleModal() {
    modal.classList.toggle("show-modal");
}

function clickOnSprite(event) {
    console.log("CLICK!" + event.clientX + "," + event.clientY);

    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(clickableObjects);

    if (intersects.length > 0) {
        intersects.forEach(function (element) {
        console.log("Intersection: " + element.object.id);
        element.object.material.color.set('#0bffff');
        clicked = !clicked; // This will temporarily stop the animation
        toggleModal();

    });
}

} // Function ending

closeButton.addEventListener("click", toggleModal);
window.addEventListener('click', clickOnSprite, false);

HTML

        ×

Satellite Information

CSS
.modal {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    visibility: hidden;
    transform: scale(1.1);
    transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}
.modal-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 1rem 1.5rem;
    width: 24rem;
    border-radius: 0.5rem;
}
.close-button {
    float: right;
    width: 1.5rem;
    line-height: 1.5rem;
    text-align: center;
    cursor: pointer;
    border-radius: 0.25rem;
    background-color: lightgray;
}
.close-button:hover {
    background-color: darkgray;
}
.show-modal {
    opacity: 1;
    visibility: visible;
    transform: scale(1.0);
    transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}

Thanks for the help:)


text:
Q: Tapping on the app icon does not display the notification in the app I am using the Event source-based notifications in hybrid applications sample from https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-0/notifications/push-notifications-hybrid-applications/event-source-based-notifications
When I receive a push notification and I tap on the app icon instead of tapping the notification in the notification bar, the notification isn't pushed and still appearing on the notification bar. Only if I tap on the notification bar, even if the app is open, the notification is pushed and is deleted from the notification bar.
There are no problems if the app is open when I receive the notification.
How I can force the notification to be pushed when I tap on the app icon rather than tapping the notification in the notification bar?
MobileFirst 7.0.0
Android Environment

A: I have indeed reproduced this. It appears to be a regression.
After a push is received and you then tap either the incoming notification in the notifications bar or the app icon

*

*the app is supposed to launch

*you are then prompted to login

*push support etc is checked for, and finally

*if there's a notification in the queue then it is supposed to be displayed (the pushNotificationReceived function is supposed to be called). This is not happening when tapping on the app icon

If you are an IBM customer or business partner I suggest for you to open a PMR (support ticket). This is going to be investigated by the development team...


text:
Q: CSS attribute selectors I study about css in w3school . The css selectors table has rows :

[attribute|=value]

*

*[lang|=en] Selects all elements with a lang attribute value starting with "en"

[attribute^=value]

*

*a[src^="https"] Selects every  element whose src attribute value begins with "https"

What differences between [attr |= value] and [attr ^= value] except double quotes ?

A: [attr|=value]
Represents an element with an attribute name of attr whose value is a hyphen-separated list of words, one of which is exactly "value". It can be used for language subcode matches.
[attr^=value]
Represents an element with an attribute name of attr and whose value is the prefixed by "value".
Have a look at w3fools
I recommend https://developer.mozilla.org/en-US/docs/CSS/Attribute_selectors and the whole MDN


text:
Q: Install php via yum including mysql support Is it enough to specify php module like this to have mysql support?
yum install php

or should I use
yum install php php-mysql

Is there a difference?
Thanx.

A: It is not enough. You will need to do:
yum install php php-mysql

To Install PHP and PHP-MySQL.


text:
Q: C# WP8 dynamically increase control size according to text I am trying to achieve below. I have created a control as you can see below where I am showing restricted test in textblock initially but as user click on readmore button I have to expand control size according to text inside the text block. Refer below image.

How to achieve this any help? This control will be added in another user control which is collection of this control.

A: If you are restricting the text by some means and then adding more text, you can accomplish this with really any panel control. Do not give the panel (or it's parent) a width or height property so that it can grow. Here is an example using a Grid
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBlock Text="Event"/>
    <TextBlock Text="{Binding EventSummary}" Grid.Row="1" Visibility="{Binding SummaryVis}"/>
    <TextBlock Text="{Binding EventDescription}" Grid.Row="1" Visibility="{Binding DescriptionVis}" />
    <HyperlinkButton HorizontalAlignment="Right" Content="read more" Command="{Binding ReadMoreCommand}" />
    <!-- Buttons -->
    <StackPanel Orientation="Horizontal" />
</Grid>

In the ReadMoreCommand you would change the visibility of the two textblocks
private void ReadMore(object val)
{
    DescriptionVis = Visibility.Visible;
    SummaryVis = Visibility.Collapsed;
}


text:
Q: ASP.NET with jQuery - POST vs GET Ok, I have a very silly question to ask (which Im rather embaressed about I must admit!). Im using the nyroModal plugin for jQuery within an ASP.NET 3.5 WebForms app.  Basically, let's say I have a hyperlink pointing to http://www.mysite.com/GetData.html?id=100
When the link is clicked, I want GetData.html to extract data from a database and populate some innerHTML elements with the return data.  the querystring value will be extrcated using jqURL plugin for jQuery, and I will use jQuery's built-in Ajax function to make a call to a webservice passing in the id as a parameter.
My question is this: How do I use jQuery.Ajax() if this is not a POST method, but rather a GET method, from how I understand it?  According to documentation, in order for $.ajax() to work, the type must be "POST".
Could someone please shed some light on this for me?
Thank you

A: You have many options:
1- use the load method:
$('#container').load(("/page");

2-use the get command:
$.get('/page')

3-use the ajax command:
$.ajax({
type:'GET',
url:'/page',
success:function() {
}
})

A: $.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});

... from the first example in the jQuery docs.

A: jQuery.get() ?


text:
Q: RayHandler doesn't goes with Box2D world I have a difficult situation.
I'm making a 2D game and I'm on the step
of integrating box2Dlights part.
But when i'm rendering my RayHandler, I have a black screen.

Here is another image, where I don't render my lights. There is no lights now.
I need to have collision of Box2D and Box2Dlights mixed together.
Please note:

*

*All my boxes are made in units, equal to 1, so that one room is 16 squares length.

*All entire world is zoomed by setToOrtho((16 - 1.875f) / Gdx.graphics.getHeight()), where 16 is tile size.

*If I scaled my tile size, I would like to have this stuff work.

All code is complicated so I send the only GameScreen and GameMap classes for now:
@Override
public void show() {
    InstanceVars inst = InstanceVars.getInstance();
    inst.world = new World(new Vector2(0, 0f), true);
    inst.engine = new Engine();
    inst.handler = new RayHandler(inst.world);

    LevelCreator creator = new LevelCreator("level_def.cfg");

    try {
        gameWorld = creator.createNewLevel();
        gameWorld.start();
    } catch (FileCorruptedException e) {
        e.printStackTrace();
    }
}

@Override
public void render(float delta) {

    gameWorld.render();
}

@Override
public void resize(int width, int height) {
    gameWorld.resize(width, height);
}

@Override
public void dispose() {
    gameWorld.dispose();
    InstanceVars.getInstance().dispose();
}

for the GameScreen.java
and
private World physWorld = InstanceVars.getInstance().world;
private Box2DDebugRenderer physRender = new Box2DDebugRenderer();
private OrthographicCamera cam = new OrthographicCamera();
private RayHandler lights = new RayHandler(physWorld);
private PlayerController controls;
private float STD_ZOOM = ((float) CELL_SIZE + 16) / Gdx.graphics.getHeight();
private Body playerBody;

public GameMap() {
    cam.zoom = STD_ZOOM;
}

public void start() {
    GameObject player = (GameObject) getProperties().get("ent_player");
    playerBody = player.getComponent(PhysicsComponent.class).getBody();

    controls = new PlayerController();
    Gdx.input.setInputProcessor(controls);
    physWorld.setContactListener(new CollisionInteractor(InstanceVars.getInstance().engine));

    PointLight light = new PointLight(lights, 1000, Color.GOLDENROD, 500, playerBody.getPosition().x, playerBody.getPosition().y);
}

public void render() {
    updatePlayer();
    physWorld.step(1/60f, 8, 2);
    updateCamera();

    physRender.render(physWorld, cam.combined);
//        lights.updateAndRender();
}

private void updatePlayer() {
    if (controls.up) playerBody.setLinearVelocity(playerBody.getLinearVelocity().x, -controls.speed);
    else playerBody.setLinearVelocity(playerBody.getLinearVelocity().x, controls.down ? controls.speed : 0);

    if (controls.down) playerBody.setLinearVelocity(playerBody.getLinearVelocity().x, controls.speed);
    else playerBody.setLinearVelocity(playerBody.getLinearVelocity().x, controls.up ? -controls.speed : 0);

    if (controls.left) playerBody.setLinearVelocity(-controls.speed, playerBody.getLinearVelocity().y);
    else playerBody.setLinearVelocity(controls.right ? controls.speed : 0, playerBody.getLinearVelocity().y);

    if (controls.right) playerBody.setLinearVelocity(controls.speed, playerBody.getLinearVelocity().y);
    else playerBody.setLinearVelocity(controls.left ? -controls.speed : 0, playerBody.getLinearVelocity().y);
}

public void resize(float width, float height) {
    STD_ZOOM = ((float) CELL_SIZE - 1.875f) / Gdx.graphics.getHeight();

    cam.setToOrtho(true, width, height);
}

private void updateCamera() {
    cam.position.set(playerBody.getPosition(), 0);
    cam.update();
}

public void dispose() {
    super.dispose();
    physWorld.dispose();
    physRender.dispose();
}

for GameMap.java.
If you need more details, don't be afraid to ask.
I cannot solve the problem on my own.


text:
Q: subrow issue in SKSTableView Is there anyone using SKSTableView and knows the subrow stuff ? I'm encountering the problem that in delegate method
func tableView(tableView: SKSTableView!, cellForSubRowAtIndexPath indexPath:
NSIndexPath!) -> UITableViewCell! {}

no matter how many number of subrows are returned, indexPath.subrow keeps giving me 0, which is the index of the first subrow. So the subrow cell can only fetch the first item of the given array.
Please help and thanks ahead.

A: you have to update NSIndexPath category
- (NSInteger)subRow
{

    id myclass = [SKSTableView class];
  //  id subRowObj = objc_getAssociatedObject(self, SubRowObjectKey);
    id subRowObj = objc_getAssociatedObject(myclass, SubRowObjectKey);
    return [subRowObj integerValue];
}

- (void)setSubRow:(NSInteger)subRow
{
    id subRowObj = [NSNumber numberWithInteger:subRow];

    id myclass = [SKSTableView class];
   // objc_setAssociatedObject(self, SubRowObjectKey, subRowObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(myclass, SubRowObjectKey, subRowObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


text:
Q: Loading XML node inside ListBox and PivotControl (c# & Windows Phone 7) I have the following XML
<?xml version="1.0" encoding="utf-8" ?>
    <root>
    <Sxoles>
        <sxoli>
            <onoma>name1</onoma>
            <sch>school1</sch>
            <sxoliId>100</sxoliId>
            <mathima>lesson1</mathima>
            <mathima>lesson2</mathima>

        </sxoli>
        <sxoli>
            <onoma>name2</onoma>
            <sch>school2</sch>
            <sxoliId>200</sxoliId>
            <mathima>lesson1</mathima>
            <mathima>lesson2</mathima>

        </sxoli>

    </Sxoles>
    </root>

I want to read mathima node and load inside a listbox (see bellow)
                           <Grid>
                                <ListBox x:Name="testList">
                                <ListBox.ItemTemplate>
                                    <DataTemplate>
                                            <TextBlock Grid.Column="1"
                                            x:Name="mathima"
                                            Style='{StaticResource                PhoneTextSubtleStyle}'
                                             />
                                      </DataTemplate>
                                    </ListBox.ItemTemplate>
                            </ListBox>
                            </Grid>

The list box is contained in a pivotitem of a pivotcontrol
As result i'd like to see lesson1, lesson2 etc... in the list (only the mathima node).
I created a class
 public class Sxoli
    {
        ...
        [XmlElement("mathima")]
        public string mathima { get; set; }

    }

In back code (.xaml.cs file) i have
mathima.Text = sxoli.mathima;

but i get the following error
"the name mathima does not exist in the current context"
What can i do?

A: You can get mathima values using LINQ 2 XML
XElement doc=XElement.Load("yourXML.xml");//loads your xml
var mathimaList=doc.Descendants("Sxoles").Descendants("sxoli").Elements("mathima").Select(x=>x.Value);//gets mathima values

mathimaList now contains all the values of mathima..


text:
Q: Ecto - how to get records by ids in exact order I have a list of record ids - [9, 1, 4, 3].
I want to retrieve records from postgresql and want them be ordered as in this ids list. But when I make a query, records are returned in arbitrary order:
Ecto.Query.from(r in Record, where: r.id in [9, 1, 4, 3])
  |> Repo.all()
  |> Enum.map(&Map.get(&1, :id)) # => [4, 9, 1, 3]

How could I retrieve records with the same order?

A: I don't think there's any easy way to do this in the database, but here's a way to do this in Elixir:
ids = [123, 4, 1, 3, 2, 456]
posts = from(p in Post, where: p.id in ^ids, select: {p.id, p}) |> Repo.all |> Map.new
posts = for id <- ids, posts[id], do: posts[id]
posts |> Enum.map(&(&1.id)) |> IO.inspect

Output:
[4, 1, 3, 2]

First, we build a map of id => post. Then, for each id in ids, we get the corresponding Post, if it was found. In my app, there was no Post with id 123 or 456, so they were ignored in for.

A: You can use the PostgreSQL's array_position function and Ecto's fragment function. In your case, it would look like:
Ecto.Query.from(r in Record, where: r.id in [9, 1, 4, 3])
|> Ecto.Query.order_by([r], fragment("array_position(?, ?)", [9, 1, 4, 3], r.id)
|> Repo.all()

I would avoid processing data outside of the database engine. It shouldn't matter in this simple example. However, it might impact performance for bigger data sets or more complex data structures because first, you have to load the results into the memory and then perform operations on them to change the order.


text:
Q: Margin of a TabPanel via TabControl.Resources How do we set the Margin of a TabPanel via TabControl.Resources, I tryed this code:
                    <TabControl.Resources>
                        <Style TargetType="TabPanel">
                            <Setter Property="Margin" Value="500,0,0,0" />
                        </Style>
                    </TabControl.Resources>
                </TabControl>

But this doesn't work for some reason while setting its width does work:
                <TabControl.Resources>
                        <Style TargetType="TabPanel">
                            <Setter Property="Width" Value="500" />
                        </Style>
                    </TabControl.Resources>
                </TabControl>

For the moment I have set margin with a Template but I would like to edit it for one separate TabControl.
Thanks Mikael Törnqvist

A: You will need to specify the margin for the TabPanel within the Template of the TabControl
like:

    <Style  TargetType="{x:Type TabControl}">
        <Setter Property="OverridesDefaultStyle" Value="True" />
        <Setter Property="SnapsToDevicePixels" Value="True" />
        <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type TabControl}">
            <Grid KeyboardNavigation.TabNavigation="Local">
              <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
              </Grid.RowDefinitions>
              <VisualStateManager.VisualStateGroups>
                <VisualStateGroup x:Name="CommonStates">
                  <VisualState x:Name="Disabled">
                    <Storyboard>
                      <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                                    Storyboard.TargetProperty="(Border.BorderBrush).
                        (SolidColorBrush.Color)">
                        <EasingColorKeyFrame KeyTime="0"
                                             Value="#FFAAAAAA" />
                      </ColorAnimationUsingKeyFrames>
                    </Storyboard>
                  </VisualState>
                </VisualStateGroup>
              </VisualStateManager.VisualStateGroups>
              <TabPanel x:Name="HeaderPanel"
                        Grid.Row="0"
                        Panel.ZIndex="1"
                        Margin="500,0,4,-1"
                        IsItemsHost="True"
                        KeyboardNavigation.TabIndex="1"
                        Background="Transparent" />
              <Border x:Name="Border"
                      Grid.Row="1"
                      BorderThickness="1"
                      CornerRadius="2"
                      KeyboardNavigation.TabNavigation="Local"
                      KeyboardNavigation.DirectionalNavigation="Contained"
                      KeyboardNavigation.TabIndex="2">
                <Border.Background>
                  <LinearGradientBrush EndPoint="0.5,1"
                                       StartPoint="0.5,0">
                    <GradientStop Color="{DynamicResource ContentAreaColorLight}"
                                  Offset="0" />
                    <GradientStop Color="{DynamicResource ContentAreaColorDark}"
                                  Offset="1" />
                  </LinearGradientBrush>
                </Border.Background>
                <Border.BorderBrush>
                  <SolidColorBrush Color="{DynamicResource BorderMediumColor}"/>
                </Border.BorderBrush>
                <ContentPresenter x:Name="PART_SelectedContentHost"
                                  Margin="4"
                                  ContentSource="SelectedContent" />
              </Border>
            </Grid>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
</TabControl.Resources>