text:
Q: Add new line to print column output in python for csv I am fairly new to python and am trying to determine the best way to do this. I have the below code.
import csv
from collections import defaultdict
columns = defaultdict(list)

with open('test.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
    for (k,v) in row.items():
        columns[k].append(v)

print(columns['Created'])
print(columns['Person'])
print(columns['Comment'])

I am running it against the below CSV file output.
Created,UnwantedData,Person,Bogus,Comment
4-15-17,test,Chad,w,There is an update
4-16-17,for,Marlon,x,There is no update
4-17-17,this ,Kevin,y,I have reviewed the files
4-18-17,issue,Dan,z,I hate this place.

I only want to print the Created, Person, and Comment sections, however I am getting the below.
['4-15-17', '4-16-17', '4-17-17', '4-18-17']
['Chad', 'Marlon', 'Kevin', 'Dan']]
['There is an update ', 'There is no update', 'I have reviewed the files ', 'I hate this place. ']

I am trying to get the output to looks something like this by adding a new line between each time the output is printed, like so.
4-15-17
Chad
There is an update

4-16-17
Marlon
There is no update

4-17-17
Kevin
I have reviewed the files

4-18-17
Dan
I hate this place.

Anything would be greatly appreciated

A: May I suggest an alternative approach where you simply create a new list of entries with the dicts are simply filtered to only contain the required keys.
import csv
wanted = ('Created', 'Person', 'Comment')

with open('test.csv') as f:
    rdr = csv.DictReader(f)

    result = []
    for row in rdr:
        result.append({k: v for k, v in row.items() if k in wanted})

for r in result:
    print(r['Created'])
    print(r['Person'])
    print(r['Comment'])
    print('')

If you wish to use your existing code, simply use zip to rejoin the items from each list.
import csv
from collections import defaultdict
columns = defaultdict(list)

with open('test.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        for k, v in row.items():
            columns[k].append(v)

params = [columns['Created'], columns['Person'], columns['Comment']]
for cre, pers, cmt in zip(*params):
    print(cre)
    print(pers)
    print(cmt)
    print('')

A: When you print columns['Created'] you are printing everything stored in the Created column. Instead you simply need to iterate through each item in the column.
import csv
from collections import defaultdict
columns = defaultdict(list)

with open('test.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        for (k, v) in row.items():
            columns[k].append(v)

for i in xrange(len(columns['Created'])):
    print(columns['Created'][i])
    print(columns['Person'][i])
    print(columns['Comment'][i] + "\n")

The "\n" will cause a new line to be printed after the comment section.

A: Can achieve the result in a single iteration. And It will save the time.
import csv
from collections import defaultdict

with open('test.csv') as f:
    reader = csv.DictReader(f)
    for row_dict in reader:
        print "%s\n%s\n\n" % (row_dict['Created'], row_dict["Person"], row_dict['Comment'])


text:
Q: Gatsby and Netlify CMS Image Widget: Is it possible to use an image or a url string? I'm using Gatsby and Netlify CMS for an image upload. I'm using the image widget and when I upload an image to the media library, my Gatsby site works fine. However, if I change the image to a URL string of an existing image, my Gatsby page query breaks:

      Field "featureImage" must not have a selection since type "String" has no
subfields.

I suspect this is obviously because my graphQL query was set up to expect an image file, and I've changed that file to a string in the CMS. Is there a way to make this implementation dynamic? Here's the relevant code:
PAGE QUERY IN TEMPLATE COMPONENT
export const pageQuery = graphql`
  query IndexPageTemplate {
    markdownRemark(frontmatter: { templateKey: { eq: "index-page" } }) {
      frontmatter {
        featureImage {
          childImageSharp {
            fluid(maxWidth: 2048, quality: 100) {
              ...GatsbyImageSharpFluid
            }
          }
        }
        instagram
        twitter
        facebook
        email
      }
    }
  }
`

GATSBY NODE FOR RELATIVE PATH IMAGES
exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions
  fmImagesToRelative(node) // convert image paths for gatsby images

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: `slug`,
      node,
      value,
    })
  }
}

A: There's a lack of details in the answer since it's a very general issue and needs debugging. My 2 cents:

*

*Check the path of the filesystem in your gatsby-node.js: Gatsby needs to know where are those assets stored in your project in order to create the proper GraphQL nodes using its transformers and sharps. For example:
  {
    resolve: `gatsby-source-filesystem`,
    options: {
      name: `uploads`,
      path: `${__dirname}/static/assets/images`
    }
  },

*Check the paths, naming, extensions of everything involved (images, folders, etc).

*Check your media_folder and public_folder folder. They should look like:
  media_folder: static/assets/images
  public_folder: /assets/images

Notice the missing slash in media_folder at the beginning.

*Check the plugin's order. All your filesystem needs to be set above the remark plugins.

*Use gatsby-remark-relative-images-v2 to create relative paths for assets:
  resolve: `gatsby-transformer-remark`,
  options: {
    plugins: [
      // gatsby-remark-relative-images-v2 must
      // go before gatsby-remark-images
      {
        resolve: `gatsby-remark-relative-images-v2`,
      },
      {
        resolve: `gatsby-remark-images`,
        options: {
          maxWidth: 590,
        },
      },
    ],
  },

redpajama_set_name: RedPajamaStackExchange


text:
Q: I am not able to launch an android application from another android application. What to do? I am using on receive() to receive broadcast and launch another application(by intent). Whenever the app(wifimann) receives the broadcast, the other app (called kotkot(written in Kotlin)) doesn't launch from initial app despite the Wi-Fi being connected.
My code is as follows:

*

*MainActivity:
package com.wifi.wifimann;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

}

*ConnectivityReciever.java:
package com.wifi.wifimann;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;

import com.wifi.wifimann.MainActivity;

public class ConnectivityReceiver extends BroadcastReceiver {

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

        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkCapabilities networkAgent = connMgr.getNetworkCapabilities(connMgr.getActiveNetwork());
//        NetworkInfo wifi = networkAgent.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
        if (networkAgent.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
            Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("com.example.kotkot");
            if (launchIntent != null) {
                context.startActivity(launchIntent);//null pointer check in case package name was not found
            }
        }

    }
}

*

*AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wifi.wifimann">
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <receiver android:name=".MyBroadcastReceiver"  android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
            </intent-filter>
        </receiver>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

It also says that MyBroadcastReceiver is unresolved. But my build.gradle has the same pkg name("com.wifi.wifimann") as its application ID.

*

*kotkot:

*

*MainActivity:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.core.content.ContextCompat.startActivity
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.content.Context.CONNECTIVITY_SERVICE
import androidx.core.content.ContextCompat.getSystemService
import android.content.BroadcastReceiver
import android.content.Context
import android.net.NetworkCapabilities
import android.os.Build
import androidx.core.content.ContextCompat.getSystemService

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val welcome_greeting: TextView = findViewById(R.id.welcome_greeting)
        welcome_greeting.setText("kotleenhere!!")
    }
}


text:
Q: SSJS perform data extract Running this script but getting the error : -

{"message":"Error executing perform call.","description":"ExactTarget.OMM.FunctionExecutionException: Error executing perform call.\r\n Error Code: OMM_FUNC_CONTEXT_ERR\r\n - from Jint --> \r\n\r\n --- inner exception 1---\r\n\r\nExactTarget.OMM.InvalidFunctionParameterException: Property: PartnerProperties is an array but value to be set was not an array.\r\n Error Code: OMM_FUNC_CONTEXT_ERR\r\n - from OMMCommon\r\n\r\n\r\n\r\n"}

Script -
<script runat=server>
Platform.Load("Core","1.1.1");
  try {
    var prox = new Script.Util.WSProxy();
var action = "Start";
var props = {CustomerKey: "CFXXXXXXXXXXXXXXXXXXXXXXXX",
             PartnerProperties : {OutputFilename: "Testing.csv"}
};
var opts = {};
var data = prox.performItem("DataExtractActivity", props, action, opts);

   Write(data);

</script>

<script runat="server">
  } catch(e) {
  Write(Stringify(e));
}
</script>

I am trying to perform the dataextract with the variable filename like FILENAMINGPATTERN - should be variable.

A: Try this:
var prox = new Script.Util.WSProxy();
var action = "start"
var props = {ObjectID: "a9af4db2-d10c-4cd0-8949-232f5b314b43", PartnerProperties: [{"Name": "OutputFileName","Value": "Testing.txt"}]};
var opts = {};
var data = prox.performItem("DataExtractActivity", props, action, opts);

ObjectID can be retrieved via SOAP or if you do an inspect element on the data extract activity in Marketing Cloud. The code performs the extract but ignores the properties set, meaning you can't update the output filename. And when performing an update, this error shows up

{"Status":"Error","RequestID":"2ec6c13b-862d-4782-b532-ab0d87398249","Results":[{"Object":null,"UpdateResults":null,"ParentPropertyName":null,"StatusCode":"Error","StatusMessage":"Cannot perform Update on objects of type DataExtractActivity","OrdinalID":0,"ErrorCode":5,"RequestID":null,"ConversationID":null,"OverallStatusCode":null,"RequestType":"Synchronous","ResultType":null,"ResultDetailXML":null}]}


text:
Q: Recursively add ArrayList data into JTable I know this is beginner's question but it doesn't work. Here's the code
public void imageshow( String path ) throws IOException {
    File root = new File( path );
    File[] list = root.listFiles();
    if (list == null) return;

    for ( File f : list ) {
       imageshow(f.getAbsolutePath());

         if(f.getName().endsWith("jpg")||f.getName().endsWith("png")||f.getName().endsWith("gif")||f.getName().endsWith("tif"))
                {
                images=new ArrayList<String>();
                DefaultTableModel model=new DefaultTableModel();
   model.addColumn("Imya");

   table.setModel(model);
                model.addRow(new Vector(images));
                images.add(f.getName());
                image_count++;
                for(String img:images)
                {
                    System.out.println(img);
                }
            }
        }
    }

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    DirectoryReader fw = new DirectoryReader();
    System.out.println("---Images----");

    try {
        fw.imageshow("D:\\Installs\\shohruh\\doc");
    } catch (IOException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    }
 }

So , I want when the button is clicked it should recursively add to my JTable. Which details was I missed? Logically, I wrote a code correctly. But I doesn't displayed on JTable! Please help to fix this problem. Thanks in advance

A: sample code for you.
String[] usernames = new String[]{"dev","root","developer","lastroot"};

            Collections.reverse(Arrays.asList(usernames));
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(usernames));

snaps before using
Collections.reverse(Arrays.asList(usernames));

-- snaps After using
 Collections.reverse(Arrays.asList(usernames));

Hope it may work for you.

A: Maybe because of initializing ArrayList in each loop:
images=new ArrayList<String>();

When you want to use recursive alogrithm, you should put this outside the recursive method (as instance variable or something).
Then, there is statement:
model.addRow(new Vector(images));

but images list is still empty
EDIT

private DefaultTableModel model=new DefaultTableModel();
private ArrayList<ArrayList<String>> image=new ArrayList<ArrayList<String>>();
public void imageshow( String path ) throws IOException {
File root = new File( path );
File[] list = root.listFiles();

if (list == null) return;

for ( File f : list ) {
   imageshow(f.getAbsolutePath());

     if(f.getName().endsWith("jpg")||f.getName().endsWith("png")||f.getName().endsWith("gif")||f.getName().endsWith("tif"))
            {
            ArrayList<String> row = new ArrayList<String>();
            row.add(f.getName());
            images.add(row);
            image_count++;
        }
    }
}

