Q: My script does not detect the redirection URL this is the case :
Needed a responsive html5 audio player and the best I found was one made by a person called Osvalds .
The first problem I found was that the " autoplay " attribute reproduced the same song twice in Firefox. I could fix this by adding a few lines of javascript (though the play button does not change the song to be played ) .
The second problem (and this is where I need help) is that the javascript does not detect or failure with URL redirect but it does work with the final URL.
I mean, my php variable to return a URL like:
" http://www.goear.com/action/sound/get/104fc33 "
But this in turn redirects me to a final URL:
"http://live1.goear.com/listen/d6a9757a390b5d49b8584288d5589318/52eac3f1/sst2/mp3files/10102006/450929654ac4765a83324119603d02d6.mp3"
Ok , when I used a flash-based player , there was no problem . And when I use the "audio" tag without the script there is no problem .
I tried to fix this by passing php variable to " CURL " and it worked!
But it turned out that my host does not support the " CURLOPT_FOLLOWLOCATION " .
That was another option to look at the javascript source code audio player .
This is my html:
          <audio  id="audiobox" preload="auto" controls loop>
            <source src="http://live1.goear.com/listen/d941195f4a5f477381d8a95ba666a0cb/52eac666/sst2/mp3files/10102006/450929654ac4765a83324119603d02d6.mp3">

            <script type="text/javascript">
              function play() {
              document.getElementById('audiobox').play();
              }
                play();
            </script>

          </audio>

        <script src="jquery-1.11.0.min.js"></script>
        <script src="audioplayer.js"></script>

In this direction is the code javascript audio player:
I'm no expert in javascript but I think the problem must be in line 56: "this.attr AudioFile = $ ('src')." I think if I could define the php variable directly in the script it could run.
But do not know if there's another way:
http://pastebin.com/WxnTQmXa
This left a jsFiddle example, in this case the "src" attribute is calling the final URL that ends in MP3 and as you can see, the music plays and the player works.:
http://jsfiddle.net/aEXsL/2/
And here is the example with the problem, the same code just labeled "source" points to the URL that returns me the variable (remember that this only fails using this script):
http://jsfiddle.net/aEXsL/3/
It appears only one button (it means the player is failing).
Hope you can help me. Thanks in advance.
Edit:
Here is the link to the script author:
http://tympanus.net/Development/AudioPlayer/AudioPlayer.zip

A: Use this code
<script type="text/javascript">
var song=new Audio('http://live1.goear.com/listen/d941195f4a5f477381d8a95ba666a0cb/52eac666/sst2/mp3files/10102006/450929654ac4765a83324119603d02d6.mp3');
song.play();
</script>

but your link not contain any MP3 i think now


Q: How long it will take the inapp purchase pending status change to success In Apple purchase history
It is a question regarding my application in-app purchase pending. I am using store kit delegate function and  code as shown below
for (SKPaymentTransaction * transaction in transactions) {

    switch (transaction.transactionState)

    {

        case SKPaymentTransactionStatePurchased:

            [self completeTransaction:transaction];

            break;

        case SKPaymentTransactionStateFailed:

            [self failedTransaction:transaction];

            break;

        case SKPaymentTransactionStateRestored:

            [self restoreTransaction:transaction];

        case SKPaymentTransactionStateDeferred:

            [self DefferedTransaction:transaction];

            break;

        case SKPaymentTransactionStatePurchasing:

            [self PurchasingTransaction:transaction];

            break;

        default:

            break;

    }

};

Then I get a pending transaction . and I update my server database with temporary value. But I want to know when the pending transaction becomes a success.