And when you are calling:
model.addColumn("Imya");
table.setModel(model);
for(ArrayList<String> list:images)
     model.addRow(new Vector(list));

Not tested
EDIT - whole code:

private DefaultTableModel model=new DefaultTableModel();
private ArrayList<ArrayList<String>> image=new ArrayList<ArrayList<String>>();
public void imageshow( String path ) throws IOException {
    File root = new File( path );
    File[] list = root.listFiles();
    if (list == null) return;
    for ( File f : list ) {
        imageshow(f.getAbsolutePath());
        if(f.getName().endsWith("jpg")||f.getName().endsWith("png")||f.getName().endsWith("gif")||f.getName().endsWith("tif"))
            {
            ArrayList<String> row = new ArrayList<String>();
            row.add(f.getName());
            images.add(row);
            image_count++;
        }
    }
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
    DirectoryReader fw = new DirectoryReader();
    images.clear();
    System.out.println("---Images----");
    try {
         fw.imageshow("D:\\Installs\\shohruh\\doc");
    } catch (IOException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    }
    model.addColumn("Imya");
    table.setModel(model);
    for(ArrayList<String> list:images)
         model.addRow(new Vector(list));
}

Not well formated and not tested, written by JavaDoc


text:
Q: Linq orderby two-column sort with custom comparer List<MyObject> objects = (from a in alist
    join b in blist on a.ID equals b.ID
    where a.Number != 4
    orderby b.Rank, a.CustomField
    select a).ToList();

This is my query and I want to use a custom Comparer for the CustomField property. Is there a way to do that in a two-field orderby?
I am able to do this:
List<MyObject> objects = objects.OrderBy(a => a.CustomField, new MyComparer<object>())

but I need it to be sorted by both s.Rank and a.CustomField.

A: Use OrderBy() in conjunction with ThenBy() with your custom comparers.
// I'm pretty sure it is not possible to specify
// your custom comparer within a query expression
List<MyObject> objects = (from a in alist
                          join b in blist on a.ID equals b.ID
                          where a.Number != 4
                          select new { a, b })
                         .OrderBy(o => o.b.Rank, new MyRankComparer())
                         .ThenBy(o => o.a.CustomField, new MyComparer<object>())
                         .Select(o => o.a)
                         .ToList();

A: Try this:
List<MyObject> objects = objects
    .OrderBy(a => a.Rank)
    .ThenBy(a =>
        a.CustomField, new MyComparer<object>()
    ).ToList();

It first sorts by Rank field and then by CustomField with your custom comparer.


text:
Q: Scraping large and complex PDF tables I've been trying to scrape some data off of PDFs regarding 2020 election results in California for my own morbid curiosity.
I need to scrape many tables that appear across many pages.  In some cases, the rows will continue onto the next page, and additional columns will appear on other pages as well.  I've included a link to one example.  I'm comfortable with R, but I can also use Python if that will be better for scraping.  I haven't found many resources indicating how to deal with tables that carry onto additional pages for either language though. I need to get these tables into a CSV or XLSX format.
Thank you in advance!
In this example, Pages 15-28 should be one table.
https://www.co.tehama.ca.us/images/images/Elections/StatementOfVotesCastNOV2020v2excel.pdf

A: I was able to get the entire table using the following procedure.

*

*Open the pdf in MS Word - not Adobe Acrobat.  Word will convert the
document.

*After the conversion has completed, select all. (Both may
take some time.)

*Paste into a blank Excel worksheet. Save and enjoy.


text:
Q: insert string that match regular expression My program takes a string input from a user. If the input string matches the regular expression then it should be inserted into the arrayList.
I wrote that following. But, it does not work:
        if( element.matches("[a-zA-Z]"));
        {
        set.add(element);
        }

A: If that's actually how your code is written then the element will always be added to the set. You need to remove the ; at the end of the first line for the conditional to work:
if (element.matches("[a-zA-Z]")) {
    set.add(element);
}

If you're trying to match more than more character you likely want "[a-zA-Z]+" for the expression.

A: I guess you forgot the + sign, meaning "once or more":
if (element.matches("[a-zA-Z]+")) {..}

(and of course, as the example above shows, you have to get rid of the semicolon)


text:
Q: How to resize a scene size in Xcode? I want to autoscale the size of my scene because in my GameScene.sks I can choose a few iPhone models for the scene size only (iPhone 4s, iPhone SE, iPhone 6s and iPhone 6 Plus). So I try to autoscale to support all models automatically.
This is the code in my SKScene:
class GameScene: SKScene {

override init(size: CGSize) {

    super.init(size: size)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
.......

The syntax seems to be correct but when I switch into the GameScene in the simulator the app will crash. I'm a beginner, so it could be that the override init function is used wrong.

A: import SpriteKit

class GameScene: SKScene {
    let backgroundNode = SKSpriteNode()

    override func didMove(to view: SKView) {
        backgroundNode.size = CGSize(width: displaySize.width, height: displaySize.height)
        backgroundNode.color = .red
        self.addChild(backgroundNode)
    }
}

A: I suggest that you set the scaleMode in the GameViewController within the viewDidLoad() method instead of setting each sizes manually. You can set scaleMode to aspectFill/ aspectFit/ resizeFill, etc.. Here is a sample code.
class GameViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    let scene =
      GameScene(size: view.bounds.size)
    let skView = self.view as! SKView
    scene.scaleMode = .aspectFill
    skView.presentScene(scene)
  }

Here is the document Scaling a Scene's Content to Fit the View.
https://developer.apple.com/documentation/spritekit/skscene/scaling_a_scene_s_content_to_fit_the_view


text:
Q: How to get full path of selected file on change of  using django compress.html
 <form action="/compress" method="POST"  enctype="multipart/form-data">
            {% csrf_token %}
            Select pdf :
            <input type="file" name="pdf1" id ="pdf1" accept="pdf/*" />

            <button type="submit" class="btn btn-dark mt-2"  value="click">
             submit
            </button>

views.py
  def mergepdf(request):
    from pylovepdf.ilovepdf import ILovePdf
    ilovepdf = ILovePdf('my_secrete_key', verify_ssl=True)
    task = ilovepdf.new_task('compress')
    task.request.FILES['full_path']# here i want full path of selected file
    task.set_output_folder('/Downloads/download_pdffile')
    task.execute()
    task.download()
    task.delete_current_task()

The filePath var contains the only name of selected file, not the full path.
I searched it on the net, but it seems that for security reasons browsers (FF, chrome) just give the name of the file.
Is there any other way to get the full path of the selected file?


text:
Q: How to delete text inserted after a bookmark so i can insert new text I have set up a few bookmarks and when a button is pressed runs a macro to insert dates at the bookmarks, This works great. if i press the button again new dates are inserted before the existing dates.
I want to know what code to use to remove the old dates and add new dates.
I did find some code that lists all my bookmarks.
Dim d As Document
'Set d = Documents.Add("G:\My Drive\Moss\CRM\Work in progress\action plan
\Wordchange.docm")
Set d = ActiveDocument

Dim b As Bookmark

Dim dt As Date
'dt = DateAdd("d", 21, DateTime.Now)
dt = DateAdd("d", 90, Date)
Set b = d.Bookmarks("weeksadd3m")
b.Range.Text = Format(dt, "dd/mm/yyyy")

I would like to clear text after bookmark so fresh dates can be inserted.
Thanks to all that will consider this.
moss

A: The bookmark must be set to cover the range of its new content. Try code like this:-
Private Sub SetBookMark()

    Dim Doc As Document
    Dim Rng As Range
    Dim Mark As String
    Dim Dt As Date

    'Set Doc = Documents.Add("G:\My Drive\Moss\CRM\Work in progress\" & _
                             "action plan\Wordchange.docm")
    Set Doc = ActiveDocument
    Mark = "weeksadd3m"
    Dt = DateAdd("m", 3, Date)

    With Doc.Bookmarks
        If .Exists(Mark) Then
            Set Rng = .Item(Mark).Range
            Rng.Text = Format(Dt, "dd/mm/yyyy")
            .Add Mark, Rng
        End If
    End With
End Sub


text:
Q: Passing a form-variable into the onsubmit field? I am trying to verify the contents of a form before sending it. Basically, I'm trying to work with the numbers in the form and ensure they are within the correct range. The problem is that the JavaScript I have which is trying to verify it thinks that the item being passed to it is NaN (I have been parsing it).
A little work revealed that the variable ("size") is referring to an "HTMLInputEleMent", which I guess is, indeed, NaN (although I am not quite sure what it actually is).  I think that the problem is that the onSubmit is not passing what I want it to be passing, even though I named the field "size" and I passed onSubmit "size" too.
I tried putting it in quotation marks, but that just turns it into a string...
I am wondering if perhaps you are unable to pass a variable from WITHIN the form to it's onSubmit field? Is that so? If so, how should I do this?
Here is the form:
        <form onsubmit="return goodForm(size, day, month, year)" action="http://localhost:8080/pomper_servlet/CostCalc" method="GET">
            The day of the month must be entered as a number (ex: 1,22)
            <input type="text" name="day">

            The month of the year must be entered as a number (ex: Jan.=1, etc.)
            <input type="text" name="month">

            The year must be entered as a 4 digit number (ex: 2008, 2017)
            <input type="text" name="year">

            Please Choose a tour-length, in accordance with the chart below:
            <input type="TEXT" name="length">

            How many people will be in your group? (No More than 10 allowed!)
            <input type="text" name="size">

            Please select a tour:

            <input type="RADIO" name="tour" value="Gardiner Lake">
            Gardiner Lake

            <input type="RADIO" name="tour" value="Hellroaring Plateau">
            Hellroaring Plateau

            <input type="RADIO" name="tour" value="The Beaten Path">
            The Beaten Path

            <input type="SUBMIT" value="Submit">
        </form>