A: It was quite interesting that I have run about one week behind the inApp pending issue . And I got an answer from apple side that is when we deal the inapp purchase with the below code `for (SKPaymentTransaction * transaction in transactions) {
switch (transaction.transactionState)

{

    case SKPaymentTransactionStatePurchased:

        [self completeTransaction:transaction];

        break;

    case SKPaymentTransactionStateFailed:

        [self failedTransaction:transaction];

        break;

    case SKPaymentTransactionStateRestored:

        [self restoreTransaction:transaction];

    case SKPaymentTransactionStateDeferred:

        [self DefferedTransaction:transaction];

        break;

    case SKPaymentTransactionStatePurchasing:

        [self PurchasingTransaction:transaction];

        break;

    default:

        break;

}

when a transaction is happen without any failure it will get SKPaymentTransactionStatePurchased state and we can proceed the applications process with success methods And no need to worry about the pending transaction apple consider this as success transaction and within 48 hours the amount will credit into the account.


Q: How should I batch upload to s3 and insert to MongoDB from nodeJS webserver with a final callback? I have a web server that accepts images from client, processes them, upload them to S3, batch-insert the urls to my mongoDB, and lastly sending the json result back to the client.
Working with a single image works as follows:
router.post("/upload", function(req, res){
    var form = new multiparty.Form();

    form.parse(req,function(err,fields,files){
        s3.upload({
                Key: filename,
                Bucket: bucketname,
                ACL: "public-read",
                Body: fs.createReadStream(filepath)
         }, function(err, data){
            if(err) //error handle

            Model.collection.insert({"name": "name", "url" : data.Location}, function(err, result){
                if(err) //error handle
                res.json({result: result})
            })
        })
    })
})

This works very well as I am simply uploading the file data to s3 -> when done, insert s3's output (url) to database -> when done, send mongo's result as jsonarray to the client.
The issue is - my client html excepts multiple type=file input with the same name=images, so that i can access them in my form parser as images[i]. The above algorithm is repeated images.length times. Problem rises when  I have to return the jsonarray result back to the client as I would have to wait for all of the asynchronous S3 upload->mongo insert to finish, and I can't pinpoint how and where the callback would be for this job.
What I've tried are the following:

*

*Iterate through images, upload them to S3 first, populate an array with the resulting url ([data.Location]). Batch insert them to mongoDB and return jsonarray result to client in the call back. This didn't work as mongo insert doesn't wait for S3 upload.

*Iterate through images, upload and insert the images to S3 and mongoDB each iteration. if (currentIndex = images.length), return jsonarray result. This doesn't work accurately as I do not know which images will end last (different size).

How should I design the algorithm to batch upload s3, batch insert to mongo, return result including s3 urls, filename etc back to client as jsonarray?
Thanks, in advance!

A: I usually solve this kind of problems with Promises, see: Bluebird.
You could then do a batch upload on S3 using Promise.all(), once you get that callback you can batch insert into Mongo, when done, run the final callback. OR, you could do a batch that does both things: upload->insert to mongo, and when all of those are done, return final callback. It will depend on your server and on how many files you want to upload at once. You could also use Promise.map() with the concurrency option set to whatever concurrent tasks you want to run.
Pseudo-code example:
Lets asume that getFiles, uploadFile and uploadToMongo return a Promise object.
var maxConcurrency =  10;

getFiles()
    .map(function(file){
        return uploadFile(file)
            .then(uploadToMongo)
    },{concurrency: maxConcurrency})
    .then(function(){
            return finalCallback();
    }).catch(handleError);

Example, how to manually "promisify* S3:
function uploadMyFile(filename, filepath, bucketname) {
    return new Promise(function(resolve, reject){
        s3.upload({
            Key: filename,
            Bucket: bucketname,
            ACL: "public-read",
            Body: fs.createReadStream(filepath)
        }, function(err, data){
            //This err will get to the "catch" statement.
            if (err) return reject(err);
            // Handle success and eventually call:
            return resolve(data);
        });
    });
}

You can use this as:
uploadMyFile
        .then(handleSuccess)
        .catch(handleFailure);

All nice and pretty!

A: If you cant get promises to work, you can store the status of your calls in a local variable. You would just break up your calls into 2 functions, a single upload and a bulk upload.
This is dirty code, but you should be able to get the idea:
router.post("/upload", function(req, res){
    var form = new multiparty.Form();

    form.parse(req,function(err,fields,files){
        if (err){
            cb(err);
        } else {
            bulkUpload(files, fields, function(err, result){
                if (err){
                    cb(err);
                } else {
                    res.json({result:result});
                }
            })
        }
    })
})

function singleUpload(file, field, cb){
    s3.upload({
            Key: filename,
            Bucket: bucketname,
            ACL: "public-read",
            Body: fs.createReadStream(filepath)
     }, function(err, data){
        if(err)
            cb(err);
        } else {
            Model.collection.insert({"name": "name", "url" : data.Location}, function(err, result){
                if(err){
                    cb(err);
                } else {
                    cb(null, result);
                }
            })
        }
    })
}

function bulkUpload (files, fields, cb) {
    var count     = files.length;
    var successes = 0;
    var errors    = 0;

    for (i=0;i<files.length;i++) {
        singleUpload(files[i], fields[i], function (err, res) {
            if (err) {
                errors++
                //do something with the error?
            } else {
                successes++
                //do something with the result?
            }

            //when you have worked through all of the files, call the final callback
            if ((successes + errors) >= count) {
                cb(
                    null,
                    {
                        successes:successes,
                        errors:errors
                    }
                )
            }
        });
    }
}

This would not be my recommended method, but another user has already suggested promises. I figure an alternative method would be more helpful.
Good Luck!


Q: Use 100% div width, if 50% width is too small How could one go about creating a div, that would have a default size of XX%, however, if the screen gets too small it would switch into 100% size? I have tried using min-width property but the problem with this is that it will not be responsive after the min-width is reached and will overflow if the screen is even smaller.

A: You have to use @media queries. So let's say you have a
 that should take up only 50% of the web page and then you need to show it full width once it enters mobile phone, say 640px width:
div {
  width: 50%;
}

@media screen and (max-width: 640px) {
  div {
    width: 100%;
  }
}

A: You can do it with @media queries, e.g.:

div {
  width: 50%;
  height: 100px;
  border: 1px solid;
}

@media (max-width: 568px) { /* adjust to your needs */
  div {width: 100%}
}

A: you must use @media for that like this :
@media screen and (min-width: 769px) {
    /* STYLES HERE */
}

@media screen and (min-device-width: 481px) and (max-device-width: 768px) {
    /* STYLES HERE */
}

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE */
}


Q: How to decode an utf8 encoded string split in two buffers right in between a 4 byte long char? A character in UTF8 encoding has up to 4 bytes. Now imagine I read from a stream into one buffer and then into the another. Unfortunately it just happens to be that at the end of the first buffer 2 chars of the 4 byte UTF8 encoded char are left and at the beginning of the the second buffer the rest 2 bytes.
Is there a way to partially decode that string (while leaving the 2 rest byte) without copying those two buffers into one big
string str = "Hello\u263AWorld";

Console.WriteLine(str);
Console.WriteLine("Length of 'HelloWorld': " + Encoding.UTF8.GetBytes("HelloWorld").Length);
var bytes = Encoding.UTF8.GetBytes(str);
Console.WriteLine("Length of 'Hello\u263AWorld': " + bytes.Length);
Console.WriteLine(Encoding.UTF8.GetString(bytes, 0, 6));
Console.WriteLine(Encoding.UTF8.GetString(bytes, 7, bytes.Length - 7));

This returns:

Hello☺World
Length of 'HelloWorld': 10
Length of 'Hello☺World': 13
Hello�
�World

The smiley face is 3 bytes long.
Is there a class that deals with split decoding of strings?
I would like to get first "Hello" and then "☺World" reusing the reminder of the not encoded byte array. Without copying both arrays into one big array. I really just want to use the reminder of the first buffer and somehow make the magic happen.

A: You should use a Decoder, which is able to maintain state between calls to GetChars - it remembers the bytes it hasn't decoded yet.
using System;
using System.Text;

class Test
{
    static void Main()
    {
        string str = "Hello\u263AWorld";

        var bytes = Encoding.UTF8.GetBytes(str);
        var decoder = Encoding.UTF8.GetDecoder();

        // Long enough for the whole string
        char[] buffer = new char[100];

        // Convert the first "packet"
        var length1 = decoder.GetChars(bytes, 0, 6, buffer, 0);
        // Convert the second "packet", writing into the buffer
        // from where we left off
        // Note: 6 not 7, because otherwise we're skipping a byte...
        var length2 = decoder.GetChars(bytes, 6, bytes.Length - 6,
                                       buffer, length1);
        var reconstituted = new string(buffer, 0, length1 + length2);
        Console.WriteLine(str == reconstituted); // true
    }
}


Q: Building an uberjar with Gradle I want to build an uberjar (AKA fatjar) that includes all the transitive dependencies of the project. What lines do I need to add to build.gradle?
This is what I currently have:
task uberjar(type: Jar) {
    from files(sourceSets.main.output.classesDir)

    manifest {
        attributes 'Implementation-Title': 'Foobar',
                'Implementation-Version': version,
                'Built-By': System.getProperty('user.name'),
                'Built-Date': new Date(),
                'Built-JDK': System.getProperty('java.version'),
                'Main-Class': mainClassName
    }
}

A: Simply add this to your java module's build.gradle.
mainClassName = "my.main.Class"
jar {
  manifest {
    attributes "Main-Class": "$mainClassName"
  }

  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

This will result in [module_name]/build/libs/[module_name].jar file.

A: I found this project very useful. Using it as a reference, my Gradle uberjar task would be
task uberjar(type: Jar, dependsOn: [':compileJava', ':processResources']) {
    from files(sourceSets.main.output.classesDir)
    from configurations.runtime.asFileTree.files.collect { zipTree(it) }

    manifest {
        attributes 'Main-Class': 'SomeClass'
    }
}

A: I replaced the task uberjar(.. with the following:
jar {
    from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {
        exclude "META-INF/*.SF"
        exclude "META-INF/*.DSA"
        exclude "META-INF/*.RSA"
    }

    manifest {
        attributes 'Implementation-Title': 'Foobar',
                'Implementation-Version': version,
                'Built-By': System.getProperty('user.name'),
                'Built-Date': new Date(),
                'Built-JDK': System.getProperty('java.version'),
                'Main-Class': mainClassName
    }
}

The exclusions are needed because in their absence you will hit this issue.

A: Have you tried the fatjar example in the gradle cookbook?
What you're looking for is the shadow plugin for gradle


Q: Save file from HTTP response Looking for some guidance or pointers, not necessarily the solution however I will post a solution back when done.
Using WSO2 ESB / Integrator that is calling an external service. According to the external service [1], they will respond with a file back in the HTTP response. It is this file that I am after; both to save the binary to disk and send to a user via web page redirect.
Can anybody point me in a direction in which I can take the HTTP response and create a file? I am presuming that I need to transform the response and use VFS.
Any help would be greatly appreciated.
[1] - https://support.webmerge.me/hc/en-us/articles/206526216-Webhook

A: It is fairly straight forward, the first step is to enable the transport sender for VFS (and the receiver if you also want to read files) in de axis2.xml config file.
The lines are already there and just need to be uncommented.
<transportReceiver name="vfs" class="org.apache.synapse.transport.vfs.VFSTransportListener"/>

<transportSender name="vfs" class="org.apache.synapse.transport.vfs.VFSTransportSender"/>

Next you will need to transform your response to whatever format you want to write to the file. You could use an xslt transformation, payload mediator or datamapper mediator for example.
After that you simple send the payload to a vfs endpoint. This can be a local file location, or a remote ftp location for example. Make sure you have the correct privileges to write a file in said location. For example if you run your esb as WSO2 user, and want to write files to /opt/wso2/fileexchange, make sure the WSO2 user has write privileges on that folder.
Then to write to that location just use a send mediator like this:
<property xmlns:ns2="http://org.apache.synapse/xsd" name="transport.vfs.ReplyFileName" value="myFile.txt" scope="transport"/>
    <property name="OUT_ONLY" value="true"/>
    <send>
        <endpoint name="FileEpr">
            <address uri="vfs:file:///opt/wso2/fileexchange"/>
        </endpoint>
    </send>

Make sure to set the transport.vfs.ReplyFileName property to the filename you want to write. And the OUT_ONLY property, since the filesystem is not going to send a nice reply back to you.
For more on this subject you can always check this blog

A: I prefer send the URI which refer to the file instead of sending the binary data. So the more efficient way is upload the file to a FileSystem, then transfer it with a String(URI). Only when you need read the file's data, then download it from FileSystem. And you should ensure the network is OK between FileSystem and the final user.


Q: Azure Service bus queues have a URL, do they also have an IP-Adress or even Range? I was wondering if there is any possibility of Service Buses or even their queues have an IP-address or even Ranges? I have been searching both in the documentation and also in azure but I couldn't find anything.
What are the possibilities here when it comes to IP-Control so to speak? is it a question of upgrading the Pricing teir for the service bus?

A: It doesn't work that way. The service is only accessible via DNS, not IP address.
Upgrading from Standard tier to Premium gives you throughput and latency commitment, but not an IP address.


Q: Is there a way to dynamically evaluate/use an angular (angular 2+) pipe? Let's say I have a pipeVar, it can be any pipe, eg.: number, uppercase, customPipe, etc
Is there a simple way to just call something like
{{ myVal | pipeVar }}

or some special syntax like
{{ myVal | #pipeVar }}

?
The closest thing I have found so far is Dynamic pipe in Angular 2

A: i have update plunkr plunkr link
Change in dynamic-pipe.ts like this
const dynamicPipe = "";
//i have give one simple logic for example if your dynamic pipe is like
this.dynamicPipe = ['number','uppercase','customPipe']; //pipe,pipe1 ... pipeN
//now create a one variable like 'number' | 'uppercase' | 'customPipe'
for (let i=0;i<this.dynamicPipe.length;i++){
     dynamicPipe = dynamicPipe + " | "+this.dynamicPipe[i];
}
@Component({
    selector: 'dynamic-comp',
    template: '{{ data ' + dynamicPipe + '}}'
})


Q: Unity Leap Motion Error Message "INPUT AXIS NOT SET UP" I'm currently doing my first VR project with Leap Motion, HTC Vive and Unity.
When I create a new project and add the LeapRig, everything is just fine, but after adding the Interaction Manager as a child of LeapRig, I get the following error message, which gets repeated multiple times a second:
INPUT AXIS NOT SET UP.  Go to your Input Manager and add a definition for  on the 9th Joystick Axis.
UnityEngine.Debug:LogError(Object)
Leap.Unity.Interaction.InteractionXRController:fixedUpdateGraspButtonState(Boolean) (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionXRController.cs:733)
Leap.Unity.Interaction.InteractionXRController:fixedUpdateGraspingState() (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionXRController.cs:706)
Leap.Unity.Interaction.InteractionController:fixedUpdateGrasping() (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionController.cs:1783)
Leap.Unity.Interaction.InteractionController:Leap.Unity.Interaction.IInternalInteractionController.FixedUpdateController() (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionController.cs:259)
Leap.Unity.Interaction.InteractionManager:fixedUpdateInteractionControllers() (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionManager.cs:372)
Leap.Unity.Interaction.InteractionManager:FixedUpdate() (at Assets/LeapMotion/Modules/InteractionEngine/Scripts/InteractionManager.cs:299)

Has anyone an idea why this happens and how to fix it?
I already worked with the interaction manager, but suddenly this error message occured.
I can run my program just fine too, but the error bothers me anyway and makes it difficult to use the console properly.
Greetings from Germany
Marc

A: From the Interaction Engine docs:

If you intend to use the Interaction Engine with Oculus Touch or Vive
  controllers, you'll need to configure your project's input settings
  before you'll be able to use the controllers to grasp objects. Input
  settings are project settings that cannot be changed by imported
  packages, which is why we can't configure these input settings for
  you. You can skip this section if you are only interested in using
  Leap hands with the Interaction Engine.
Go to your Input Manager (Edit -> Project Settings -> Input) and set
  up the joystick axes you'd like to use for left-hand and right-hand
  grasps. (Controller triggers are still referred to as 'joysticks' in
  Unity's parlance.) Then make sure each InteractionXRController has its
  grasping axis set to the corresponding axis you set up. The default
  prefabs for left and right InteractionXRControllers will look for axes
  named LeftXRTriggerAxis and RightXRTriggerAxis, respectively.
Helpful diagrams and axis labels can be found in Unity's
  documentation.


Q: CMFCPropertyGridCtrl last item not drawn? I have a CMFCPropertyGridCtrl that I'm using in an options dialog box.  I have a method in my options dialog class called InitPropertyGrid().  This method clears any properties and populates the CMFCPropertyGrid objects (using a custom Settings object for the property values) and appends them to the grid.
When I open my dialog box the first time all the properties show correctly.  However, if I then close my dialog box and reopen it, the very last property is not drawn on the screen.  All other properties are drawn normally:
First time:

All subsequent times:

As you can see, the plus/minus icon is showing minus in both cases to indicated the section is expanded.  When the last item is not showing, clicking on the +/- icon once to contract and once to expand causes the last item to be correctly shown.
Note when I close the dialog box, I do not destroy it but just reshow it.  However immediately before calling ShowWindow on the dialog I call the InitPropertyGrid() (called by UpdateToCurrentSettings) method.
if(optionsDialog_ == NULL)
{
    optionsDialog_ = new OptionsDialog(settings_, this);
    optionsDialog_->Create(OptionsDialog::IDD, this);
}

optionsDialog_->UpdateToCurrentSettings();
optionsDialog_->ShowWindow(SW_SHOW);

A: I found I can eliminate this problem simply by calling myPropertyGrid.ExpandAll(TRUE) at the end of the code where I initialize the property grid (InitPropertyGrid() for me).  This seems to force all the properties to expand.


Q: Appropriate substitute for inetd on Windows platform? What is the appropriate Windows XP or later way to summon a remote communications process that would be analogous to inetd on Unix/Linux?  For example, how does VNC client connect to the VNC server on Windows?  I have an application on Linux that I want to port to Windows XP, this application is a client-server architecture where the client summons the server using inetd.

A: Inetd is a "daemon".  The equivalent functionality in Windows would be to create a "service".
VNC, in fact, installs as a service.
Common protocols like HTTP, FTP and SMTP are implemented by the "Web publishing service" (IIS), should you choose to enable IIS.
And, of course, you can write, register and enable any service you wish, that does anything you wish.  Including listen on a TCP/IP port for incoming client requests.

A: Cygwin has xintd ported to windows.
I use xMing, for X and cygwin for the rest of my unix tools on win7 and use to on XP.
If you are sure that your user base can install cygwin, this may be your easy way to port.
If you want to go the pure windows route build a service


Q: Java script object data for functions How do I acces some object data in a javascript function? All I want to do is to take some input from the html file and then if the input text is === to one of my objects in javascript i want to acces some data from that object to use within my function.
For example:
I have the html form with 2 text inputs and a button to acces the function. And in the javascript document I have two objecst called bob and susan with the data "bob.age = 25" and "susan.age = 30". So I want a function that calculates bob.age + susan.age. But I want to use the  inputs of bob and susan in my form html. So when i have the inputs bob and susan i want the function to do bob.age + susan.age
here is my html form:
<form name="mmForm">
       E1
       <input type="text" id="element1">
       E2
       <input type="text" id="element2">
       <input type="button" value="Calculate" onclick="procesForm_mm()">

Result:

   </form>

here my javascript function:
function procesForm_mm() {
var e1 = document.mmForm.element1.value;

var e2 = document.mmForm.element2.value;

result_mm = parseInt(e1) + parseInt(e2);

document.getElementById("resultfield_mm").innerHTML += result_mm;
}

and this is the data i want to acces:
var Fe = new Object();
Fe.denumire = "Fier";
Fe.A = 56;
Fe.Z = 26;
Fe.grupa = "VIIIB";
Fe.perioada = 4;

A: Try this (a lot of guessing involved):
function procesForm_mm() {
    var e1 = document.mmForm.element1.value;
    var e2 = document.mmForm.element2.value;
    result_mm = parseInt(eval(e1).A) + parseInt(eval(e2).A);
    document.getElementById("resultfield_mm").innerHTML += result_mm;
}

var Fe = new Object();
Fe.denumire = "Fier";
Fe.A = 56;
Fe.Z = 26;
Fe.grupa = "VIIIB";
Fe.perioada = 4;

var Co = new Object();
Co.denumire = "Cobalt";
Co.A = 59;
Co.Z = 27;
Co.grupa = "IXB";
Fe.perioada = 4;

See it working here: http://jsfiddle.net/KJdMQ/.
It's important to keep in mind that use of the JS eval function has some disadvantages: https://stackoverflow.com/a/86580/674700.
A better approach would be to keep your JS objects in an array and avoid the use of the eval function:
function procesForm_mm() {
    var e1 = document.mmForm.element1.value;
    var e2 = document.mmForm.element2.value;
    result_mm = parseInt(tabelPeriodic[e1].A) + parseInt(tabelPeriodic[e2].A);
    document.getElementById("resultfield_mm").innerHTML += result_mm;
}
var tabelPeriodic = [];

tabelPeriodic["Fe"] = new Object();
tabelPeriodic["Co"] = new Object();

var el = tabelPeriodic["Fe"];
el.denumire = "Fier";
el.A = 56;
el.Z = 26;
el.grupa = "VIIIB";
el.perioada = 4;

el = tabelPeriodic["Co"];
el.denumire = "Cobalt";
el.A = 59;
el.Z = 27;
el.grupa = "IXB";
el.perioada = 4;

(See it working here)
Note: This looks like a chemistry application, I assumed that the form is supposed to add some chemical property values for the chemical elements (i.e. A possibly being the standard atomic weight). The form would take as input the names of the JS objects (Fe and Co).


Q: Dual head configuration with two touchscreens in Linux As a part of my current project I need to set up a Linux-based workstation with two monitors, both of which are multitouch-enabled (ViewSonic VX2258wm, Quanta touch panel). So, naturally, I set up a dual-head configuration and I connect the touchpanels using USB cables. While dual-head output works just fine, the operating system doesn't differentiate between the first and the second touch panels (so, if the first monitor is active, and I touch the second, the mouse pointer moves to the corresponding coordinates of the first monitor). I understand that the X server knows nothing about which touch panel corresponds to which monitor (since those are logically and, as a matter of fact, physically, different devices).
Does anyone know if it is possible to make such configuration work right? Any suggestions, hints, kludges will be appreciated.

A: You need to setup the two input devices manually in xorg.conf and specify the offset for each one so that they map to the correct location in your overall X screen setup.
Each input driver will need to be specifically mapped by to the ID of the device it corresponds to. Not specifying this will cause the driver to take over ANY matching devices.
After you have two separate input devices working, you just need to use the corresponding option for whatever the driver is to specify the coordinate space or offset.


Q: Setting APPMENU_DISPLAY_BOTH for gtk3 applications does not work To start the application with the menu enabled in the application and the panel, the following command has to be used:
APPMENU_DISPLAY_BOTH=1 appname

I recently discovered that this only works for non-gtk3 applications in Ubuntu 12.04 LTS, i.e. if you replace appname with applications such as gnome-terminal, gedit, evince, empathy, evolution, rhythmbox, nautilus, etc. only global menus will be displayed. However, if you start, for example, gimp or inkscape by using APPMENU_DISPLAY_BOTH, both global and local menus will be shown.
The questions is: why is APPMENU_DISPLAY_BOTH not taken into account when starting such gnome applications?
P.S. I know how to disable global menus in order to get the local ones (UBUNTU_MENUPROXY trick, removing appmenu-gtk/qt packages, removing the indicator-appmenu, etc.)
Thanks for the help!


Q: root in binary tree always NULL The program should read a txt, store all the words alphabetically and print them in order, with the number of times the word appears on the txt.
The problem seems to be in the Insert method, because it never prints TEST, so it seems the pAux is always NULL for some reason. And because of that, the Print method returns in his first call.
What am I doing wrong?
tree.h
#ifndef TREE_H_
#define TREE_H_

typedef struct Item{
    char* key;
    int no;
} TItem;

typedef struct No{
    TItem item;
    struct No* pLeft;
    struct No* pRight;
} TNo;

void TTree_Insert (TNo**, char[]);
void TTree_Print (TNo*);

#endif

tree.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tree.h"

TNo* TNo_Create (char* c){
    TNo* pNo = malloc(sizeof(TNo));
    pNo->item.key = malloc(sizeof(char)*strlen(c));
    strcpy(pNo->item.key, c);
    pNo->item.no = 1;
    pNo->pLeft = NULL;
    pNo->pRight = NULL;
    return pNo;
}

void TTree_Insert (TNo** pRoot, char word[80]){
    char* c = malloc(sizeof(char)*strlen(word));
    strcpy(c, word);
    TNo** pAux;
    pAux = pRoot;
    while (*pAux != NULL){
        if (strcmp(c, (*pAux)->item.key) < 0) pAux = &((*pAux)->pLeft);
        else if (strcmp(c, (*pAux)->item.key) > 0) pAux = &((*pAux)->pRight);
        else{
            (*pAux)->item.no++;
            return;
        }
    }
    *pAux = TNo_Create(c);
    return;
}

void TTree_Print (TNo *p){
    if (p == NULL) return;
    TTree_Print (p->pLeft);
    printf("%s - %d", p->item.key, p->item.no);
    TTree_Print (p->pRight);
}

main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "tree.h"

int main(){
    TNo* pRoot = NULL;
    FILE* txt = fopen("Loremipsum.txt", "r");
    char aux[80];
    int c, x = 0;

    while ((c = fgetc(txt)) != EOF){
        while (!(isalpha((char)c))) c = fgetc(txt);
        while (isalpha((char)c)) {
            if (isupper((char)c)) c = c+32;
            if (islower((char)c)) aux[x++] = (char)c;
            c = fgetc(txt);
        }
        aux[x] = '\0';
        TTree_Insert(&pRoot, aux);
        x = 0;
        aux[0] = '\0';
    }
    TTree_Print(pRoot);
    fclose(txt);
    return 0;
}

A: I did not look through all your code. I will answer only your question. You have to pass pRoot to TTree_Insert by reference. Otherwise you pass its copy to the function and any changes of the copy within the function do not influence the original value.
For example
void TTree_Insert ( TNo **pRoot, char word[80] ){
    char* c = malloc(sizeof(char)*strlen(word) + 1 ); // <==
    strcpy( c, word ); // <==
    TNo* pAux;
    pAux = *pRoot;
    //...

And in main you have to call the function like
TTree_Insert( &pRoot, aux );

Take into account that you have to adjust  all other code of the function. For example
void TTree_Insert( TNo **pRoot, const char word[80] )
{
    char* c = malloc( sizeof( char ) * strlen( word ) + 1 );

    strcpy( c, word );

    TNo **pAux = pRoot;

    while ( *pAux != NULL )
    {
        printf("TESTE");
        if ( strcmp(c, ( *pAux )->item.key ) < 0 )
        {
            pAux = &pAux->pLeft;
        }
        else if ( strcmp(c,  ( *pAux )->item.key ) > 0 )
        {
             pAux = &pAux->pRight;
        }
        else
        {
            ( *pAux )->item.no++;
            break;
        }
    }

    if ( *pAux == NULL ) *pAux = TNo_Create(c);

    return;
}

I hope it will work.:)

A: pRoot is initially NULL, and you never change it later.

so it seems the pAux is always NULL for some reason

Well, that's the reason... why don't you use a debugger or do some printing?


Q: tex4ht produces quotation marks instead of German umlauts A simple file with umlauts compiled using
make4ht test "xhtml,charset=utf-8" " -cunihtf -utf8"
shows question marks instead of German umlauts.
Here the MWE test.tex:
\documentclass{article}
\usepackage[utf8]{inputenc} %Files are encoded using UTF-8
\usepackage[T1]{fontenc} %The text uses German umlauts
\begin{document}
A text with some „ÜÖÄüöäß“.
\end{document}

Output:
A text with some „�������“.

This seams to be a bug in the current MikTeX installation (is it a bug of tex4ht or MikTex?).
My current workaround was to copy the file unicode.4hf
from
C:\Program Files\MiKTeX 2.9\tex4ht\ht-fonts\unicode\charset
to
C:\Program Files\MiKTeX 2.9\tex4ht\ht-fonts\unicode\charset\uni
which solved the problem.

A: There is indeed a problem with the current MikTeX distribution, see bug report and comments at https://sourceforge.net/p/miktex/bugs/2350/. The bug, which was originally reported by Ulrike Fischer and in the meantime has been marked as closed, still persists.
As mentioned there, the current workaround is copying the file unicode.4hf from C:\Program Files\MiKTeX 2.9\tex4ht\ht-fonts\unicode\charset to C:\Program Files\MiKTeX 2.9\tex4ht\ht-fonts\unicode (or to C:\Program Files\MiKTeX 2.9\tex4ht\ht-fonts\unicode\charset\uni).
If using make4ht with the -u option (as suggested by Michal), make4ht calls tex4ht with -cmozhtf option. Then tex4ht is actually supposed to look for unicode.4hf in ht-fonts/mozilla/charset/ directory but fails to find it there. In this case one should copy unicode.4hf from C:\Program Files\MiKTeX 2.9\tex4ht\ht-fonts\mozilla\charset to C:\Program Files\MiKTeX 2.9\tex4ht\ht-fonts\mozilla.


Q: which is fastest for an oracle query? This
select * from customers where id = 1;
select * from customers where id = 2;

or
select * from customers where id in(1,2);

which is faster?

A: The first one are actually two statements causing you to make two roundtrips to the database.
The second one will most likely be faster as it is just one statement.

A: Is this really what you are trying to determine? Are you asking if it is faster to make one trip returning two rows or two trips each returning one row? If that is the question, then I agree with the comments -- try it, measure it, and compare.
If you are trying to make this kind of thing efficient, then you should probably look at using bind variables instead. If your question really means what it says, then probably any answer here will do.

A: Any question with "faster" is always going to be dependent on the specifics of your database. I don't really have anything to add over plhmhck and MJB about the fact that you're talking about 2 queries vs. 1 query.
But be aware the the optimizer will usually (always?) rewrite WHERE id IN (1,2) to WHERE (id = 1 OR id = 2)


Q: Distributing processing for an application that wasn't designed with that in mind We've got the application at work that just sits and does a whole bunch of iterative processing on some data files to perform some simulations.  This is done by an "old" Win32 application that isn't multi-processor aware, so new(ish) computers and workstations are mostly sitting idle running this application.
However, since it's installed by a typical Windows Install Shield installer, I can't seem to install and run multiple copies of the application.
The work can be split up manually before processing, enabling the work to be distributed across multiple machines, but we still can't take advantage of multiple core CPUs.  The results can be joined back together after processing to make a complete simulation.
Is there a product out there that would let me "compartmentalize" an installation (or 4) so I can take advantage of a multi-core CPU?  I had thought of using MS Softgrid, but I believe that still depends on a remote server to do the heavy lifting (though please correct me if I'm wrong).
Furthermore, is there a way I can distribute the workload off the one machine?  So an input could be split into 50 chunks, handed out to 50 machines, and worked on?
All without really changing the initial application?
In a perfect world, I'd get the application to take advantage of a DesktopGrid (BOINC), but like most "mission critical corporate applications", the need is there, but the money is not.
Thank you in advance (and sorry if this isn't appropriate for serverfault).

A: Long story short, if the process isn't multi-processor or distributed computing aware then no you can't make it so yourself.
You could use simple virtualisation (Virtual PC, VMWare's desktop product) to run several copies 'side by side' on the same hardware but this will not be "multi-processor aware" or "distributed" computing, it'll be several completely separate processes working on different work queues. Its hard to tell from your post but I think that may well be all you're trying to do anyway.

A: You may get better help on Stack Overflow -- Basically what you want to do is install N copies of the software and write a "front end" that takes the workload, chops it into N pieces & gives it to the isolated "back-end" copies of the program (automating the manual division you described).
The actual implementation (the separate installations & front end) depends on how your software is written.  Also if your finished work needs to be re-integrated (you have 4 chunks that need to become one piece) the custom front-end needs to be smart enough to do that too...

A: You've said you can't install more than one copy of the software, but can you run more than one copy of the software? You shouldn't need to do the former to be able to do the latter, I would think. If something in the software prevents multiple running copies, you might be able to hack up the EXE with a resource editor to remove or bypass that limitation.


Q: .Net HotChocolate GraphQL Mutations pick from a list of stings like enum I have a bunch of data, in a .NET GRaphQL API that are basically list of strings like
Public List<string> avarageMessageSize = new List<string>{
"Up to 5 KB",
"Between 5 KB and 4 MB",
Between 4 MB and 20 MB",
"20 MB and bigger"
};

When a new Entity is made with a GraphQL Mutation, for other values that are stored in Enums I have input types that let me choose and pick in a mutation to add the correct value, is this also possible for list items, to pick and choose the correct value(string) in a Mutation?

A: You can easily make the string an enum. Essentially a GraphQL enum can be represented by any object in dotnet.
The strings have to follow the GraphQL enum rules. So Up to 5 KB would probably be represented by Up_to_5KB. But in your dotnet API you would just use the Up to 5 KB string.
The GraphQL engine would translate it to the enum in GraphQL. You also cannot have arbitrary values anymore, they must be represented by the enum values allowed in this case.


Q: How to send a notification without waking the screen on Android I have a foreground service in my app, whose persistent notification has a timer in it, which means that the notification is sent once per second to update the timer that is shown in the notification.  This means that on some devices, where notifications are set to either wake the screen entirely or show a dark version on the screen briefly, the screen is constantly awake.
Is there a way to send the notification in a way that it won't wake up the screen?  Setting it as a silent notification on the device fixes this, but the point of a foreground service notification is that it's prominent on the device, so this isn't a great solution, and not all users would know to do that.
This is how I'm building the notification:
NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Currently Reading")
            .setSound(null)
            .setContentIntent(TaskStackBuilder.create(this).run {
                addNextIntentWithParentStack(timerIntent)
                getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                )
            })
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)

A: Have you tried updating the notification instead? And use setOnlyAlertOnce()
"You can optionally call setOnlyAlertOnce() so your notification interupts the user (with sound, vibration, or visual clues) only the first time the notification appears and not for later updates."
Check this link
https://developer.android.com/training/notify-user/build-notification.html#Updating

A:
setPriority(NotificationCompat.PRIORITY_DEFAULT)?

lower it, so wont be shown on lockscreen (android 7 and up)
and here we go with a small fix for this part:
setPriority(NotificationCompat.PRIORITY_LOW)
you can also add:
setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
but it'll also remove notification from lockscreen...
docs:

*

*https://developer.android.com/training/notify-user/build-notification.html#lockscreenNotification

*https://developer.android.com/training/notify-user/channels#importance
hope this helps =]


Q: How can I assign RGB color codes to a WORD? I am assigning the color values to the display frame buffer, and that buffer pointer return type is BYTE. But i am not able to assign the RGB color value into it. This i am doing to set the pixel location using directdraw on WINCE platform .Here is the snapshot code.
BYTE* pDisplayMemOffset = (BYTE*) ddsd.lpSurface;

int x = 100;

int y = 100;

pDisplayMemOffset += x*ddds.lXPitch + y*ddds.lPitch ;

***(WORD*)pDisplayMemOffset = 0x0f00;

But how i can assign RGB(100,150,100) combination in this, i have tried to put DWORD instead of WORD while assigment but it desnt work. i knw i required hex value for color in 0x000000 format(RGB), but i think BYTE cnt store such large value into it.
Can anyone tell me how to do this?

A: How this assignment can be done is very dependent on the pixel-format you specified when acquiring ddsd. See the field ddpfPixelFormat and also specifically in there: dwRGBBitCount.
Maybe you can provide this pixel format information so that i can improve my answer. However, i can easily give you an example of how you do this pixel-color assignment if e.g. the pixel-format is:
[1 byte red] [1 byte green] [1 byte blue] [1 byte unused]

Here's the example:
*(pDisplayMemOffset+0) = 0x10;// asigning 0x10 to the red-value of first pixel
*(pDisplayMemOffset+1) = 123; // asigning 123 to green-value of first pixel
                              // (no need for hex)
*(pDisplayMemOffset+4) = 200; // asigning 200 to red-value of second pixel
                              // (BYTE is unsigned)

If you have to extract the color values from an integer it largely depends on which byte-ordering and color-ordering that integer was given in, but you can try it out easily.
First i would try this:
*(((unsigned int*)pDisplayMemOffset)+0) = 0x1A2A3A4A
*(((unsigned int*)pDisplayMemOffset)+1) = 0x1B2B3B4B

If this works, then the pixel-format had either an unused 4th byte (like my example above) or an alpha-value that is now set to one of the values. Again: aside from the pixel-format also the ordering of the bytes in your integer decides whether this directly works or whether you have to do some byte-swapping.


Q: Image files stored on Google cloud storage are not displayed but only strange text I have a project that uploads an multi-image to Google cloud storage, the upload works fine, but when I download an image, it only shows strange text.
It has 2 steps to upload a file to Google cloud storage. In step 1, I will get the URL that will help me upload the file to the storage. Step 2, I will upload the file to the response URL I got from step 1. And I can download the file from the response in step 2
Step 1: get upload URL from GCS
    Options requestHeaders = await getRequestOptions(jwtBearer, hashing);
requestHeaders.headers!['Content-Type'] = 'application/json';
var signedUrlFiles = await dio.post(
  genUrlsApi,
  data: {
    ...(body != null ? body.toJson() : {}),
    'files': files
        .map((f) => FileElement(
        fileName: f.fullName, type: buildApiQuery(f.type)["type"]!)
        .toJson())
        .toList()
  },
  queryParameters: query,
  options: requestHeaders,
);
var response = DBSBaseResponse.fromJsonFactory(signedUrlFiles.data);
GCSUploadFileResponse result = GCSUploadFileResponse.fromJsonFactory(response.data);

step 2 : upload file from GCS URL
for(var file in result.files){
    var file = files.firstWhere((f) => f.fullName == url.fileName);
    FormData formData = FormData.fromMap({
    'file': await MultipartFile.fromFile(
      file.uri,
      filename: url.fileName,
    ),
  });
  var result = await dio.put(
    url.url,
    data: formData,
    onSendProgress: (
      int sent,
      int total,
    ) {
     //show logger
    },
  );

}
I can not show the image because the company policy. sorry for this trouble


Q: My function click() dont work with href of this site, how i can fix and make work? from selenium import webdriver
from selenium.webdriver.chrome.service import Service
#Service("local do diretorio do chromeDriver")

driver = webdriver.Firefox('/home/arch/Downloads/bot/')
driver.get("https://blaze.com/pt/?modal=auth&tab=login")

element=driver.find_element_by_name("username").send_keys("email")
driver.find_element_by_name("password").send_keys("pass")
#link da url desejada

driver.find_element_by_xpath('/html/body/div[1]/main/div[3]/div/div[2]/div[2]/form/div[4]/button').click()
driver.find_element_by_xpath('/html/body/div[1]/main/div[1]/div[4]/div[2]/div[1]/div/div/div[4]/div[1]/div/div[3]/div/a')

I have this code in python that opens in blazer.com and makes login but when i try to click o game mines which in this href:
<a href="/pt/games/mines"/>

and doesnt work justs stops , someone could help with this error

A: You probably forgot to click the "mines" button. Don't forget the .click() at the end of your code, like this:
driver.find_element_by_xpath('/html/body/div[1]/main/div[1]/div[4]/div[2]/div[1]/div/div/div[4]/div[1]/div/div[3]/div/a').click()

And you also might want to give the site some time to load by importing time and using time.sleep(x) which sleeps the code for x seconds.
import time

time.sleep(2) # Use this between the .click() lines to give the site time to load after clicking a button


Q: what does my request does not inlclude if-non-match in header I am using https://github.com/filipw/AspNetWebApi-OutputCache NUGET package to manage caching for my ASP.NET WEB API.
The server side caching works well. However I don't see it working on my browser (client side).
On request I see that max-age and etag is being returned.
However I make further request I don't see etag being supplied with request header with if-non-match parameter. This is why I get response 200 (OK) back with response data. It should have parsed data from cache itself.
https://dl.dropboxusercontent.com/u/2781659/stackoverflow/Cache.jpg
Can anybody please advise?

A: I just briefly looked at the Github project you referenced, and I wanted to throw in my $0.02, for whatever it's worth -
Breeze.js is responsible for taking care of client side caching for you.  The idea is to not have to worry about what the back-end is doing and simply make a logical decision on the client on whether to proceed and hit the server for data again.  If you don't need to refresh the data, then never hit the server, just return from Breeze's cache.
The project you are referencing seems to do both - server side and client-side caching.  The decision of caching on the server is one not to be taken lightly, but this project seems to handle it pretty well.
The problem is that you are trying to mix two libraries which, at best, conflict in the area of what their concerns are.  There may be a way to marry the two up, but at what cost?  Why would you need to cache on the server that which is already cached on the client?  Why cache on the client if you plan to cache the exact same data on the server?
The only reason I can think of is for paging of data (looking at a subset of the whole) and wanting to see the next data set without having to hit the server again.  In that case, your query to the server should not match the original anyway and therefore one would expect that you need to customize the two solutions to do what you are asking for.
In general that project seems to ignore queryString parameters, from what I can tell, to support JSONP so you should have no problem coming up with a custom solution, if you still think that is necessary.


Q: Sort any random list of files by modification date Looking for generic way how to sort a random list of files by its modification time, so something like:
./make_list_of_files | some_sorter_by_mtime

my currect solution is (here the make_list_of_files is the find command):
find / -type f -print |\
  perl -nle 'push @in,$_;END {@out = sort{ (stat($a))[9] <=> (stat($b))[9] } @in; $,="\n";print @out}'

exists some simpler solution (e.g. without perl)?

A: Your some_sorter_by_mtime should be for example:
xargs stat -f "%m %N" | sort -n | cut -f2-

the idea behind is:

*

*print out file modification time and the filename

*sort the output numerically (so by modification time)

*cut out the time field

so,
find / -type f -print | xargs stat -f "%m %N" | sort -n | cut -f2-

A: Like this?
find / -type f -print | xargs ls -l --time-style=full-iso | sort -k6 -k7 | sed 's/^.* \//\//'

A: Yes, without perl:
find / -type f -exec ls -lrt '{}' \+

Guru.


Q: CSS rotate3d works correctly only on Firefox The CSS rotate3d animation seems to depend on the (modern) browser you use!!! Just test the code...
@keyframes KF_Rotate {
                       0% { transform: rotate3d(0,0,0,  0deg); }
                     100% { transform: rotate3d(0,1,0,180deg); }
                     }
.Rotate:hover { animation: KF_Rotate 3s; }

How is it possible?


Q: Authorize ARB subscription payment I am creating a subscription using Authorize.net ARB API. I can see in my account, where the subscription is created.
Its a very simple subscription, where a user would be paying $100 every month. I would like to know, if the user would be billed at the time of creation of the subscription ?
My understanding is that, he would be billed only from next month ? Any idea, how to bill the customer from the time the subscription is created ?
Thanks

A: ARBCreateSubscriptionRequest has parameter "startDate" where you can set date the subscription begins.
If first price should be different from monthly payments you can also set parameter "trialAmount" for first payment
All information you can find here
http://www.authorize.net/support/ARB_guide.pdf

A: You should always charge the first subscription payment using the AIM API. The AIM API will process immediately and act as a verification for the credit card. You will know immediately if a card is invalid and before you create the subscription. If you schedule a payment to process the same day the subscription is created it does not process immediately. That process later that night. If the credit card is invalid you lose the opportunity to have the user correct it because they are no longer present at your website.


Q: How to sync the modification date of folders within two directories that are the same? I have a Dropbox folder on one computer with all the original modification dates. Recently, after transferring my data onto another computer, due to a .DS_Store issue, some of the folder's "Date Modified" dates were changed to today. I am trying to write a script that would take the original modification date of a folder, and then be able to find the corresponding folder in my new computer, and change it using touch. The idea is to use stat and touch -mt to do this. Does anyone have any suggestions or better thoughts? Thanks.

A: Use one folder as the reference for another with --reference=SOURCE:
$ cd "$(mktemp --directory)"
$ touch -m -t 200112311259 ./first
$ touch -m -t 200201010000 ./second
$ ls -l | sed "s/${USER}/user/g"
total 0
-rw-r--r-- 1 user user 0 Dec 31  2001 first
-rw-r--r-- 1 user user 0 Jan  1  2002 second
$ touch -m --reference=./first ./second
$ ls -l | sed "s/${USER}/user/g"
total 0
-rw-r--r-- 1 user user 0 Dec 31  2001 first
-rw-r--r-- 1 user user 0 Dec 31  2001 second


Q: Overriding Rails Default Routing Helpers I'm writing an app where I need to override the default routing helpers for a model.  So if I have a model named Model, with the corresponding helper model_path() which generates "/model/[id]".  I'd like to override that helper to generate "/something/[model.name]".  I know I can do this in a view helper, but is there a way to override it at the routing level?

A: You can define to_param on your model. It's return value is going to be used in generated URLs as the id.
class Thing
  def to_param
    name
  end
end

The you can adapt your routes to scope your resource like so
scope "/something" do
  resources :things
end

Alternatively, you could also use sub-resources is applicable.
Finally you need to adapt your controller as Thing.find(params[:id]) will not work obviously.
class ThingsController < ApplicationController
  def show
    @thing = Thing.where(:name => params[:id).first
  end
end

You probably want to make sure that the name of your Thing is unique as you will observe strange things if it is not.
To save the hassle from implementing all of this yourself, you might also be interested in friendly_id which gives you this and some additional behavior (e.g. for using  generated slugs)

A: You need the scope in routes.rb
scope "/something" do
  resources :models
end


Q: iOS command-line build: How to create xcode archive from command line? I am using below command to create an signed ipa file from command line i.e. terminal.
xcrun -sdk iphoneos PackageApplication \
    "path/to/build/MyApp.app" \
    -o "output/path/to/MyApp.ipa" \
    --sign "iPhone Distribution: My Company" \
    --embed "path/to/something.mobileprovision"
As understood from above, this will create an ipa file. But, I want to create a xcarchive file which will be used to upload to app store using Application Loader. How can I modify this command to achieve that. Any help will be greatly appreciated. Thanks...

A: Just use xcodebuild archive command


Q: Teamwork Ruby on Rails I've been working with RoR for a while but now I need to work with designers and other developers. Is there a tool like github or something like dropbox where you can share with your team the files but with a URL where you can check live any change. For example for my own I just run Rails s and I can see what happen on my localhost but for a designer it isn't that simple. And also we don't want everybody running his own rails project on his localhost.
So is there a tool or what do you do guys when you have to work with others collaborates?

A: You consider to use a staging environment?

A staging environment (stage) is a nearly exact replica of a production environment for software testing. Staging environments are made to test codes, builds, and updates to ensure quality under a production-like environment before application deployment. The staging environment requires a copy of the same configurations of hardware, servers, databases, and caches. Everything in a staging environment should be as close a copy to the production environment as possible to ensure the software works correctly.

See the Font
To use it, i recommend you a application like Heroku, after configure, you can 'deploy' your app commiting in a branch (its not real time, but works for your case).
If you have a VM, i recommends you this tutorial: https://emaxime.com/2014/adding-a-staging-environment-to-rails.html

A: Open questions like this are not really best placed on StackOverflow, which is geared more toward solving specific issues, with provided code examples and errors etc.
However, in answer to your question:
I see you mention Github in your question, but do you fully understand the underlying concept of Git Version Control, or is there a speficic reason as to why it doesn't meet your needs? As far as I believe, it's main purpose is to solve your exact scenario.
https://guides.github.com/introduction/git-handbook/


Q: MySQL Query Browser to run 400+ Insert Statements? I'm manually duplicating a few records and would like to paste the INSERT statements directly into Query Browser, but I have only ever performed one INSERT at a time with QB. Is it possible to insert, and run, 400+ inserts one after another without having to manually initiate each?

A: Open a New Script Tab, located under File. Paste your inserts, and press Execute.

A: as you said, yes it's possible....but IMO if you have the 400+ insert statements, you'd be better off saving them into a plain text file and running them with the mysql command line client.
that way, you get to use your favourite editor to create the file rather than a tiny little input window in the QB.  Your editor will probably also have far better editing capabilities, including syntax highlighting.
if the insert statements are all the same except for the actual data to be inserted, then you can put just the data in, say, a CSV file and write a simple perl/awk/php/whatever script to generate the SQL from that....then load that into your editor for any final edits.  or you could use the LOAD DATA statement instead of individual INSERT statements.
other advantages of using a text-file sql script are:

 it gives you a final chance to look over and check the sql script before running it
 you can run the sql script on a backup copy of the database first to verify that it's correct
 the sql script is documentation - a record of what you did.  you can put comments in it to explain why

finally, if you're using a database engine that supports transactions (e.g. innodb) then remember to use them to ensure that either ALL inserts are successfully completed, or NONE are.  that allows you to safely correct and re-run the sql script if there was an error.

A: The old MySQL Query Browser and MySQL Administrator have been replaced by MySQL Workbench.
MySQL Workbench includes:
- Model (replacing DBDesigner)
- Query (replacing MySQL Query Browser)
- Admin (replacing MySQL Administrator)
- SSH-Tunnel (Remote Admin)
MySQL Workbench discussions:
- http://forums.mysql.com/index.php?151


Q: TabBarController status bar issue in iOS7 I added the UITabBarController view on the UIWindow. TabBarController view is messing up with Status Bar. The TabBarController is in the MainWindow.xib. How can i fix this?
window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
tabController.viewControllers = [NSArray arrayWithObjects:nearbySplit, mySplit, allSplit, messageSplit, nil];
tabController.selectedIndex = 0;
    window.rootViewController = tabController;
    [window addSubview:tabController.view];

    [window makeKeyAndVisible];

A: Add the this code in view controller
if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
    self.edgesForExtendedLayout = UIRectEdgeNone;   // iOS 7 specific

in your viewDidLoad method.


Q: youtube api v3 does something when a user uploads a new video How can I do that when an user uploads a new video, my javascript code in node.js execute something?
I readed the docs and I didn't fond anything.


Q: How to upload a folder to blob storage using SAS URI in storage explorer enter image description hereI'm trying to upload a folder to blob container using storage explorer via SAS URI, but the upload is failing for folder & files. How can I achieve that ? When I connect to blob storage using account name and key it works fine, but not with SAS URI.

A: I've created several tests and all succeeded with SAS URI.

I think you should check a few places:

*

*According to your screen shot. Maybe your SAS key has expired?

*The URI configuration. We should concat the connect string and the  SAS token.

The configuration is as follows:

A: First you need to check the permissions allotted to SAS and also the expiry date, there can be two cases here: one you may not have adequate access to upload and second the SAS might have expired.
If this is a one time activity and then you can use AzCopy tool as well to upload files to blob storage.


Q: Creating site column without using features I am trying to create a site column in VS2010 without using features. Is this possible? If yes, please let me know where I can start looking.
I don't want to use feature because feature comes with its own maintainability headache which I want to avoid as much as possible. I want to be able to individually install/update/delete each site column that I create in any given environment.

A: You can create columns in three ways:

*

*By using the SharePoint
user interface

*By using the SharePoint object model

*By deploying a Feature that installs the
column based on an XML definition
file

A: If you are just trying to avoid using declarative xml to create the column, you can write C# code to create the column. But to deploy to your site through a wsp, it will still need to be packaged in a feature.
You could write a console application that runs on the server and executes the code to create the column. However, this seems like more of a maintainability headache than creating a feature.
Either way, the code would look something like this:
using(SPSite site = new SPSite("url-of-your-site"))
{
  using(SPWeb web = site.RootWeb)
  {
    web.Fields.Add("ColumnName", SPFieldType.Text, true);
  }
}

You could also create a Powershell script to add the column. Something like:
$site = Get-SPSite "your-site-url"
$web = $site.RootWeb
$column = '<Field Name=...' +
                 'ID=...' +
                  etc. +
          '></Field>'
$web.Fields.AddFieldAsXml($column)

But, really features aren't that bad once you accept that feature activation is the way to programmatically add elements to a SharePoint site.


Q: Need Help To Uncheck Radio Button If Aleady Checked Using Jquery i need help to uncheck or check same radio button if button already checked? I have jquery function which is used to enable or disabled other radio buttons if already checked now i want to add some function that use for check or uncheck same radio button?
(function ($) {
  $(document).ready(function () {
    $('input:radio').click(function(){
      var $inputs = $('input:radio')

      if($(this).is(':checked')){
        $inputs.not(this).prop('disabled',true);
      }else{
        $inputs.prop('disabled',false);
      }
    })

  });
})(jQuery);

<input type="radio" value="Test1" />Test1
<input type="radio" value="Test2" />Test2
<input type="radio" value="Test1" />Test1
<input type="radio" value="Test2" />Test2

A: Although it is too late to answer, it could help others
I tried this solution.
Works very well for me!
$("input[type='radio'].myClass").click(function(){
        var $self = $(this);
        if ($self.attr('checkstate') == 'true')
        {
            $self.prop('checked', false);
            $self.each( function() {
                $self.attr('checkstate', 'false');
            })
        }
        else
        {
            $self.prop('checked', true);
            $self.attr('checkstate', 'true');
            $("input[type='radio'].myClass:not(:checked)").attr('checkstate', 'false');
        }
})

A: Simply replace disabled with checked:
$input.prop("checked", false);

or for this element:
this.checked = false;

However, if you are looking for form element which can be checked and unchecked, maybe input type="checkbox" /> is what you need.

A: $inputs.filter(':checked').prop('checked', false);

A: I think you need checkbox instead of radio button to uncheck the checked :
<input class="checkDisable" type="checkbox" value="Test1" />Test1
<input class="checkDisable" type="checkbox" value="Test2" />Test2
<input class="checkDisable" type="checkbox" value="Test3" />Test3
<input class="checkDisable" type="checkbox" value="Test4" />Test4

(function ($) {
$(document).ready(function () {
 $('input:checkbox.checkDisable').change(function(){
    var $inputs = $('input:checkbox.checkDisable')
    if($(this).is(':checked')){
        $inputs.not(this).prop('disabled',true);
    }else{
        $inputs.prop('disabled',false);
        $(this).prop('checked',false);
    }
 })

});
})(jQuery);

A: The answer of Pablo Araya is good, but ...
$self.prop('checked', true);

is superfluous here. The radio button already has a checked state for every click.


Q: Jquery - клик не на данный элемент вызывает определенный эффект

$('.menu li a').click(function(event) {
  $('.dropdown_menu').css('display','none');
  $(this).next('.dropdown_menu').css('display','block');
});
body{
  font-family: sans-serif;
}
.menu ul{
  list-style:none;
  display:flex;
  flex-direction:row;
}
.menu ul li{
  position:relative;
  margin-right:30px;
}
.dropdown_menu{
    position: absolute;
  bottom:-200px;
  left:0%;
  z-index: 10;
  background: #000;
  display: none;
  width: 200px;
    padding:20px;
}
.dropdown_menu ul{
  display:flex;
  flex-direction:column;
}
.dropdown_menu li a{
  color:#fff;
  line-height:1.8;
}

   Главная

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

   Комнаты

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

   Услуги

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

   Больше

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Как сделать так чтобы при клике на другой элемент вне dropdown автоматически все закрывалось?

A: Не силен в jQuery, но должно помочь

$(document).click(function(e) {
  if ($('.menu').has(e.target).length === 0) {
    $('.dropdown_menu').css('display', 'none');
  }
});
$('.menu li a').click(function(event) {
  $('.dropdown_menu').css('display', 'none');
  $(this).next('.dropdown_menu').css('display', 'block');
});
body {
  font-family: sans-serif;
}

.menu ul {
  list-style: none;
  display: flex;
  flex-direction: row;
}

.menu ul li {
  position: relative;
  margin-right: 30px;
}

.dropdown_menu {
  position: absolute;
  bottom: -200px;
  left: 0%;
  z-index: 10;
  background: #000;
  display: none;
  width: 200px;
  padding: 20px;
}

.dropdown_menu ul {
  display: flex;
  flex-direction: column;
}

.dropdown_menu li a {
  color: #fff;
  line-height: 1.8;
}

      Главная

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

      Комнаты

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

      Услуги

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

      Больше

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

A: добавьте
$(document).click(function(){
    $('.dropdown_menu').css('display','none');
})

и тут кое что
$('.menu li a').click(function(event) {
    $('.dropdown_menu').css('display','none');
    $(this).next('.dropdown_menu').css('display','block');
    event.stopPropagation();
});

$('.dropdown_menu li a').click(function(event){
    event.stopPropagation();
})


Q: Windows Phone 8 & Internet Explorer 10 caches 302 redirects We are developing a web app for mobile devices and we are experiencing a rare caching issue in Windows Phone 8 & Internet Explorer 10.
Our app is based on JSF and jQueryMobile. And we are using de "redirect-after-post" system for navigation.
When we make a call to a new page two requests should be executed and so they are in all the  OS an navigators except in our beloved Microsoft system (WP8 & IE10, Nokia Lumia 620):

*

*Navigator requests URL

*Server returns HTTP 302 status with new location

*Navigator requests new location

The fact is that WP8 & IE10 doesn`t execute the last request, and shows a cached result. We are including the "Cache-control", "Pragma" and "Expires" headers in the 302 response to make the navigator not to show a cached page, but IE10 ignores them.
Any clue to solve this problem?
thanks & regards

A: Try forcing the Uri returned in step 2 to be unique (append a random or incrementing value to the end of the query string).
This works around the caching behaviour in the HttpWebRequest class in the SDK.


Q: Заполнить переменные через foreach Есть 4 переменных и список. Нужно пробежаться по списку (он может содержать от 2 до 3 значений) и заполнить ими переменные.
foo1 = "";
foo2 = "";
foo3 = "";
foo4 = "";

foreach (string el in al_ready)
    {
    }

Как это сделать?
A: Единственное, что приходит на ум:
try
{
    foo1 = al_ready[1];
}
catch(Exception e)
{
    foo1="Пусто :)";
}

try
{
    foo2=al_ready[2];
}
catch(Exception e)
{
    foo2="Пусто :)";
}
//и так далее

На изящность решения не претендую)))


Q: how do I link my src/app.js file to babel src/app.js file keeps showing it doesn't exist in git bash
I tried adding quotations
babel src/app.js --out-file=public/scripts/app.js --presets="env,react"
instead of this
babel src/app.js --out-file=public/scripts/app.js --presets=env,react but it still did not work

A: Consider looking at the .gitignor file, please. if you put src folder or src/app in .gitignor then it's not shown in git bash


Q: connect is unsuccessful in my socket programming function in C I have a function which initiates the socket connection. I am trying to a server with a name let's say xp. Socket() is working fine. But when it comes to connect, I am getting an error. I tried to get the IP of that server, I got some random IP. I passed the parameters to the connect API. I print the results of these in a log file. I think error lies within the connect(). I am working on Linux Ubuntu. Here is my program for SocketInit(). I can't get the error with that.
I call the SocketInit function as
    SocketInit(argv[2]); argv[2] has my server name.