And here is the function, from functions.js:
function goodForm(gSize, day, month, year) {
"use strict";
window.alert("goodFrame(): "+gSize);
var groupSize1 = parseInt( gSize.replace(/^"|"$/g, ""), 10);
window.alert("goodFrame(): "+groupSize1);
var sizeInt = parseInt(groupSize1);
if(groupSize(sizeInt) && goodDate(day, month, year)){
    window.alert("true");
    return true;
}
else{
    window.alert("false")
    return false;
}

There are references to other functions in there, but they aren't relevant to this, I think. The alerts were/are for debugging purposes...
Thanks in advance!

A: Is something like this what you mean?
JavaScript:
 document.getElementById("myForm").onsubmit = function() {
     alert(document.getElementById("size").value);
 }

HTML:
<form name="myForm" id="myForm">
    <input type="text" name="size" id="size">
    <input type="submit">
</form>

Elaboration:
The onsubmit function is attached to an item whose id is "myForm" specified in the HTML as id="myForm".  You can lookup the item with this ID using the method getElementById on the document.  Careful not to do getElementByID (Id vs ID).  When you submit the form, this method will get called and you'll be on your way.
Then you can lookup items on the page to get their value the same way you looked up the form.  Just give them an ID like id="size" and you can look it up.
You can also do something like:
alert(document.myForm.size.value);

or
alert(document.forms["myForm"].size.value);

...but I've stayed away from that method since, a while ago at least, some browsers hated it. Maybe it's better and more performant now, I'm not sure.

A: You can try giving each one of the Inputs (day, month, year, size) to id (you can use the same value as your name attribute).
Get the value by id within your goodForm() function.
<input type="text" name="day" id="day"> <-- set
document.getElementById("some id").value <-- get

A: First, doing inline validation like this (via onsubmit) is bad form.  Usually you will want to do event binding, I'm going to include sample code using jQuery, but you can use other methods as well.
First, give your form a unique ID attribute for the page.  I'm assuming <form id="MyForm"...
Next, you will likely want your validation method to "know" about the fields it needs.
//this function is executed when the page's dom is loaded
// assumes jQuery is loaded already
$(function(){

    //binds the myFormOnSubmit method below to run as part of your form's onsubmit method
    $('#MyForm').submit(myFormOnSubmit);

    //runs when the form is trying to submit
    function myFormOnSubmit(event) {
        var f = $(this);

        // note, you have to match on attribute selectors
        //  you may want to give each of these fields an id=".." attribute as well to select against #IdName
        var size = f.find('[name=size]').val();
        var day = f.find('[name=day]').val();
        var month = f.find('[name=month]').val();
        var year = f.find('[name=year]').val();
        var tour = f.find('[name=tour]:checked').val(); //selected radio button's

        var isValid = validDate(year,month,day) && validSize(gSize) && validTour(tour);

        if (!isValid) {
            event.preventDefault(); //stop submit
        }
    }

    function validTour(tour) {
        return !!tour; //will be false if it's an empty string, ex: no selected value
    }

    function validSize(size) {
        var s = parseInt(size); //get integer value for size

        if (s <= 0 || s > 10) return false; //not in range
        if (s.toString() !== size) return false; //doesn't match input, invalid input
        return true; //true
    }

    function validDate(year, month, day) {
        //coerce the values passed into numbers
        var y = +year, m = +month, d = +day;

        //convert to an actual date object
        var dtm = new Date(y, --m, d);

        //compare the values
        if (!dtm) return false; //invalid input
        if (dtm.getFullYear().toString() !== year.toString()) return false; //year doesn't match input
        if ((dtm.getMonth() + 1).toString() !== month.toString()) return false; //month doesn't match input
        if (dtm.getDate().toString() !== day.toString()) return false; //day doesn't match input

        var now = new Date(); console.log(now);
        var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

        //entered date is before today, invalid
        if (dtm &lt= today) return false;

        //passed checks
        return true;
    }
});

A: In case you don't want to use JQuery:
You don't need to pass the parameters, try giving them an id and get them by their id inside the good form function.
function goodForm() {
    var size = document.getElementById("size");
    if(null != size){
       // do something with size.value
    }

}


text:
Q: PHP On error? browser downloads empty file I have a laravel/php script that runs the exec command:
$result = exec($command, $output);
return json_encode($output);

I know exec is dangerous (this is for testing).  When I load the page in a browser, the command takes a while and eventually the browser downloads and empty file:

If I comment out the exec command, the page outputs and empty array just fine.
When I use fiddler to see the response I get the following:
HTTP/1.1 200 OK
Date: Thu, 31 Dec 2015 20:08:53 GMT
Server: Apache/2.2.22 (Win32) mod_ssl/2.2.22 OpenSSL/0.9.8x
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/x-httpd-php
Content-Length: 0

This happens in Chrome and IE.


text:
Q: Once we have signaled a condition variable, will we keep on executing original thread? I have a problem below.
Process A                             Process B
int A = 0;                            int B = 0;
pthread_mutex_lock(&mutex);
while (condition == FALSE)
  pthread_cond_wait(&cond, &mutex);
                                    pthread_mutex_lock(&mutex);
                                    condition = TRUE;
                                    pthread_cond_signal(&cond);
                                    pthread_mutex_unlock((&mutex)
   A += 10;                         B += 10;

My problem is, if process B has other instructions, ex: int B += 10;,
B will execute B += 10 immediately or A will take control otherwise?
It is, whether process B will continue executing or A will be wake up & take control?
For example, will B += 10 precede A += 10 or vise versa?

A: Every condition variable is associated with a mutex. The mutex must be held when pthread_cond_wait is called; pthread_cond_wait releases the mutex, waits for the condition to be signalled, and then reacquires the mutext before returning.
You may call pthread_cond_signal with the mutex held, or after releasing the mutex. If it is called with the mutex held, no pthread_cond_wait can continue until the mutex is released.
The example code in the question does not release the mutex before executing B += 10; [Note 1], so that will definitely execute before A += 10;. The mutex must at some point be released, of course.
Once the mutex is released, both threads execute in an unspecified order. If your computer has more than one core (quite common these days), they might both be executing at the same time.

Note:

*

*int B += 10; is invalid. You can't declare a variable and increment it in one statement (where would the variable be initialized?)

A: It is an undefined behaviour. As you haven't synchronized access, you can't be sure which one is the first. Though in real life it depends upon OS implementation of pthread_cond_signal, you shouldn't rely on it.

A: Your code is incomplete because process B never unlocks the mutex.
When process A executes pthread_cond_wait it atomically unlocks the mutex and waits for the signal from process B. When process B calls pthread_cond_signal, process A will attempt to lock the mutex again. Since B never unlocks the mutex, A will be stuck trying to acquire the mutex.
Hence, only the B += 10 statement will run. The A += 10 will run if and only if process B unlocks the mutex.


text:
Q: Strategies for dealing with Circular references caused by JPA relationships? I am trying to partition my application into modules by features packaged into separate jars such as feature-a.jar, feature-b.jar, ... etc.
Individual feature jars such as feature-a.jar should contain all the code for a feature a including jpa entities, business logic, rest apis, unit tests, integration test ... etc.
The problem I am running into is that bi-directional relationships between JPA entities cause circular references between the jar files. For example Customer entity should be in customer.jar and the Order should be in order.jar but Customer references order and order references customer making it hard to split them into separate jars / eclipse projects.
Options I see for dealing with the circular dependencies in JPA entities:

*

*Option 1: Put all the entities into one jar / one project

*Option 2: Don't map certain bi-directianl relationships to avoid circular dependencies across projects.

Questions:

*

*What rules / principles have you used to decide when to do bi-directional mapping vs. not?

*Have you been able to break jpa entities into their own projects / jar by features if so how did you avoid the circular dependencies issues?

A: There is no rules have you used to decide for Circular reference in JPA. I also have to test it.
In my example, there is an entity Category Which have OneToOne to parentCategory and OneToMany to childCategories as bidirectional.
I think, the Circular Reference  like below data structure.
CategoryID      Name    ParentID
001             AAA     002
002             BBB     003
003             CCC     004
004             DDD     001

I would like to suggest which is to avoid problematically.
Example :
public void addNewCategory(Category category) {
    checkCircularity(Category category, category.getParent());
}

public static void checkCircularity(Category child, Cagegory parent) throws CircularReferenceException {
    if (superior != null) {
        if (sub.isEqual(superior) || sub.isEqual(parent.getParent())) {
            throw new CircularReferenceException("Circularity Referencing.........");
        } else if (finder.getSuper(superior) != null) {
            checkCircularity(child, parent.getParent());
        }
    }
}

If the program does not throw CircularReferenceException, there is no circular reference for that Category instance.


text:
Q: How to add a login password when start/launching Ubuntu? When I installed Ubuntu, I did not add a password since I am using only of movies and music.
Now I am using it for other purpose as well.
So when I launch Ubuntu, it does not ask login password.
I want to add a password. I tried system>preference>about me and system>passwords and encryption keys but none of them ask me password when I start Ubuntu.
Could anyone tell me how to add a password to login?
Thanks in advance.

A: The place you want is:

System -> Administration -> Login Screen

Make sure it is set to "Show the screen for choosing who will log in" and then save it and reboot.
When the computer starts up you should be presented with a list of users on the system (if Show list of users was checked) or a box to enter your login name.  You will then need to enter your password (the one you use for administrative tasks) to get any further.
If you managed to create your user account without a password (not sure if this is actually possible), then adding a password to your account can be done number of ways.
The simplest way is just to open a Terminal window (Applications -> Accessories -> Terminal) and typing passwd at the prompt.  If you already have a password set it will ask for that before allowing you to change your password.

A: You're looking for this:
System->Administration->Users and Groups.  It should be pretty easy to find from there.


text:
Q: Are there examples of "loss-less" Forster Resonance Energy Transfer (FRET)? When I think of a Forster Resonance Energy Transfer (FRET) process, I typically imagine the initial excitation of an absorbing chromophore with a photon followed by the subsequent emission of a lower frequency photon from a secondary emitting chromophore, where this process occurs as a result of dipole-dipole coupling between electronic states of the two chromophores allowing for an InterSystem Crossing (ISC) event.
However, isn't this just because Kasha's rule (http://en.wikipedia.org/wiki/Kasha's_rule) or some variant of this rule, tells us that ISC events are most likely to occur from the lowest excited eigenstate of the initially excited chromophore, where we shed energy non-radiatively to get to this state?
Can't we use a laser and a band-pass filter to directly excite to absorbing chromophore to the lower regime of the first excited singlet state where ISC can occur with high probability (provided the right chromophore system)?  Are there examples of "loss-less" FRET energy transfer where the excitation and emission wavelengths are identical or near-identical (e.g. where the wavelengths are less than a nanometer apart)?


text:
Q: why dict(dict) get the same dict? It might sounds stupid. When I override dict in python like:
class idict(dict):
    def __init__ (self, *args, **kwargs):
        self._store = dict(*args, **kwargs)

Then I use
a = {1:2, 2:3}
b=idict(a)
print b._store == a

gives True
I don't know why dict(dict) get the same dict. Does dict in python have any method handle this? I'm not sure if I'm doing it in the right way.
Another question further of this one:
If I know I will get a parent class instance (like dict), I want to add/change method in this instance. I usually create child class from parent class and get child class instance. This seems memory-inefficient, as parent instance is already there.
One way after my search is adding/changing a method in the parent class directly (e.g. parent_class.method = new_method), and then get the instance of parent class. I'm not sure if this is right way in terms of OOP.

A: It's not getting the same dict. It's making a shallow copy of the original dict, and == compares by value, not by identity, so because it has all the same keys and values, it's equal, even though it's not the same dict.
If you tested print b._store is a, you'd get False, because is tests object identity.
As for your other question, I'm not 100% sure what you're going for there, but I think you're objecting to the fact that you aren't benefiting from inheriting from dict, since you still have an attribute storing all your values. That's only because you're not doing inheritance correctly here. You have to delegate up to the parent class's methods, rather than making your own _store attribute, and you'll reuse the storage of the parent. So for example, a correct __init__ here would be:
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs) # On Py2 super(idict, self) needed instead of super()

Now you don't have _store at all, you're initializing the parent class storage  by passing the work up the chain.
Side-note: Technically, the correct __init__ would be:
def __init__(*args, **kwargs):
    if not args:
        raise TypeError("descriptor '__init__' of 'Counter' object "
                        "needs an argument")
    self = args[0]
    if len(args) > 2:
        raise TypeError('expected at most 1 arguments, got %d' % len(args))

    super(idict, self).__init__(*args[1:], **kwargs)

This is a special case that only applies to methods intended to accept arbitrary keywords, where you need to detect and properly respond to the possibility that a caller might pass self=someval without raising exception (e.g. in the case of dict, dict(self="abc") is legal). Python dict subclasses like collections.Counter use this technique.


text:
Q: Microsoft Edge javascript won't add class to button I'm using javascript to create a button with a hamburger icon. It works fine on every browser and OS except for Microsoft Edge on a Windows 10 Home PC.
Here's my code (just assume than any unnamed variables or functions were named earlier in the code):
function isMobile() {
    return window.outerWidth <= config.mobile.breakpointWidth
}

function toggleMobileClass() {
    isMobile() ? addClass(MBody, "mdcre-mobile") : removeClass(MBody, "mdcre-mobile")
}

function getMobileOpenIcon() {
    return 'Open Naviation'
}

function getMobileCloseIcon() {
    return 'Close Navigation'
}

function addMobileNavButton() {
    if (!document.getElementsByClassName("mdcre-nav-button")) {
        var e = document.createElement("button");
        e.classList += "mdcre-nav-button", e.innerHTML = getMobileOpenIcon(), e.addEventListener("click", function() {
            toggleMobileNavVisibility(), toggleMobileNavButtonIcon()
        }), MBody.appendChild(e)
    }
}

function removeMobileNavButton() {
    var e = document.getElementsByClassName("mdcre-nav-button")[0];
    e && e.remove()
}

function toggleMobileNavButton() {
    isMobile() ? addMobileNavButton() : removeMobileNavButton()
}

function toggleMobileNavVisibility() {
    document.getElementById("lightbox-menu").style.display = document.getElementById("lightbox-menu").style.display === 'block' ? 'none' : 'block';

      toggleClass(MHeader, 'show-nav');
      toggleClass(MBody, 'no-scroll');
}

function toggleMobileNavButtonIcon() {
    document.getElementsByClassName("mdcre-nav-button")[0].innerHTML = hasClass(MHeader, "show-nav") ? getMobileCloseIcon() : getMobileOpenIcon()
}

Explanation: When you go below a certain size (decided elsewhere by variable breakpointWidth), a button element is created and it is assigned the class mdcre-nav-button.
On Microsoft Edge, it creates the button element, but doesn't add the class.
I'm pretty sure the issue is with the function "addMobileNavButton", although I can't figure out what is giving Microsoft Edge a hard time.
Other info: I'm only having problems with Microsoft Edge on a Windows 10 Home PC, recently updated. The code in Chrome and Firefox on the same PC work fine. I've tried Microsoft Edge on an iPhone 5c and it also worked fine.

A: += is not the correct way to add a class to a classList. Use the add() method.
function addMobileNavButton() {
    if (!document.getElementsByClassName("mdcre-nav-button")) {
        var e = document.createElement("button");
        e.classList.add("mdcre-nav-button");
        e.innerHTML = getMobileOpenIcon();
        e.addEventListener("click", function() {
            toggleMobileNavVisibility(), toggleMobileNavButtonIcon()
        }), MBody.appendChild(e)
    }
}

You could also use addClass(e, "mdcre-nav-button")


text:
Q: Cannot access a disposed object. Object name: 'System.Net.HttpListener' I am creating a windows service that listens for specific Http requests. I am running an httpListener in a separate task. When the service is stopped i close the listener instance. But it seems that the http listenerContext is waiting for an incoming request and as the listener get closed i get the following error
Cannot access a disposed object. Object name: 'System.Net.HttpListener'.

Even if i use some mechanism to inform StartListening() that listening is stopped, it will not run as the execution at the corresponding thread stuck at HttpListenerContext context = await _listener.GetContextAsync();  until a request arrives.
  public void StartListening() {
         _listener.Start();
         _logger.LogDebug("Http Listening started");

         Task.Run(async () => {
            while (true) {
               try {
                 if (isOpen == false) {
                 return 0;
                   }
                  HttpListenerContext context = await _listener.GetContextAsync();
                  HttpListenerRequest request = context.Request;

                  //processing of the requests url/////
                  var newUri = request.Url.AbsoluteUri;
                  _concurrentUrlQueue.Enqueue(newUri);
                  if (ConcurentUrlQueueChanged != null) ConcurentUrlQueueChanged(this, new EventArgs());
               }
               catch (Exception e) {
                  _logger.LogError("Error at get listening  context, Message: " + e.Message);
               }

            }
         });

      }
      public void StopListening() {
          isOpen = false;
         _logger.LogDebug("Http Listening Stop");
         _listener.Close();

      }

Which is the appropriate way to close an http listener that is listening to get context. The code i use is the following.
Thank you..

A: I found a solution. As i understand the listener.GetContextAsync() is a blocking method, and the execution of my code will only continiou when a new context is detected. I can use the non blocking versions BeginGetContext() and EndGetContext(). When i want to stop execution i use a cancellation token.
   public void StartListening() {

         _listener.Start();
         _logger.LogDebug("Http Listening started");

         Task.Run(() => {
            while(true) {

               if(_cancellationToken.IsCancellationRequested) return ;

               try {
                  NonblockingListener();
               }
               catch (Exception e) {
                  _logger.LogError("Error With the listening Proccess, Message : "+e.Message);
               }

            }
         },_cancellationToken);
      }

      public void StopListening() {

         _cancellationTokenSource.Cancel();
         ListenerCallback(null);

         _logger.LogDebug("Http Listening Stop");
         _listener.Close();
      }

      public void NonblockingListener() {
         IAsyncResult result = _listener.BeginGetContext(ListenerCallback, _listener);
         result.AsyncWaitHandle.WaitOne();
      }

      public void ListenerCallback(IAsyncResult result) {

       if(_cancellationToken.IsCancellationRequested)return;

         _listener = (HttpListener)result.AsyncState;

         HttpListenerContext context = _listener.EndGetContext(result);
         HttpListenerRequest request = context.Request;

         //processing code
         EnqueUrl(request);
      }


text:
Q: Can I keep specific header one page? I m working on auto report and I need to put some specific header on specific page specially after \newpage. How can I control it?
\\newpage
<header 1>
for rest of pages
<header 2>

Regards

A: You can just define the header for the specific page and then for the rest.
An example how to define such a header is given for example at http://en.wikibooks.org/wiki/LaTeX/Page_Layout.
There are also packages for defining fancy headers, for example fancyhdr.


text:
Q: How change value of fields marked with the annotation by the annotation processing How to set the value of the variable and then after the calculation read it using annotation processing? I know how to do this with reflection, but I need to use annotation processing mechanism. Is it possible? Do I have to change something in the annotation?
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Bind {

}

public class Model1 {
@Bind private int LL;
@Bind private  double[] twKI;
@Bind private  double[] twKS;
@Bind private  double[] twINW;
@Bind private  double[] twEKS;
@Bind private  double[] twIMP;
@Bind private double[] KI;
@Bind private double[] KS;
@Bind private double[] INW;
@Bind private double[] EKS;
@Bind private double[] IMP;
@Bind private double[] PKB;

 public Model1() {}

 public void run() {
 PKB = new double[LL];
 PKB[0] = KI[0] + KS[0] + INW[0] + EKS[0] - IMP[0];
 for (int t=1; t < LL; t++) {
  KI[t] = twKI[t]* KI[t-1];
  KS[t] = twKS[t]* KS[t-1];
  INW[t] = twINW[t]* INW[t-1];
  EKS[t] = twEKS[t]* EKS[t-1];
  IMP[t] = twIMP[t]* IMP[t-1];
  PKB[t] = KI[t] + KS[t] + INW[t] + EKS[t] - IMP[t];
  }
 }
}

 /* Part of the code in which I set the values */
 public class Controller{
 ...
 private Class class1;
 private Object modelName;

 class1 = Class.forName("zad1.models."+model);
 modelName = class1.newInstance();
 Field fieldtkWI  = class1.getDeclaredField("twKI");
 fieldtkWI.setAccessible(true);
 fieldtkWI.set(modelName, twKI);
 }

EDIT:
This annotation is to allow:

*

*assigning value to the output variable of the model before performing calculations,

*downloading the values of variables calculated in the model (after calculations have been carried out).


text:
Q: Minecraft server startup with ubuntu automatically? How can I make this command run automatically on every boot and work?
screen -S Minecraft java -Xmx3G -Xms3G -jar minecraft_server.1.19.3.jar nogui
I try cronjob but this not works.


text:
Q: Mongoose model testing require models I have a problem testing my mongoose models
I have a structure like

*

*app

*

*models

*

*Address

*User

*Organization

*test

Both models User and Organization need to know the model Address. My models are structured like:
module.exports = function (mongoose, config) {

    var organizationSchema = new mongoose.Schema({

        name : {
            type : String
        },
        addresses : {
            type : [mongoose.model('Address')]
        }

    });

    var Organization = mongoose.model('Organization', organizationSchema);

    return Organization;
};

In my normal app i require Address before requiring User and Organization and everything is fine. I now wrote tests for User and Organization. In order to have the Address model registered i call require('../models/Address.js') This works fine if i run one test. But if i run all tests in a batch i get an error because i tried to register Address twice.
OverwriteModelError: Cannot overwrite Address model once compiled.
How do i solve this problem?

A: Best solution (IMO):
try {
  mongoose.model('config')
} catch (_) {
  mongoose.model('config', schema)
}

A: The problem is that you cant set mongoose model twice. The easiest way to solve your problem is to take advantage of node.js require function.
Node.js caches all calls to require to prevent your model from initializing twice. But you wrapping your models with functions. Unwrapping them will solve your problem:
var mongoose = require('mongoose');
var config = require('./config');

var organizationSchema = new mongoose.Schema({
    name : {
        type : String
    },
    addresses : {
        type : [mongoose.model('Address')]
    }
});

module.exports = mongoose.model('Organization', organizationSchema);

Alternative solution is to make sure that each model initialized only once. For example, you can initialize all you modules before running your tests:
Address = require('../models/Address.js');
User = require('../models/User.js');
Organization = require('../models/Organization.js');

// run your tests using Address, User and Organization

Or you can add try catch statement to your models to handle this special case:
module.exports = function (mongoose, config) {

    var organizationSchema = new mongoose.Schema({

        name : {
            type : String
        },
        addresses : {
            type : [mongoose.model('Address')]
        }

    });

    try {
        mongoose.model('Organization', organizationSchema);
    } catch (error) {}

    return mongoose.model('Organization');
};

Update: In our project we have /models/index.js file to handle everything. First, it calls mongoose.connect to establish connection. Then it requires every model in models directory and creates a dictionary of it. So, when we need some model (e.g. user) we requires it by calling require('/models').user.

A: This question already has an answer, but for a unique way to accomplish this check out https://github.com/fbeshears/register_models.  This sample project uses a register_models.js that includes all models from an array of file names.  It works really well and you end up with all your models pretty much wherever you need them.  Keep in mind node.js's cache will cache objects in your project while it's running.

A: I use try/catch to tackle this problem and it works ok. But i think this not the best way of doing this.
try{
    var blog = mongoose.model('blog', Article);
} catch (error) {}

A: I fixed this by patching r.js and making sure that all my modules used localRequire calls.
Checkout the thread here
https://github.com/jrburke/requirejs/issues/726


text:
Q: std::shared_ptr: reset() vs. assignment This is a basic question, but I did not find a previous post about it. The title of the following question sounds like it might be the same question as mine, but the question itself does not match the title: is it better to use shared_ptr.reset or operator =?
I am confused about the purpose of the reset() member function of std::shared_ptr: what does it contribute in addition to the assignment operator?
To be concrete, given the definition:
auto p = std::make_shared<int>(1);

*

*Are the following two lines equivalent:
p = std::make_shared<int>(5);
p.reset(new int(5));

*What about these:
p = nullptr;
p.reset();

If the two lines are equivalent in both cases, then what is the purpose of reset()?

EDIT: Let me re-phrase the question to better emphasize its point. The question is: is there a case where reset() lets us achieve something that is not as easily achievable without it?

A: It's possible for reset to avoid a dynamic memory allocation in certain cases. Consider the code
std::shared_ptr<int> p{new int{}};  // 1
p.reset(new int{});                 // 2

On line 1 there are 2 dynamic memory allocations happening, one for the int object and a second one for the shared_ptr's control block that'll keep track of the number of strong/weak references to the managed object.
On line 2 there is again a dynamic memory allocation for a new int object. Within the body of reset the shared_ptr will determine that there are no other strong references to the previously managed int, so it must delete it. Since there aren't any weak references either, it could also deallocate the control block, but in this case it would be prudent for the implementation to reuse the same control block because it would otherwise have to allocate a new one anyway.
The above behavior would not be possible if you always had to use assignment.
std::shared_ptr<int> p{new int{}};    // 1
p = std::shared_ptr<int>{new int{}};  // 2

In this case, the second call to the shared_ptr constructor on line 2 has already allocated a control block, so p will have to deallocate its own existing control block.

A: When using reset() the parameter passed to reset need not be a managed object (nor can it be); whereas with = the right hand side must be a managed object.
So these two lines give you the same end result:
p = std::make_shared<int>(5); // assign to a newly created shared pointer
p.reset(new int(5)); // take control of a newly created pointer

But we cannot do:
p = new int(5); // compiler error no suitable overload
p.reset(std::make_shared<int>(5).get()); // uh oh undefined behavior

Without reset() you would not be able to reassign a shared pointer to a different raw pointer without creating a shared pointer and assigning it. Without = you wouldn't be able to make a shared pointer point to another shared pointer.

A: I won't include the rationale behind your first sub-question of the difference between construction via make_shared or from a pointer, as this difference is highlighted in several different locations, including this excellent question.
However, I think it is constructive to distinguish between using reset and operator=. The former relinquishes ownership of the resource managed by the shared_ptr, either by destroying it if the shared_ptr happened to be the sole owner, or by decrementing the reference count. The latter implies shared ownership with another shared_ptr (unless you're move constructing).
As I mentioned in the comments, it's important that the pointer passed in to reset not be owned by another shared or unique pointer, because it would yield undefined behavior upon the destruction of the two independent managers - they both would attempt to delete the resource.
One use case of reset could be lazy initialization of a shared resource. You only want the shared_ptr to manage some resource, memory for example, if you really need it. Doing an outright allocation, such as:
std::shared_ptr<resource> shared_resource(new resource(/*construct a resource*/));

might be wasteful if its never actually needed. To do this with lazy initialization, something like this may apply:
std::shared_ptr<resource> shared_resource;
void use_resource()
{
       if(!shared_resource)
       {
            shared_resource.reset(new resource(...));
       }

       shared_resource->do_foo();
}

Using reset in this case is more concise than doing a swap or assigning to a temporary shared_ptr.

A: reset() changes the managed object of an existing shared_ptr.

p = std::shared_ptr(new int(5)); and p.reset(new int(5));

The former involves creating a new shared_ptr and moving it into a variable. The latter does not create a new object, it simply changes the underlying pointer in managed by the shared_ptr.
Put another way the two are meant to be used in different cases. Assignment is for when you have a shared_ptr and reset for when you have a raw pointer.
Another thing to keep in mind is that shared_ptr was available in boost before move assignment existed and influenced the latest version heavily. Without move assignment being able to change a shared_ptr without making a copy is beneficial as it saves you the bookkeeping of the extra object.


text:
Q: R naiveBayes classifier predict "subscript out of bounds" I am new to R, and am trying to solve why my predict is out of bounds. the question should be an easy fix as this is more of an introduction.
set my classifier with train data
sms_classifier <- naiveBayes(sms_train, sms_train_labels)

but error occurs when i try to do the predict funtion
sms_test_pred <- predict(sms_classifier, sms_test)

error given
Error in
`[.default`(object$tables[[v]], , nd + islogical[attribs[v]]) : subscript out of bounds

A: Assuming you are trying to build a spam classifier that requires documentTerm matrix, this happens when you have more factors (aka terms) in the test dataset that are not present in the train dataset. So get rid of these very rare terms using the below code -
freq_terms = findFreqTerms(dtm.train, 5)
reduced_dtm.train = DocumentTermMatrix(corpus.train, list(dictionary=freq_terms))
reduced_dtm.test =  DocumentTermMatrix(corpus.test, list(dictionary=freq_terms))

The above code will get rid of any less frequent terms (anyway they are useless) and the levels in the test dataset will match the levels in the train dataset. Then the predict function should not throw any error.


text:
Q: listbox or listview of thumbnails with a directory as the input in c# I've seen a lot of code for doing listbox or listview thumbnails with hard coded, or submitted paths to an image.  How would one just provide a path and c# display the contents of the directory as thumbnails?
Thanks for any help, I'm a total newb, my apologies if this is a lame question.

A: Ok this is derived from the sample Listviews with Multiple Views. I added a button which chooses a file in a directory and then gets all the files from the directory and adds them to the list view. I generically set every item to the cat image.
using Microsoft.Win32;
using System.Collections.Generic;

lv.ItemsSource = null;
List<XmlElement> elements = new List<XmlElement>();
Microsoft.Win32.FileDialog fd = new Microsoft.Win32.OpenFileDialog();
bool ?a = fd.ShowDialog();
if (a == true)
{
     XmlDocument doc = new XmlDocument();
     string dir = fd.FileName.Remove(fd.FileName.Length - fd.SafeFileName.Length, fd.SafeFileName.Length);
     string[] files = Directory.GetFiles(dir);
     foreach (string file in files)
     {
           XmlElement item = doc.CreateElement(file.Remove(0,dir.Length));
           item.SetAttribute("Name", file.Remove(0, dir.Length));
           item.SetAttribute("Type", Path.GetExtension(file));
           item.SetAttribute("Image", "images\\cat.png");
           elements.Add(item);
      }
}
lv.ItemsSource = elements;


text:
Q: How can I parse a row's column value passed to a UDF when mapping a column? I have a dataframe like this, for the sake of simplicity i'm just showing 2 columns both columns are string, but in real life it will have more columns each of different types other than string:

SQLText
TableName

select * from sourceTable;
NewTable

select * from sourceTable1;
NewTable1

I also have a custom Function where i want to iterate over the dataframe and get the sql and run it to create a table, however I'm not passing each column individually, but rather the whole row:
def CreateTables(rowp):
    df = spark.sql(rowp.SQLText)
    #code to create table using rowp.TableName

This is my code, I first clean up SQLText because it's stored in another table and then I run the UDF on the column:
l = l.withColumn("SQLText", F.lit(F.regexp_replace(F.col("SQLText").cast("string"), "[\n\r]", " ")))
nt = l.select(l["*"]).withColumn("TableName",CreateTables(F.struct(*list(l.columns)) )).select("TableName","SQLText")
nt.show(truncate=False)

So when I'm running the function, and I try to run the code above, it errors out because instead of parsing the rowp.SQLText into its literal value, it passes its type?:
Column<'struct(SourceSQL, TableName)[SourceSQL]'>

So in the CreateTables function, when spark.sql(rowp.SQLText) is executed I expect the following:
df = spark.sql("select * from sourceTable;")
but instead this is happening, the variable type is literally being sent instead of the variable value
df = spark.sql("Column<'struct(SourceSQL, TableName)[SourceSQL]'>")
I've tried numerous solutions: getItem, getField, get, getAs but no luck yet.
I've also tried using indexes like rowp[0] but it just changes the variable type passed to the spark.sql function:
Column<'struct(SourceSQL, TableName)[0]'>

If I try rowp(0) it gives me a Column is not callable error.

A: There are many ways to do this.
Here is one way I tested in pyspark 3.2.3
rows = df.rdd.collect()
for i in range(len(rows)):
  spark.sql(rows[i][0])


text:
Q: Proof that a sum $x$ is found in$ [1, n (n + 1) / 2]$ squence In the subset sum existance problem, we have a sequence of integers. We are given an integer $x$ that we should look for a possible subsequence that sum to $x$. For example, if we have the sequence $\{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10\}$ and $x = 39$ then we have a subsequence $\{ 10, 9, 8, 7, 5 \}$ that sums up to $39$.
I want to prove that any sequence $[1, n]$ have a subsequence sum for any $x \in [1, n(n + 1) / 2]$. In the previous example, $n = 10$ so that any $x$ between $1$ and $55$ inclusive can be found. I have made a program and tested that this is true. Now I want to determine a proof.

A: You have verified the inductive hypothesis. Suppose that for some $n$, this is true. That is any number $1 \le x \le \frac{n(n+1)}{2}$ can be written as a sum of a sub-sequence of $\{1,\ \cdots,\ n\}$.
For $n+1$, any terms lower than $\frac{n(n+1)}{2}$ can still be formed via the induction hypothesis by simply omitting the term $n+1$. Then for any sum $S$ between $\frac{n(n+1)}{2} + 1$ and $\frac{(n+1)(n+2)}{2}$, form the corresponding sum $S - (n+1)$ using the terms from $1$ to $n$ (which is possibly via inductive hypothesis). Appending $n+1$ will then give you any sum in desired interval.

A: We can prove it inductively by constructing the subsequences systematically.Denote the subset summing to $p$ by $S(p)$.
Define $I(k)=\left\{1+\sum_{i=0}^{k-1} (n-i),\sum_{i=0}^{k} (n-i) \right\}$, such that $I(1)=\{1,...,n\}$, $I(2)={n+1,...,2n-1}$, etc.
This is trivially true for $I(1)$. Assume sums to exist for $I(k)$ where $1\leq k<n$. Observe that $S\left( \sum_{i=0}^{k} (n-i) \right)=\{n-k,n-k+1,...,n\}$. We can construct the sums for $I(k+1)$ by noting that if $p\in I(k+1)$, then $S(p)=\{m\}\cup S\left( \sum_{i=0}^{k} (n-i) \right)$, where $m=p-\sum_{i=0}^{k} (n-i)<n-k$. This completes the inductive step and the proof is complete.

A: Here is an alternative approach: consider the case for $n = 5$.
Then $n(n+1)/2 = 5(6)/2 = 15$.
Observe that we can write the numbers $1, \ldots, 15$ as follows:
$1, 2, 3, 4, 5,$
$1+5, 2+5, 3+5, 4+5,$
$1+4+5, 2+4+5, 3+4+5,$
$1+3+4+5, 2+3+4+5,$
$1+2+3+4+5$.
The number of elements summed for entries in the above rows, respectively, are: $1, 2, 3, 4, 5$.
By construction, they are distinct and increasing by one, beginning with $1$ and ending with $15$.
The above can be similarly written out for the general $n$ instead of $15$.


text:
Q: Как сделать вибрацию при старте приложения? Задача: запустить вибрацию при запуске приложения.
Такой код выдает ошибку :
@Override
protected void onStart() {
    super.onStart();
    Log.d("Start", "MainActivity: onStart()");
    vib.vibrate(1000);
    }

A: В AndroidManifest.xml дайте разрешение:
<uses-permission android:name="android.permission.VIBRATE"/>

Дальше всё также, пример:
    @Override
    protected void onStart() {
    super.onStart();
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(2000);
}


text:
Q: Switching between multiple ui forms in Qt I am developing the user interface for a embedded device. I have created about 30 ui forms. You have first the Welcome form which loads the database and connects automatically to the available known wifi and all those start up functions. Once everything is loaded the next form to be loaded is the user login
So this is how I go about it, if Login is my second ui
//Instantiating the Login class
Login *myLog = new Login();

//Close the welcome class
this->close();

//open the Login class
myLog->show();

Is this the right way to switch between multiple UI? The software can be imagined like any smart phone device with multiple Icon buttons to open different apps. And each app or folder has a functionality of its own. I have a home button to move back to main menu homepage and so on. I have used the above given code to switch between various ui forms and I am not sure if this is the way to go about it. I am very new to Qt and I was asked to do this task within 2 weeks and I created the easiest way I found. Is there a better way to go about it?
Any help or guidelines is appreciated. If you could give me links to understand better it would be great
Thank you
EDIT

Every ui form has a short cut panel for direct access to login, main menu, settings-power options, wifi options (within settings). The layout flow shown under 1 is similar to 2, 3 and settings. Sorry for the ugly image. The two way arrow indicates i can switch back and forth. The single arrow shows linear movement.

A:
Is there a better way to go about it?

I think so.
As noted in the comment, I would use a QStackedWidget myself.
I think this blog post explains how to establish "Home", "First" and so forth widgets inside it. This should be useful for you:
How to use Qstackedwidget in Qt (Switching between multiple views in Qt)


text:
Q: ipad keyboard hides uitextView I have quite a long form in ipad having uitextfields and uitextviews. I am able to scroll up when the keyboard hides the uitextfield using keyboard notifications. but when the uitextview becomes active and it is under the keyboard it just slides enough so that i can see the blinking cursor. Is this the normal behavior? If not how can i scroll the entire uitextview upwards so that the entire uitextview is visible at the time of editing?
Here is the code..
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name: UIKeyboardDidShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark Keyboard Events

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return NO;
}

#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
-(void)keyboardWasShown:(NSNotification *)aNotification
{

if (displayKeyboard==YES) {
    return;
}
NSDictionary* info = [aNotification userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
//NSValue* aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;

offset = _scrollView.contentOffset;

CGRect viewFrame = _scrollView.frame;

viewFrame.size.height -= keyboardSize.height-tabbarHt;
_scrollView.frame = viewFrame;

CGRect textFieldRect = [activeField frame];
textFieldRect.origin.y += 10;
[_scrollView scrollRectToVisible: textFieldRect animated:YES];
displayKeyboard = YES;

}

-(void)keyboardWillBeHidden:(NSNotification *)aNotification
{

if (!displayKeyboard) {
    return;
}

_scrollView.frame = CGRectMake(0, 0, 1024, 655);
_scrollView.contentOffset =offset;
displayKeyboard = NO;
}

-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField {
activeField = textField;
return YES;
}

A: Give delegate to your UITextView
CGRect activeField;

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    activeField = textView.frame;
}

-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField {
   activeField = textField.frame;
   return YES;
}

Try With this code. Every time you have given only textField rect size. when you call text view you have to pass textview frame size


text:
Q: Need advice on referencing a Managed COM Server (EXE) from Client Application I have a managed COM out of process server exe in c# exposing my application object model for automation everything is working fine. I can access it from unmanaged code (for example, VC++) and it starts my out of proc server and every works through COM, by using a type library created for my server exe.
When I try and do this from managed code, say a C# client application, I reference my server exe, but it loads the server in-process into the client application.
How can I get it too work from managed code and run has an out of process server in its own process?
What I am trying to do is expose a application object model in COM over my application so it can be automated used by unmanaged code and also managed code, similar to how microsoft office. Everything works fine under unmanaged code through COM, but trying to do the same from Managed code only instantiates my object in-process.
C# Example:
MyApp.Application app = new MyApp.Application();

Would just instantiate the object but I want it too start my out of process COM server as well. Am I missing something here, just wondering if anyone has advice on what to do or where to look.

A: I found the answer in this article:

regardless of whether the
  implementation .NET assembly is a
  Class Library DLL or an executable,
  this assembly is always loaded
  in-process into the address space of
  the client application. And, in the
  case of an EXE assembly it is neither executed,
  nor will a running instance of it be
  used to instantiate the required .NET
  class....

Some other unorthodox means are required in order to simulate the use of a .NET EXE assembly as an out-of-proc COM Server.

A: All I can think of is to use Serviced Components hosted in COM+. MSDN Link


text:
Q: Where, in zend engine, does a PHP script get loaded? I'd like to follow the journey of a PHP script through the zend engine source code.  When I request my_prog.php, in which source file / function is it read from disk?  zend.c, zend_compile.c, others?
Also, is there documentation on this?  I've been searching for two days and have not found anything useful, and I'm pretty good at searching on the net.


text:
Q: r plyr revalue limitation of number of operations? I'm currently using revalue() from plyr to revalue factors levels in a dataframe from a code, like A01-21 to the real value. There are around 2400 levels, and I want revalue in order to be able to have the code as reference in my dataframe, and the corresponding values in translatable texts (to show them in french in french web pages, etc...)
You can test this yourself :
First create a dataframe:
test <- c("H07-24", "H07-25", "H07-26", "H07-27", "H07-28", "H07-29", "H07-30", "H07-31", "H07-32", "H07-33", "H07-34", "H07-35", "H07-36", "H07-37", "H07-38", "H07-40", "H07-41", "H07-42", "H07-43", "H07-44", "H07-45", "H07-46", "H07-47", "H07-48", "H07-49", "H07-50", "H07-51", "H07-52", "H07-53", "H07-54", "H07-55", "H07-56", "H07-57", "H07-60", "H07-61", "H07-62", "H07-63", "H07-64", "H07-65", "H07-66", "H07-67", "H07-68", "H07-69", "H07-70", "H07-71", "H07-72", "H07-73", "H07-74", "H07-75", "H07-80", "H07-81", "H07-82", "H07-83", "H07-84", "H07-85", "H07-86", "H07-90", "H07-91", "H07-92", "H07-93", "I00-00", "I01-00", "I01-10", "I01-11", "I01-12", "I01-13", "I01-20", "I01-21", "I01-22", "I01-23", "I01-24", "I02-00", "I02-10", "I02-10", "I02-11", "I02-12", "I02-20", "I02-21", "I02-22", "I02-23", "I02-24", "I02-40", "I02-40", "I03-00", "I03-01", "I03-02", "I03-03", "I03-04", "I03-05", "I03-20", "I03-30", "I03-31", "I03-32", "I03-33", "I03-34", "I03-35", "I03-36", "I03-36", "I03-37", "I03-40", "I03-41", "I03-42", "I03-43", "I03-50", "I03-50", "I04-00", "I04-10", "I04-20", "I04-30", "I04-30", "I04-50", "I04-60", "I04-70", "I05-00", "I05-10")

values <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)

df <- data.frame(values=values, test=test)

Let's test revalue with 115 entries
df$test <- revalue(df$test, c("H07-24"="H07-24 - Mettre à disposition assistance technique", "H07-25"="H07-25 - Actions pour réclamer actions publiques à l administration", "H07-26"="H07-26 - Actions pour réclamer actions publiques à l'administration", "H07-27"="H07-27 - ", "H07-28"="H07-28 - ", "H07-29"="H07-29 - DYNAMISME - APATHIE", "H07-30"="H07-30 - Promouvoir des actions, se mobiliser - communauté active - faire des activités", "H07-31"="H07-31 - Dynamisme de la société - motivation, société active, participative (acharnement sociétal)", "H07-32"="H07-32 - Activités pour développer la société", "H07-33"="H07-33 - Dynamisme des élus - des leaders", "H07-34"="H07-34 - Intéresse pour participer dans les projets", "H07-35"="H07-35 - Sponsoriser activités", "H07-36"="H07-36 - Sponsoriser activités", "H07-37"="H07-37 - ", "H07-38"="H07-38 - ACTIONS EN COMMUN - PARTENARIAT", "H07-40"="H07-40 - Action de s engager en commun –les personnes", "H07-41"="H07-41 - Engage en commun entre les communautés", "H07-42"="H07-42 - Organisation de la société (communauté organisée)", "H07-43"="H07-43 - Travail en commun entre l autorité et les associations", "H07-44"="H07-44 - Mobiliser le partenariat", "H07-45"="H07-45 - Mobiliser le partenariat", "H07-46"="H07-46 - ", "H07-47"="H07-47 - ", "H07-48"="H07-48 - ", "H07-49"="H07-49 - SYNERGIES COLLECTIVES", "H07-50"="H07-50 - De rencontre social, se réunir", "H07-51"="H07-51 - Donner d empowerment (habiliter qqun à faire qqch) (capacitar)", "H07-52"="H07-52 - Participation dans les réunions, les activités - s opposer", "H07-53"="H07-53 - Promouvoir les débats", "H07-54"="H07-54 - Promouvoir les débats", "H07-55"="H07-55 - ", "H07-56"="H07-56 - ", "H07-57"="H07-57 - ENGAGEMENTS COLLECTIFS - ASSOC", "H07-60"="H07-60 - S associer - s organiser en associations - Avoir une association", "H07-61"="H07-61 - Avoir des réunions - participer dans l association", "H07-62"="H07-62 - Participation de la communauté dans l association", "H07-63"="H07-63 - Collaboration entre les associations (et ente les associations et la communauté)", "H07-64"="H07-64 - Initiative associatif, participation des associés", "H07-65"="H07-65 - Paiement des cotisations sociétales", "H07-66"="H07-66 - Cadre directive des associations", "H07-67"="H07-67 - Construction d un siège social", "H07-68"="H07-68 - Organisation - gestion de l association (ACD)", "H07-69"="H07-69 - PROMOUVOIR - ORGANISER - DÉVELOPPER ACTIVITÉS- FESTIVES", "H07-70"="H07-70 - PROMOUVOIR / ORGANISER / DÉVELOPPER ACTIVITÉS/ FESTIVES", "H07-71"="H07-71 - ", "H07-72"="H07-72 - ", "H07-73"="H07-73 - ", "H07-74"="H07-74 - ", "H07-75"="H07-75 - RÉFLEXION SOCIALE - FAIRE DIAGNOSTIC SOCIÉTAL", "H07-80"="H07-80 - Être capable d identifier les problèmes sociaux", "H07-81"="H07-81 - Faire des comparaisons", "H07-82"="H07-82 - Réflexion sur les problèmes sociaux", "H07-83"="H07-83 - Permettre les actions qui portent bonheur à la société", "H07-84"="H07-84 - Profiter des ressources communautaires pour se développer", "H07-85"="H07-85 - Conscientisation sociale", "H07-86"="H07-86 - Conscientisation sociale", "H07-90"="H07-90 - ", "H07-91"="H07-91 - ", "H07-92"="H07-92 - ", "H07-93"="H07-93 - RELATIONS DANS LA SOCIÉTÉ", "I00-00"="I00-00 - RELATIONS DE GENRE", "I01-00"="I01-00 - DISCRIMINATIONS BASÉES SUR LE GENRE", "I01-10"="I01-10 - Discrimination directe", "I01-11"="I01-11 - Discrimination  structurelle", "I01-12"="I01-12 - Plafond de verre", "I01-13"="I01-13 - MANQUE DE RESPECT", "I01-20"="I01-20 - Mépris", "I01-21"="I01-21 - Préjugé", "I01-22"="I01-22 - Ne pas reconnaître autrui", "I01-23"="I01-23 - Stigmatisation", "I01-24"="I01-24 - RELATIONS ENTRE LES GÉNÉRATIONS", "I02-00"="I02-00 - MODALITÉS DES RELATIONS ENTRE LES GÉNÉRATIONS", "I02-10"="I02-10 - RELATIONS MUTUELLES ENTRE GÉNÉRATIONS", "I02-10"="I02-10 - Soutien mutuel", "I02-11"="I02-11 - Respect mutuel", "I02-12"="I02-12 - ATTITUDE D UNE GÉNÉRATION À L AUTRE", "I02-20"="I02-20 - Respect mutuel", "I02-21"="I02-21 - Support mutuel", "I02-22"="I02-22 - Préjugés mutuels", "I02-23"="I02-23 - Confiance réciproque", "I02-24"="I02-24 - GENERATIONS CONTRACT", "I02-40"="I02-40 - FOSSÉ GÉNÉRATIONNEL", "I02-40"="I02-40 - RELATIONS ENTRE CULTURES", "I03-00"="I03-00 - Préjugés", "I03-01"="I03-01 - Dialogue interculturel", "I03-02"="I03-02 - Non reconnaissance", "I03-03"="I03-03 - Discrimination", "I03-04"="I03-04 - Mépris, dédain, être hautain", "I03-05"="I03-05 - DIALOGUE INTER-RELIGIEUX", "I03-20"="I03-20 - PROBLÈMES DE LANGAGE", "I03-30"="I03-30 - Statut des langues regionales", "I03-31"="I03-31 - Langues minoritaires", "I03-32"="I03-32 - Statut de la deuxième langue", "I03-33"="I03-33 - Relations entre la langue maternelle et la deuxième langue", "I03-34"="I03-34 - Assimilation linguistique", "I03-35"="I03-35 - Perte de la langue maternelle", "I03-36"="I03-36 - Bilinguism", "I03-36"="I03-36 - Non maîtrise des langues natives et secondes", "I03-37"="I03-37 - ENSEIGNEMENT DES LANGUES", "I03-40"="I03-40 - Enseignement de la langue maternelle", "I03-41"="I03-41 - Enseignement des langues étrangères", "I03-42"="I03-42 - Enseignement de la deuxième langue", "I03-43"="I03-43 - OUVERTURE ET TOLÉRANCE DANS LE DOM. DE LA LANGUE", "I03-50"="I03-50 - SOUTIEN EN CAS DE DIFFICULTÉS DE LANGUE", "I03-50"="I03-50 - RELATIONS ENTRE CLASSES SOCIALES", "I04-00"="I04-00 - ÉCHANGES", "I04-10"="I04-10 - RESPECT MUTUEL", "I04-20"="I04-20 - SOLIDARITÉ", "I04-30"="I04-30 - MIXITÉ", "I04-30"="I04-30 - PRÉJUGÉS", "I04-50"="I04-50 - DISCRIMINATION", "I04-60"="I04-60 - STIGMATISATION", "I04-70"="I04-70 - RELATIONS LOCALES", "I05-00"="I05-00 - RELATIONS DE VOISINAGE - APPARTEMENTS", "I05-10"="I05-10 - RELATIONS DE QUARTIER"))

This doesn't work ! It's a bit like if somehow a " symbol got lost. There is a + prompt now, that you must exit typing """.
But if we cut this in two separate operations (which use the same arguments)
df$test <- revalue(df$test, c("H07-24"="H07-24 - Mettre à disposition assistance technique", "H07-25"="H07-25 - Actions pour réclamer actions publiques à l administration", "H07-26"="H07-26 - Actions pour réclamer actions publiques à l'administration", "H07-27"="H07-27 - ", "H07-28"="H07-28 - ", "H07-29"="H07-29 - DYNAMISME - APATHIE", "H07-30"="H07-30 - Promouvoir des actions, se mobiliser - communauté active - faire des activités", "H07-31"="H07-31 - Dynamisme de la société - motivation, société active, participative (acharnement sociétal)", "H07-32"="H07-32 - Activités pour développer la société", "H07-33"="H07-33 - Dynamisme des élus - des leaders", "H07-34"="H07-34 - Intéresse pour participer dans les projets", "H07-35"="H07-35 - Sponsoriser activités", "H07-36"="H07-36 - Sponsoriser activités", "H07-37"="H07-37 - ", "H07-38"="H07-38 - ACTIONS EN COMMUN - PARTENARIAT", "H07-40"="H07-40 - Action de s engager en commun –les personnes", "H07-41"="H07-41 - Engage en commun entre les communautés", "H07-42"="H07-42 - Organisation de la société (communauté organisée)", "H07-43"="H07-43 - Travail en commun entre l autorité et les associations", "H07-44"="H07-44 - Mobiliser le partenariat", "H07-45"="H07-45 - Mobiliser le partenariat", "H07-46"="H07-46 - ", "H07-47"="H07-47 - ", "H07-48"="H07-48 - ", "H07-49"="H07-49 - SYNERGIES COLLECTIVES", "H07-50"="H07-50 - De rencontre social, se réunir", "H07-51"="H07-51 - Donner d empowerment (habiliter qqun à faire qqch) (capacitar)", "H07-52"="H07-52 - Participation dans les réunions, les activités - s opposer", "H07-53"="H07-53 - Promouvoir les débats", "H07-54"="H07-54 - Promouvoir les débats", "H07-55"="H07-55 - ", "H07-56"="H07-56 - ", "H07-57"="H07-57 - ENGAGEMENTS COLLECTIFS - ASSOC", "H07-60"="H07-60 - S associer - s organiser en associations - Avoir une association", "H07-61"="H07-61 - Avoir des réunions - participer dans l association", "H07-62"="H07-62 - Participation de la communauté dans l association", "H07-63"="H07-63 - Collaboration entre les associations (et ente les associations et la communauté)", "H07-64"="H07-64 - Initiative associatif, participation des associés", "H07-65"="H07-65 - Paiement des cotisations sociétales", "H07-66"="H07-66 - Cadre directive des associations", "H07-67"="H07-67 - Construction d un siège social", "H07-68"="H07-68 - Organisation - gestion de l association (ACD)"))

df$test <- revalue(df$test, c("H07-69"="H07-69 - PROMOUVOIR - ORGANISER - DÉVELOPPER ACTIVITÉS- FESTIVES", "H07-70"="H07-70 - PROMOUVOIR / ORGANISER / DÉVELOPPER ACTIVITÉS/ FESTIVES", "H07-71"="H07-71 - ", "H07-72"="H07-72 - ", "H07-73"="H07-73 - ", "H07-74"="H07-74 - ", "H07-75"="H07-75 - RÉFLEXION SOCIALE - FAIRE DIAGNOSTIC SOCIÉTAL", "H07-80"="H07-80 - Être capable d identifier les problèmes sociaux", "H07-81"="H07-81 - Faire des comparaisons", "H07-82"="H07-82 - Réflexion sur les problèmes sociaux", "H07-83"="H07-83 - Permettre les actions qui portent bonheur à la société", "H07-84"="H07-84 - Profiter des ressources communautaires pour se développer", "H07-85"="H07-85 - Conscientisation sociale", "H07-86"="H07-86 - Conscientisation sociale", "H07-90"="H07-90 - ", "H07-91"="H07-91 - ", "H07-92"="H07-92 - ", "H07-93"="H07-93 - RELATIONS DANS LA SOCIÉTÉ", "I00-00"="I00-00 - RELATIONS DE GENRE", "I01-00"="I01-00 - DISCRIMINATIONS BASÉES SUR LE GENRE", "I01-10"="I01-10 - Discrimination directe", "I01-11"="I01-11 - Discrimination  structurelle", "I01-12"="I01-12 - Plafond de verre", "I01-13"="I01-13 - MANQUE DE RESPECT", "I01-20"="I01-20 - Mépris", "I01-21"="I01-21 - Préjugé", "I01-22"="I01-22 - Ne pas reconnaître autrui", "I01-23"="I01-23 - Stigmatisation", "I01-24"="I01-24 - RELATIONS ENTRE LES GÉNÉRATIONS", "I02-00"="I02-00 - MODALITÉS DES RELATIONS ENTRE LES GÉNÉRATIONS", "I02-10"="I02-10 - RELATIONS MUTUELLES ENTRE GÉNÉRATIONS", "I02-10"="I02-10 - Soutien mutuel", "I02-11"="I02-11 - Respect mutuel", "I02-12"="I02-12 - ATTITUDE D UNE GÉNÉRATION À L AUTRE", "I02-20"="I02-20 - Respect mutuel", "I02-21"="I02-21 - Support mutuel", "I02-22"="I02-22 - Préjugés mutuels", "I02-23"="I02-23 - Confiance réciproque", "I02-24"="I02-24 - GENERATIONS CONTRACT", "I02-40"="I02-40 - FOSSÉ GÉNÉRATIONNEL", "I02-40"="I02-40 - RELATIONS ENTRE CULTURES", "I03-00"="I03-00 - Préjugés", "I03-01"="I03-01 - Dialogue interculturel", "I03-02"="I03-02 - Non reconnaissance", "I03-03"="I03-03 - Discrimination", "I03-04"="I03-04 - Mépris, dédain, être hautain", "I03-05"="I03-05 - DIALOGUE INTER-RELIGIEUX", "I03-20"="I03-20 - PROBLÈMES DE LANGAGE", "I03-30"="I03-30 - Statut des langues regionales", "I03-31"="I03-31 - Langues minoritaires", "I03-32"="I03-32 - Statut de la deuxième langue", "I03-33"="I03-33 - Relations entre la langue maternelle et la deuxième langue", "I03-34"="I03-34 - Assimilation linguistique", "I03-35"="I03-35 - Perte de la langue maternelle", "I03-36"="I03-36 - Bilinguism", "I03-36"="I03-36 - Non maîtrise des langues natives et secondes", "I03-37"="I03-37 - ENSEIGNEMENT DES LANGUES", "I03-40"="I03-40 - Enseignement de la langue maternelle", "I03-41"="I03-41 - Enseignement des langues étrangères", "I03-42"="I03-42 - Enseignement de la deuxième langue", "I03-43"="I03-43 - OUVERTURE ET TOLÉRANCE DANS LE DOM. DE LA LANGUE", "I03-50"="I03-50 - SOUTIEN EN CAS DE DIFFICULTÉS DE LANGUE", "I03-50"="I03-50 - RELATIONS ENTRE CLASSES SOCIALES", "I04-00"="I04-00 - ÉCHANGES", "I04-10"="I04-10 - RESPECT MUTUEL", "I04-20"="I04-20 - SOLIDARITÉ", "I04-30"="I04-30 - MIXITÉ", "I04-30"="I04-30 - PRÉJUGÉS", "I04-50"="I04-50 - DISCRIMINATION", "I04-60"="I04-60 - STIGMATISATION", "I04-70"="I04-70 - RELATIONS LOCALES", "I05-00"="I05-00 - RELATIONS DE VOISINAGE - APPARTEMENTS", "I05-10"="I05-10 - RELATIONS DE QUARTIER"))

It works !!!
Is there a limitation in C()? In revalue()? What did I miss ???

A: There is a limit of 4095 bytes per command line entered in the console, and this evidentally exceeds that. If you break your command into several lines it will work, like so:
df$test <- revalue(df$test, c("H07-24"="H07-24 - Mettre à disposition assistance technique", "H07-25"="H07-25 - Actions pour réclamer actions publiques à l administration", "H07-26"="H07-26 - Actions pour réclamer actions publiques à l'administration", "H07-27"="H07-27 - ", "H07-28"="H07-28 - ", "H07-29"="H07-29 - DYNAMISME - APATHIE", "H07-30"="H07-30 - Promouvoir des actions, se mobiliser - communauté active - faire des activités", "H07-31"="H07-31 - Dynamisme de la société - motivation, société active, participative (acharnement sociétal)", "H07-32"="H07-32 - Activités pour développer la société", "H07-33"="H07-33 - Dynamisme des élus - des leaders", "H07-34"="H07-34 - Intéresse pour participer dans les projets", "H07-35"="H07-35 - Sponsoriser activités", "H07-36"="H07-36 - Sponsoriser activités", "H07-37"="H07-37 - ", "H07-38"="H07-38 - ACTIONS EN COMMUN - PARTENARIAT", "H07-40"="H07-40 - Action de s engager en commun –les personnes", "H07-41"="H07-41 - Engage en commun entre les communautés", "H07-42"="H07-42 - Organisation de la société (communauté organisée)", "H07-43"="H07-43 - Travail en commun entre l autorité et les associations", "H07-44"="H07-44 - Mobiliser le partenariat", "H07-45"="H07-45 - Mobiliser le partenariat", "H07-46"="H07-46 - ", "H07-47"="H07-47 - ", "H07-48"="H07-48 - ", "H07-49"="H07-49 - SYNERGIES COLLECTIVES", "H07-50"="H07-50 - De rencontre social, se réunir", "H07-51"="H07-51 - Donner d empowerment (habiliter qqun à faire qqch) (capacitar)", "H07-52"="H07-52 - Participation dans les réunions, les activités - s opposer", "H07-53"="H07-53 - Promouvoir les débats",
                              "H07-54"="H07-54 - Promouvoir les débats", "H07-55"="H07-55 - ", "H07-56"="H07-56 - ", "H07-57"="H07-57 - ENGAGEMENTS COLLECTIFS - ASSOC", "H07-60"="H07-60 - S associer - s organiser en associations - Avoir une association", "H07-61"="H07-61 - Avoir des réunions - participer dans l association", "H07-62"="H07-62 - Participation de la communauté dans l association", "H07-63"="H07-63 - Collaboration entre les associations (et ente les associations et la communauté)", "H07-64"="H07-64 - Initiative associatif, participation des associés", "H07-65"="H07-65 - Paiement des cotisations sociétales", "H07-66"="H07-66 - Cadre directive des associations", "H07-67"="H07-67 - Construction d un siège social", "H07-68"="H07-68 - Organisation - gestion de l association (ACD)", "H07-69"="H07-69 - PROMOUVOIR - ORGANISER - DÉVELOPPER ACTIVITÉS- FESTIVES", "H07-70"="H07-70 - PROMOUVOIR / ORGANISER / DÉVELOPPER ACTIVITÉS/ FESTIVES", "H07-71"="H07-71 - ", "H07-72"="H07-72 - ", "H07-73"="H07-73 - ", "H07-74"="H07-74 - ", "H07-75"="H07-75 - RÉFLEXION SOCIALE - FAIRE DIAGNOSTIC SOCIÉTAL", "H07-80"="H07-80 - Être capable d identifier les problèmes sociaux", "H07-81"="H07-81 - Faire des comparaisons", "H07-82"="H07-82 - Réflexion sur les problèmes sociaux", "H07-83"="H07-83 - Permettre les actions qui portent bonheur à la société", "H07-84"="H07-84 - Profiter des ressources communautaires pour se développer", "H07-85"="H07-85 - Conscientisation sociale", "H07-86"="H07-86 - Conscientisation sociale", "H07-90"="H07-90 - ", "H07-91"="H07-91 - ", "H07-92"="H07-92 - ", "H07-93"="H07-93 - RELATIONS DANS LA SOCIÉTÉ", "I00-00"="I00-00 - RELATIONS DE GENRE", "I01-00"="I01-00 - DISCRIMINATIONS BASÉES SUR LE GENRE", "I01-10"="I01-10 - Discrimination directe", "I01-11"="I01-11 - Discrimination  structurelle", "I01-12"="I01-12 - Plafond de verre", "I01-13"="I01-13 - MANQUE DE RESPECT", "I01-20"="I01-20 - Mépris", "I01-21"="I01-21 - Préjugé", "I01-22"="I01-22 - Ne pas reconnaître autrui", "I01-23"="I01-23 - Stigmatisation", "I01-24"="I01-24 - RELATIONS ENTRE LES GÉNÉRATIONS", "I02-00"="I02-00 - MODALITÉS DES RELATIONS ENTRE LES GÉNÉRATIONS", "I02-10"="I02-10 - RELATIONS MUTUELLES ENTRE GÉNÉRATIONS", "I02-10"="I02-10 - Soutien mutuel", "I02-11"="I02-11 - Respect mutuel", "I02-12"="I02-12 - ATTITUDE D UNE GÉNÉRATION À L AUTRE", "I02-20"="I02-20 - Respect mutuel", "I02-21"="I02-21 - Support mutuel", "I02-22"="I02-22 - Préjugés mutuels", "I02-23"="I02-23 - Confiance réciproque", "I02-24"="I02-24 - GENERATIONS CONTRACT", "I02-40"="I02-40 - FOSSÉ GÉNÉRATIONNEL", "I02-40"="I02-40 - RELATIONS ENTRE CULTURES", "I03-00"="I03-00 - Préjugés", "I03-01"="I03-01 - Dialogue interculturel", "I03-02"="I03-02 - Non reconnaissance", "I03-03"="I03-03 - Discrimination", "I03-04"="I03-04 - Mépris, dédain, être hautain", "I03-05"="I03-05 - DIALOGUE INTER-RELIGIEUX", "I03-20"="I03-20 - PROBLÈMES DE LANGAGE", "I03-30"="I03-30 - Statut des langues regionales", "I03-31"="I03-31 - Langues minoritaires", "I03-32"="I03-32 - Statut de la deuxième langue", "I03-33"="I03-33 - Relations entre la langue maternelle et la deuxième langue", "I03-34"="I03-34 - Assimilation linguistique", "I03-35"="I03-35 - Perte de la langue maternelle", "I03-36"="I03-36 - Bilinguism", "I03-36"="I03-36 - Non maîtrise des langues natives et secondes",
                              "I03-37"="I03-37 - ENSEIGNEMENT DES LANGUES", "I03-40"="I03-40 - Enseignement de la langue maternelle", "I03-41"="I03-41 - Enseignement des langues étrangères", "I03-42"="I03-42 - Enseignement de la deuxième langue", "I03-43"="I03-43 - OUVERTURE ET TOLÉRANCE DANS LE DOM. DE LA LANGUE", "I03-50"="I03-50 - SOUTIEN EN CAS DE DIFFICULTÉS DE LANGUE", "I03-50"="I03-50 - RELATIONS ENTRE CLASSES SOCIALES", "I04-00"="I04-00 - ÉCHANGES", "I04-10"="I04-10 - RESPECT MUTUEL", "I04-20"="I04-20 - SOLIDARITÉ", "I04-30"="I04-30 - MIXITÉ", "I04-30"="I04-30 - PRÉJUGÉS", "I04-50"="I04-50 - DISCRIMINATION", "I04-60"="I04-60 - STIGMATISATION", "I04-70"="I04-70 - RELATIONS LOCALES", "I05-00"="I05-00 - RELATIONS DE VOISINAGE - APPARTEMENTS", "I05-10"="I05-10 - RELATIONS DE QUARTIER"))


text:
Q: How get Form data in admin magento I have added a button on admin form in magento,when i click  on it i did not get form data,i want functionality like save button.
  $this->_addButton('owner', array(
        'label'     => Mage::helper('adminhtml')->__('Change Owner'),
        'onclick'   => 'setLocation(\'' . $this->getUrl('*/*/owner/id/'.$id) . '\')',
        'class'     => 'save',
    ),1,3);

A: First of all your requirement is not clear.Where are you checking the submitted data? If you want to submit the admin form data and receive it in the controller file than you placed the button in the wrong place.It should not be in the Form.php


text:
Q: Deezer API - get current position I want to track when a user starts playing a song. My Problem is that it is only possible to track the play Button (in my opinion). But I only want the beginning of the song and not every Play Button click (also when the user has pause the song and resume it).
Therefore I wanna check the current position of the song and track only when the current position is below 1 second or something. Does anyone know how to get the position of the current playing song? The only thing regarding the player position I have found was the player_position event which is triggered when the position within the song has changed.
Any ideas? The very last I want to do is to store a variable that remembers, if the song was already tracked or something.

A: The only way to know when an user has started to play a song is to use the "player_position" as you said. It is different than the "player_play" which is executed when you use the "DZ.player.play" action. If you want, you have an example here http://developers.deezer.com/sdk/javascript/example-invisible which displays how it works.

A: Based on the hint of Fred_Dzr I made a solution, that works quite nice:
DZ.Event.subscribe('player_position', function(positionArray) {
    var track = DZ.player.getCurrentTrack();
    var position = Math.floor(positionArray[0]);
    if(position === 1) {
        if(!track['tracked']) {
            console.log('TRACKING: play: ' + track.id + ' | ' + track.artist.name + ' - ' + track.title);
            track['tracked'] = true;
        }
    } else {
        track['tracked'] = false;
    }
});

With the additional flag "tracked" on every track I am sure that the Song is not tracked twice, when the "player_position" Event is fired on position 1.1593044475699572 and 1.4754669253862243 and 1.7916924465679582 or something else.
Tracking on position 0 don't work for me, because the "player_position" Event is fired on player load, but position 1 is quite enough. Also when the User seeks to the beginning of the song the tracking is triggered. Thats ok, because in this case he listen to the Song again.
With this method I am also able to track the Midpoint of the Song.
Thank you!