short SocketInit(char *xp)
{
      if ( (local_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
        printf("socket creation is unsuccessful check in SocketInit() \n");
        sprintf(log_msg, "create socket descriptor error = %d", errno);
        LogMsg('E', log_msg);
        return(-1);
      }
      else
      {
        printf("socket connection is success\n");
      }

      pos_socket.sin_family = AF_INET;
      pos_socket.sin_port   = htons(port_no);
      pos_socket.sin_addr.s_addr = inet_addr(xp);

      if ( connect( local_socket, (struct sockaddr *) &pos_socket, sizeof(pos_socket) ) < 0 ) {
        sprintf(log_msg, "connect on socket error=%d", errno);
        printf("socket connect api is unsuccessful check in SocketInit() \n");
        LogMsg('E', log_msg);
        return(-1);
      }
      else{
        printf("connect is successful\n");
        return 0;
      }

}

How can I connect to the server. How can I pass the address to the pos_socket.sin_addr.s_addr ? Sometimes I get connect error 110 and 111. But still I can't connect.

A: Use perror() to print the human-readable error string when connect() or most other unix-like system calls return an error.  But since you told us the value of errno, I looked in errno.h for the meaning, and found:
#define ETIMEDOUT   110 /* Connection timed out */
#define ECONNREFUSED    111 /* Connection refused */

(BTW, you cannot count on errno's being the same from one unix to another which is why you need to use these defines when checking for specific errors.  Never hard-code numeric errno values into your code.  It worked out for me this time, but it won't necessarily every time).
ECONNREFUSED means that there was a machine listening at the specified IP address, but that no process was listening for connections on the specified port number.  Either the remote process is not running, it is not binding or accepting connection properly, or it potentially could be blocked by some sort of firewall.
In any case, this points to a problem with the server.
So, check to make sure your remote process is actually ready to accept the connection.  You can use telnet or netcat as a test client to see if other client programs that are known to work are able to connect to your server.
Also, I notice that your variable port_no is not declared, so we have no way of knowing what port you are trying to connect to.. but make sure that this variable is of the correct type and has the correct value for the service you are trying to connect to.  If port_no doesn't specify the correct port you will get the same type of error.


Q: A program written in Go opens many connections to mongoDB I have a very simple HTP server written in Go which serves my AngularJS front end data from a mongodb instance through an API.
Here is the code:
// ReceiveData - used to handle incoming data
func ReceiveData(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.NotFound(w, r)
        return
    }

    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        panic(err)
    }

    // database
    session, err := mgo.Dial("localhost")
    if err != nil {
        panic(err)
    } else {
        fmt.Println("session created")
        database := session.DB("schedule_calculator")
        collection := database.C("schedule_save")
        num, err := collection.Count()
        if err == nil {
            fmt.Println("schedule_save collection count = ", num)
            mongodbData := SavedData{ID: bson.NewObjectId(), Data: string(body), Date: time.Now()}
            collection.Insert(mongodbData)
            num, _ := collection.Count()
            fmt.Println("new count: ", num)
        } else {
            fmt.Println("schedule_save error - ", err)
        }
    }

    if err := json.NewEncoder(w).Encode("todos"); err != nil {
        panic(err)
    }
}

type SavedData struct {
    ID   bson.ObjectId `bson:"_id"`
    Data string
    Date time.Time
}

// SendData - Called by UI to get saved data
func SendData(w http.ResponseWriter, r *http.Request) {
    fmt.Println("SendData function")
    session, err := mgo.Dial("localhost")
    defer closeSession(session)
    if err != nil {
        panic(err)
    } else {
        fmt.Println("session created")
        database := session.DB("schedule_calculator")
        collection := database.C("schedule_save")
        num, err := collection.Count()
        if err == nil {
            fmt.Println("schedule_save collection count = ", num)

            var myData SavedData
            dbSize, err2 := collection.Count()
            if err2 != nil {
                panic(err2)
            }

            if dbSize > 0 {
                // db not empty
                err2 = collection.Find(nil).Skip(dbSize - 1).One(&myData)
                if err2 != nil {
          // TODO: handle error
                    panic(err2)
                }

                // fmt.Println(myData.Data)

                w.Header().Set("Content-Type", "application/json; charset=UTF-8")
                w.WriteHeader(http.StatusOK)

                if err := json.NewEncoder(w).Encode(myData.Data); err != nil {
          // TODO: handle error
                    panic(err)
                }
            } else {
                // db empty
        fmt.Println("DB is empty")
            }

        } else {
            fmt.Println("schedule_save error - ", err)
        }
    }
}

// closes the mongodb session
// TODO: make it use only 1 session
func closeSession(session *mgo.Session) {
    session.Close()
    fmt.Println("session closed")
}

and this is what I get in the console after some short interaction with the API:
2016-08-10T19:22:59.734+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55401 #60 (6 connections now open)
2016-08-10T19:22:59.740+0300 I NETWORK  [conn60] end connection 127.0.0.1:55401 (5 connections now open)
2016-08-10T19:23:58.794+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55405 #61 (6 connections now open)
2016-08-10T19:23:58.800+0300 I NETWORK  [conn61] end connection 127.0.0.1:55405 (5 connections now open)
2016-08-10T19:24:24.219+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55411 #62 (6 connections now open)
2016-08-10T19:24:24.225+0300 I NETWORK  [conn62] end connection 127.0.0.1:55411 (5 connections now open)
2016-08-10T19:25:56.149+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55434 #63 (6 connections now open)
2016-08-10T19:25:56.155+0300 I NETWORK  [conn63] end connection 127.0.0.1:55434 (5 connections now open)
2016-08-10T19:33:54.127+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55460 #64 (6 connections now open)
2016-08-10T19:33:54.133+0300 I NETWORK  [conn64] end connection 127.0.0.1:55460 (5 connections now open)
2016-08-10T19:35:12.060+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55476 #65 (6 connections now open)
2016-08-10T19:35:12.066+0300 I NETWORK  [conn65] end connection 127.0.0.1:55476 (5 connections now open)
2016-08-10T19:35:22.827+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55477 #66 (6 connections now open)
2016-08-10T19:35:22.833+0300 I NETWORK  [conn66] end connection 127.0.0.1:55477 (5 connections now open)
2016-08-10T19:35:37.720+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55478 #67 (6 connections now open)
2016-08-10T19:35:52.725+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55487 #68 (7 connections now open)
2016-08-10T19:36:20.498+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55488 #69 (8 connections now open)
2016-08-10T19:36:20.508+0300 I NETWORK  [conn69] end connection 127.0.0.1:55488 (7 connections now open)
2016-08-10T19:36:33.100+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55490 #70 (8 connections now open)
2016-08-10T19:36:37.155+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55492 #71 (9 connections now open)
2016-08-10T19:36:48.105+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55493 #72 (10 connections now open)
2016-08-10T19:36:50.284+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55494 #73 (11 connections now open)
2016-08-10T19:36:52.157+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55495 #74 (12 connections now open)
2016-08-10T19:36:53.328+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55496 #75 (13 connections now open)
2016-08-10T19:37:01.375+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55497 #76 (14 connections now open)
2016-08-10T19:37:05.287+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55498 #77 (15 connections now open)
2016-08-10T19:37:05.827+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55499 #78 (16 connections now open)
2016-08-10T19:37:05.836+0300 I NETWORK  [conn78] end connection 127.0.0.1:55499 (15 connections now open)
2016-08-10T19:37:08.333+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55500 #79 (16 connections now open)
2016-08-10T19:37:16.376+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55521 #80 (17 connections now open)
2016-08-10T19:37:23.323+0300 W NETWORK  [HostnameCanonicalizationWorker] Failed to obtain name info for: [ (192.168.0.102, "nodename nor servname provided, or not known"), (192.168.0.102, "nodename nor servname provided, or not known") ]
2016-08-10T19:40:41.079+0300 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55546 #81 (18 connections now open)
2016-08-10T19:40:41.087+0300 I NETWORK  [conn81] end connection 127.0.0.1:55546 (17 connections now open)

I am very new to Go, so this was the simplest way I managed to make it work however I would really like to know how to limit the opened connections to 1.

A: Missed defer closeSession(session) in ReceiveData


Q: How can I modify all comments in git repository? I have managed a my project using git.
But I must published this repository, so I have to modify all comments and author names of git repo, because I can't publish some comments and author name.
My git repo has 99 commits and is synced remote repository.
There are a lot of committing points in using git rebase -i.
How can I modify comments and author names?

A: You are after git filter-branch. With it you can easily change committer names, author names and commit messages throughout the whole history. But be aware that this changes all SHA1 values, so if someone has cloned that repository and based work off of it, he has to manually rebase all his branches onto the new history.


Q: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3307/db I have seen this error popping up many times. I have searched the web and tried stuff like adding the mysql-connector file to the buildpath, but nothing worked out for me.
This Code works when running with spigot, this is only another Linux user and not spigot.
Im running this Code in a plugin for the JTSServermod for TS3 on a Linux Debian with Java 8.
The full error message is:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3307/db
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at net.mysticsouls.TeamSpeakBot.utils.NameUUIDUtils.connect(NameUUIDUtils.java:31)
    at net.mysticsouls.TeamSpeakBot.utils.Updater.start(Updater.java:11)
    at net.mysticsouls.TeamSpeakBot.TeamSpeakBot.activate(TeamSpeakBot.java:45)
    at de.stefan1200.jts3servermod.JTS3ServerMod.e(Unknown Source)
    at de.stefan1200.jts3servermod.JTS3ServerMod.b(Unknown Source)
    at de.stefan1200.jts3servermod.i.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)

And my Code calling it is:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

public class NameUUIDUtils {

    private static final String host = "localhost";
    private static final String port = "3307";
    private static final String database = "db";
    private static final String username = "username";
    private static final String password = "*********";
    private static Connection connection;

    public static Connection getConnection() {
        return connection;
    }

    public static boolean isConnected() {
        return connection != null;
    }

    public static void connect() {
        if (!isConnected()) {
            try {
                connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username,
                        password);
                System.out.println("[NameUUID] MySQL connected!");
            } catch (SQLException ex) {
                ex.printStackTrace();
                System.out.println("[NameUUID] MySQL failed to connect!");
            }
        }

        if (isConnected()) {
            try {
                PreparedStatement preparedStatement = getConnection().prepareStatement(
                        "CREATE TABLE IF NOT EXISTS CoinSystem (Spielername VARCHAR(100), UUID VARCHAR(100), Coins INT(100), Strafpunkte INT(100))");
                preparedStatement.executeUpdate();
                preparedStatement.close();
                System.out.println("[NameUUID] MySQL Table created!");
            } catch (SQLException ex) {
                System.out.println("[NameUUID] MySQL Table failed to create!");
            }
        }
    }
}

What am i doing wrong.


Q: How to load related objects after saving a junction table record by foreign keys only? I am trying to add a new student and after that, insert data into a junction table called 'AdditionalCourse' with the help of EF Core 3.1.
Whenever I add the junction rows (additional courses) by only using the foreign keys, it doesn't fill in the course property as expected after saving. It does fill in the Student property however.
Can someone figure out what I'm doing wrong?
I can solve this by just adding a 'get' call in between to just receive the freshly updated object, but I believe this is not necessary.
A minimal working prototype below:
Program.cs
static void Main(string[] args)
    {
        using (var context = new SchoolContext())
        {
            Course course = new Course("Spanish");
            context.Add(course);
            context.SaveChanges();
            Course course2 = new Course("French");
            context.Add(course2);
            context.SaveChanges();

            Student student = new Student("Bill");
            context.Add(student);
            context.SaveChanges();

            AdditionalCourse addCourse1 = new AdditionalCourse() { CourseId = course.Id, StudentId = student.Id };
            AdditionalCourse addCourse2 = new AdditionalCourse() { CourseId = course2.Id, StudentId = student.Id };
            student.AdditionalCourses.Add(addCourse1);
            student.AdditionalCourses.Add(addCourse2);

            context.SaveChanges();

            // Debug at this line
            var x = 0;
        }
    }

AdditionalCourse junction table
public class AdditionalCourse
{
    public int CourseId { get; set; }
    public Course Course { get; set; }

    public int StudentId { get; set; }
    public Student Student { get; set; }
}

Student.cs
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<AdditionalCourse> AdditionalCourses { get; set; }

    public Student()
    {
    }

    public Student(string name)
    {
        Name = name;
        AdditionalCourses = new List<AdditionalCourse>();
    }
}

Course.cs
public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Course()
    {
    }

    public Course(string name)
    {
        Name = name;
    }
}

SchoolContext.cs
public class SchoolContext : DbContext
{
    public SchoolContext()
    { }

    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    { }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Data Source=SERVER_NAME;Initial Catalog=DATABASE_NAME;Integrated Security=True;");
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>().ToTable("student");
        modelBuilder.Entity<Course>().ToTable("course");
        modelBuilder.Entity<AdditionalCourse>().ToTable("additional_course");

        modelBuilder.Entity<AdditionalCourse>()
           .HasKey(x => new { x.CourseId, x.StudentId });
        modelBuilder.Entity<AdditionalCourse>()
           .HasOne(x => x.Student)
           .WithMany(x => x.AdditionalCourses)
           .HasForeignKey(x => x.StudentId);
        modelBuilder.Entity<AdditionalCourse>()
            .HasOne(x => x.Course)
            .WithMany()
            .HasForeignKey(x => x.CourseId);
    }
}

A:
Whenever I add the junction rows (additional courses) by only using the foreign keys, it doesn't fill in the course property as expected after saving. It does fill in the Student property however.

By design, EF Core does not automatically load navigation properties. The only exceptions are when lazy loading is enabled and the navigation property getter is called, navigations to owned entities (or in EF Core 5.0+, navigations configured as AutoInclude) only when querying, or (which is the case with your Student property) the referenced object is already loaded (tracked) in the context. The later is called navigation property fixup, and can happen both during the query materialization or later.
Since you are not using lazy loading, the only guaranteed way to get navigation properties populated is to eager/explicit load them after.
For more info, see Loading Related Data section of the EF Core documentation.


Q: How to parse an array to json using ruby on rails I'm trying to parse a hash to json but in the index.json.jbuilder I get empty hash.
what am I doing wrong:
  def self.fake_objects

    fake_objects = {id: 1,
                  title: 'appointment one',
                  description: 'bla bla bla',
                  start_time: '2014-08-19 14:00:00.000000000 Z',
                  end_time: '2014-08-19 14:30:00.000000000 Z'}
  end

events_controller
  def index
    @events = Event.all
    @fake_objects = Event.fake_objects
  end

index.json.jbuilder
(@fake_objects).to_json do |event|
  json.extract! event, :id, :title, :description
  json.start event.start_time
  json.end event.end_time
  json.url event_url(event, format: :html)
end

class Event < ActiveRecord::Base
  def self.fake_objects
    fake_objects = Event.new(id: 1,
                  title: 'appointment one',
                  description: 'bla bla bla',
                  start_time: '2014-08-19 14:00:00.000000000 Z',
                  end_time: '2014-08-19 14:30:00.000000000 Z')
  end
end

A: try something like:
json.events @fake_objects do |json, event|
  json.extract! event, :id, :title, :description
  json.start event.start_time
  json.end event.end_time
  json.url event_url(event, format: :html)
end

but @fake_objects should be defined as [], for single event you could write:
json.event do |json|
  json.extract! @fake_object, :id, :title, :description
  json.start @fake_object.start_time
  json.end @fake_object.end_time
  json.url event_url(@fake_object, format: :html)
end

If you need just array of results (without events: []) write json.array! ..


Q: Develop a chrome extension to count  tags of currently accessed webpage Hey I'm new to javascript and chrome extension developing. I'm trying to develop a chrome extension which use browser action to count the number of  tags in currently active tab of the Google Chrome browser.I can use getElementsByTagName.lenght method to calculate the number of tags and I know that I can use console API to access the DOM of a webpage. But I have no idea how to call that API from my javascript file.Do you guys know anything regarding this ?

A: To get access to the current page DOM you need to write a content script.
1. Specify the content script in manifest.json
"content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"]
    }
  ]

If you need to inject the script sometimes use Programmatic Injection by specifying permissions field:
{
  "name": "My extension",
  ...
  "permissions": [
    "activeTab"
  ],
  ...
}

2.I would prefer the latter in this case.In popup.js add the code:
function printResult(result){
//or You can print the result using innerHTML
console.log(result);

}
chrome.tabs.executeScript(null, { file: 'content.js' },function(result){
   printResult(result);
});

3.In content script u have access to current page/active tab DOM.
var result=document.getElementsByTagName("input").length;


Q: Xcode: How can I slide left/right between UIViews? I want the easiest way to implement a sliding right/left gesture between multiple UIViews like AngryBirds levels as in the below screenshot

A: Your best bet is probably to not use a slide gesture, instead use a UIScrollView with a contentSize.width smaller than its frame.size.width (to show the previous/next pages), with pagingEnabled = YES and clipsToBounds = NO.


Q: Is there any option to block messages of a specific person without blocking him from calling? Is there any option to block messages of a specific person without blocking him from calling in android phones.? also, will sender be able to know that he is blocked on calling/messaging to the phone in which he is being blocked?

A: try this one...SMS Blacklist for Android to block spam


Q: What does this "will" mean?
Holden workers will be hoping for some direction on the company's future when company chairman Mike Devereux fronts the Productivity Commission in Melbourne today. (ABC.net.au)

It seems like be plus present participle is to denote futurity. Then what does will imply? Is it for simple conjecture (epistemic), or is it adding some actualization meaning of the activity when be hoping can’t contain one?

A: The "will" points to "when company chairman Mike Devereux fronts." At that future time, they will be hoping for a certain outcome from the commission meeting.

A: FumbleFingers is correct that, semantically, there's very little--if any--difference between are hoping for and will be hoping for.
It's not be itself that signals the future, it's will be plus the present participle that signals a future progressive action; but with the progressive tenses, there is generally already a future aspect involved (i.e. they are continuous and often project beyond the present).
So yes, in answer to your question, it's phrased as will be hoping because it points to a future action. And it's specifically hoping because of the progressive aspect.
There's a reason for the use of will be hoping rather than are hoping, and that is that the statement is to some degree conditional (i.e. it hinges on Mike Devereux heading the committee) and also, as you've noted, is speculative. The workers' feelings or hopes will be brought about when/after Mike Devereux assumes the lead of the Productivity Commission in other words.
It's speculation about exactly what feelings this change will bring about written by an outsider.
Revised as if the author is speaking for or is one of the workers:

Holden workers are hoping for some direction on the company's future
  as company chairman Mike Devereux fronts the Productivity Commission
  in Melbourne today.

That's a much stronger statement.
Revised entirely in present tense:

Holden workers are hoping for some direction on the company's
  future now that company chairman Mike Devereux is fronting the
  Productivity Commission in Melbourne.


Q: how to find the remainder of division Q=A/B , Q is a real number expressed as a pair of 8 bits:

*

*most significant 8 bits for the integer part

*least significant 8 bits for the fractional part

*the number is unsigned

for example:
0 0 1 0 1 1 0 1 .  0 1 0 1 0 0 0 0
Can you find the remainder of division if you know B, on a paper? how?
I'll give an example:
2/172 :
0000 0010 . 0000 0000 /
1010 1100 . 0000 0000
=0000 0000 . 0001 0010
0000 0000 . 0001 0010 *
1010 1100 . 0000 0000
=0000 0000 . 1100 0001 (should be 2, or at least something greater than 1.5)

A: There are two algorithms: restoring and non-restoring. This is very well described in Division Algorithms and Hardware Implementations by Sherif Galal and Dung Pham. And here is about implementation in VHDL.