text:
Q: DataTables.js removes multiple rows on row().remove().draw() call When I row(row).remove().draw(false) on a row Datatables removes an extra row.
This is my javascript:
$('.wrapper').on('click', '#confirm_delete', function(e) {
    e.preventDefault();
    var modal = $(this).closest('.modal');
    var id = modal.find('#delete_id').val();
    var row = $('#list_bkng_bus').find('.booking-id[value="'+id+'"]').closest('tr');

    $.ajax({
        type: 'POST',
        url: '/includes/ajax/bookings-bus.php',
        dataType: 'json',
        data: { 'delete_id': id },
        success: function(result) {
            bkng_bus_table.row(row).remove().draw(false);
            modal.modal('hide');
            status_message('success', 'Boeking verwijderd');
        },
        error: function(xhr, status, error) {
            console.log(xhr.responseText);
            console.log(error);
            status_message('error', 'Databasefout. (Remove booking business)');
        }
    });

});

This is the content of my row variable:
0 : tr.even
context : document
length : 1
prevObject : [input.booking-id, prevObject: n.fn.init(1), context: document, selector: "#list_bkng_bus .booking-id[value="57"]"]

So it contains a tr.

A: you code should work, and if not then you VAR row should have problem.
in case of more information you can check

A: The issue was the fact that because of the way the table was generated (dynamically), multiple event listeners were attached to the element.
The solution was using .off('click') before .on('click', '#confirm_delete', function(e) {.
Which makes this code function as expected:
$('.wrapper').off('click').on('click', '#confirm_delete', function(e) {
    e.preventDefault();
    var modal = $(this).closest('.modal');
    var id = modal.find('#delete_id').val();
    var row = $('#list_bkng_bus').find('.booking-id[value="'+id+'"]').closest('tr');

    $.ajax({
        type: 'POST',
        url: '/includes/ajax/bookings-bus.php',
        dataType: 'json',
        data: { 'delete_id': id },
        success: function(result) {
            bkng_bus_table.row(row).remove().draw(false);
            modal.modal('hide');
            status_message('success', 'Boeking verwijderd');
        },
        error: function(xhr, status, error) {
            console.log(xhr.responseText);
            console.log(error);
            status_message('error', 'Databasefout. (Remove booking business)');
        }
    });

});


text:
Q: How do I Listen events from the toolbar in fragments? Im Making an App that consist in One activity with a tablayout and a Viewpager, I have 3 tabs where each tab has a fragment. The main activity has a Toolbar with a Swich on it.
The point is that I need listen events changes from this switch in the main activity and the fragments. Actually I called onCreateOptionsMenu and onOptionItemSelected in MainActivity and works but Is possible use this methods in fragments again? o How can I listen events from UI controls in the toolbar from a fragment?
Mi Code is:
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    }else{
        if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)){
            Toast.makeText(MainActivity.this,"Debes autorizar los permisos de ubicacion",Toast.LENGTH_SHORT).show();
        }else{
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST_CODE);
        }
    }

}

private void setupViewPager(ViewPager viewPager){
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), getString(R.string.tabRedes));
    adapter.addFragment(new TwoFragment(),getString(R.string.tabRedesGuardadas));
    adapter.addFragment(new ThreeFragment(),getString(R.string.tabMapas));
    viewPager.setAdapter(adapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.menuactionbar,menu);
    final SwitchCompat switch1= (SwitchCompat) menu.findItem(R.id.switch_wifi).getActionView().findViewById(R.id.switchForActionBar);

    if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){

        switch1.setChecked(wifiManager.isWifiEnabled());

        if(wifiManager.isWifiEnabled()){
            switch1.setText(R.string.switchOnWifiEs);
        }else {
            switch1.setText(R.string.swtichOffWifiEs);
            //wifiManager.setWifiEnabled(true);
        }

        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    switch1.setText(R.string.switchOnWifiEs);
                    wifiManager.setWifiEnabled(true);
                    Toast.makeText(MainActivity.this,R.string.switchingOnWifiEs,Toast.LENGTH_SHORT).show();
                }
                else{
                    switch1.setText(R.string.swtichOffWifiEs);
                    wifiManager.setWifiEnabled(false);
                    Toast.makeText(MainActivity.this,R.string.switchingOffWifiEs,Toast.LENGTH_SHORT).show();
                }
            }
        });

    }else{
        if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)){
            Toast.makeText(MainActivity.this,"Debes autorizar los permisos de ubicacion",Toast.LENGTH_SHORT).show();
        }else{
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST_CODE);
        }
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){

    switch (item.getItemId()){
        case R.id.menu_settings:
            Intent nav = new Intent(MainActivity.this,configuracion_Activity.class);
            startActivity(nav);
            return true;
        case R.id.menu_acercade:
            Intent nav2 = new Intent(MainActivity.this,acercade_Activity.class);
            startActivity(nav2);
            return true;
        default:
            Toast.makeText(MainActivity.this,"Estas entrando en e Default",Toast.LENGTH_SHORT).show();
            return super.onOptionsItemSelected(item);
    }
}

A: In your CheckedChangeListener of Switch
  switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked){
                        switch1.setText(R.string.switchOnWifiEs);
                        wifiManager.setWifiEnabled(true);
                        Toast.makeText(MainActivity.this,R.string.switchingOnWifiEs,Toast.LENGTH_SHORT).show();
                    }
                    else{
                        switch1.setText(R.string.swtichOffWifiEs);
                        wifiManager.setWifiEnabled(false);
                        Toast.makeText(MainActivity.this,R.string.switchingOffWifiEs,Toast.LENGTH_SHORT).show();
                    }
final Fragment currentFragment = getFragmentManager().findfragmentId(R.id.container);
if(currentFragment instance HomeFragment){
((HomeFragment)currentFragment).switchClicked(isChecked);
}

                }
            });

In your fragment :
public void switchClicked(final boolean isChecked){
...... your code.
}

A: Found the answer by myself, IDK if is the best way but works fine for me:
in my fragment:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
    super.onCreateOptionsMenu(menu, inflater);
    final SwitchCompat switch1= (SwitchCompat) menu.findItem(R.id.switch_wifi).getActionView().findViewById(R.id.switchForActionBar);

    switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                fab.setVisibility(View.VISIBLE);
            }
            else{
                fab.setVisibility(View.GONE);
            }
        }
    });

A: you should check this out
How to get Toolbar from fragment?
this helped me a long time ago. d:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cast SDK - using local files I'm building an app and I wanted to use the Cast SDK.
I set everything up, But then I realized that the files I want to cast must be online (using URL) and I can't use my phone local files.
Does anyone know how to use local files in the Mediainfo.builder(..)?
Even a way to cast only the app's audio will help.
Thanks.

A: You need to include a small web server in your application and serve the media that you are interested within that web server. Then communicate with your receiver and send the URL of the media (that is being served through your embedded web server) to your receiver so it can play that. Since media it is being served from your mobile device, your web server needs to stay up for the whole duration of media.


text:
Q: How to choose an area for color picker in Paint.Net This is quite beginner question. I want to choose right color of some area because the thing i want to get color is not homogeneous area. How can i choose some area with color picker in paint.net ?

A: Here is my trick that works, some of the time, in these cases:

*

*Using lasso selection or magic wand (playing with the tolarance) I select an existing area with the color area that I want. (It doesn't need to be perfect, but preferably bigger than the area you are looking to fill).

*CTRL+C (copy) the selected area.

*Create a new layer.

*Paste the selected area into the new layer.

*Remove the areas until it looks like it blends well. Blurring the whole layer also help get rid of some of the pixelation difference between layers.

*(Optional) Merge the layers once you have something you like.

I know this is considerable more work and is more of an art than a science, but it has worked for me in the past.


text:
Q: Misalignment of summary data in my Activity Questions sub-menu Android1 phone in "full site" view:
The whole line summarising a question in my Activity Questions page is misaligned and nudged to the left when that question's title goes on to a second line.
(Niether changing to desktop view nor dis/enabling responsiveness makes any difference.)
1 Android v.11 Galaxy XCover Pro


text:
Q: SoapUI/maven: No HTML report I have SoapUI project, which I run via maven.
I want to make html report after each running. I want all errors to be in the report if they occurred.
I made following POM file for all this this:
        <?xml version="1.0" encoding="UTF-8"?>
    `enter code here`<project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <groupId>com.smartbear.samples</groupId>
        <artifactId>soapui-maven3-plugin</artifactId>

        <packaging>jar</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>Maven 3 SoapUI Sample</name>
        <url>http://maven.apache.org</url>

        <repositories>
            <repository>
                <id>repository.jboss.org-public</id>
                <name>JBoss.org Maven repository</name>
                <url>https://repository.jboss.org/nexus/content/groups/public</url>
            </repository>
        </repositories>

        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>
        </dependencies>

        <pluginRepositories>
            <pluginRepository>
                <id>smartbear-sweden-plugin-repository</id>
                <url>http://www.soapui.org/repository/maven3/</url>
            </pluginRepository>
        </pluginRepositories>

        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>3.3</version>
                </plugin>
                <plugin>
                    <groupId>com.smartbear.soapui</groupId>
                    <artifactId>soapui-maven-plugin</artifactId>
                    <version>5.1.2</version>

                    <dependencies>
                        ...some dependencies

                    </dependencies>

           <configuration>
                        <projectFile>${project.basedir}/test-project.xml</projectFile>
                        <outputFolder>${project.basedir}/target/surefire-reports</outputFolder>
                        <junitReport>true</junitReport>
                        <exportAll>true</exportAll>
                        <printReport>true</printReport>
              </configuration>

                    <executions>
                        <execution>
                            <id>1st project </id>
                            <phase>test-compile</phase>
                            <goals>
                                <goal>test</goal>
                            </goals>
                        </execution>
                    </executions>

                </plugin>
            </plugins>
        </build>

        <reporting>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-report-plugin</artifactId>
                    <version>2.18.1</version>
                </plugin>
            </plugins>
        </reporting>
    </project>

But after run project via mvn - no html report, just .txt and .xml files in /surefire-reports folder.
What I should fix in my POM?
Thanks

A: From documentation:

reportFormat : Sets formats for created report. Pro only.


text:
Q: How to get events from calendar for particular week in android? I want to display the events for only one week in the listView,but I got all the events and it is displaying  in the listview.
I am using this code to get the events for particular date ,but is not getting any events from calendar.The event count is 0.I am struct with this problem! How to get events for particular date or week?
public class Meeting extends Activity {
    public ConferenceAdapter adapter;
    ListView meetingListView;
    static Cursor cursor;
    private  String description = null;
    private  String where = null;
     public String[] number;
    static List<GoogleCalendar> gCalendar = null;
    private static String startString;
    private static String endString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ec_meeting);
        adapter = new ConferenceAdapter(this);
        readCalendar(this);
        meetingListView = (ListView) findViewById(R.id.meetinglistView);
        meetingListView.setAdapter(new MeetingListViewAdapter(Meeting.this, adapter, gCalendar));
        meetingListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
                TextView descriptionId1 = ((TextView) view.findViewById(R.id.descriptionmeeting));
                TextView where=((TextView) view.findViewById(R.id.wheretextView));
                TextView tittle = ((TextView) view.findViewById(R.id.titlemeeting));
                Meeting.this.where=where.getText().toString();
                description = descriptionId1.getText().toString();

                StringBuffer numbers =new StringBuffer();
                String a=Meeting.this.where.replaceAll("-","").replaceAll(" ", "").replaceAll("\\(","").replaceAll("\\)","")+description.replaceAll("-","").replaceAll(" ", "").replaceAll("\\(","").replaceAll("\\)","");
                if(a.isEmpty()){
                    Toast.makeText(getApplicationContext(),"Sorry no conference numbers found", Toast.LENGTH_LONG).show();
                }else{
                Pattern p = Pattern.compile("[0-9]+[0-9]");
                        Matcher m = p.matcher(a);
                        while (m.find()) {
                              Meeting.this.addComma(numbers,m.group().toString());
                        }
                        number = numbers.toString().split(",");
                        Intent intent = new Intent(Meeting.this,EcConferenceNumber.class);
                        intent.putExtra("strings", number);
                        startActivity(intent);
                        finish();
                                    }
            }
        });
    }

public void addComma(StringBuffer updatedString,String value){
    if(updatedString.length() >0 && updatedString != null ){
        updatedString.append(",");
    }
    updatedString.append(value);
}
    public static void readCalendar(Context context) {

        ContentResolver contentResolver = context.getContentResolver();

        Calendar c_start = Calendar.getInstance();
        c_start.set(2014,2,4,0,0); //Note that months start from 0 (January)
        Calendar c_end = Calendar.getInstance();
        c_end.set(2013,2,11,0,0); //Note that months start from 0 (January)

        String selection = "((dtstart >= "+c_start.getTimeInMillis()+") AND (dtend <= "+c_end.getTimeInMillis()+"))";

        String[] selectionArgs = new String[] {startString, endString};
        cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"),
                (new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation"})
                ,null,selectionArgs,selection);

        gCalendar = new ArrayList<GoogleCalendar>();
        try {
            System.out.println("Count=" + cursor.getCount());
            if (cursor.getCount() > 0) {
                System.out.println("the control is just inside of the cursor.count loop");
                while (cursor.moveToNext()) {
                    GoogleCalendar googleCalendar = new GoogleCalendar();
                    gCalendar.add(googleCalendar);
                    int calendar_id = cursor.getInt(0);
                    googleCalendar.setCalendar_id(calendar_id);
                    String title = cursor.getString(1);
                    googleCalendar.setTitle(title);
                    String description = cursor.getString(2);
                    googleCalendar.setDescription(description);
                    String dtstart = cursor.getString(3);
                    googleCalendar.setDtstart(dtstart);
                    String dtend = cursor.getString(4);
                    googleCalendar.setDtend(dtend);
                    String eventlocation = cursor.getString(5);
                    googleCalendar.setEventlocation(eventlocation);

    }
            }
        } catch (AssertionError ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// inner class for setting the home screen value to the list view
class MeetingListViewAdapter extends BaseAdapter {
    private List<GoogleCalendar> calendars = null;
    LayoutInflater inflater = null;
    public MeetingListViewAdapter(Activity activity, ConferenceAdapter adapter, List<GoogleCalendar> gCalendar) {
        this.calendars = gCalendar;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return calendars.size();
    }
    @Override
    public Object getItem(int position) {
        return position;
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.calendar_events, null);
        TextView titleNameTV = (TextView) vi.findViewById(R.id.titlemeeting);
        TextView timeTV = (TextView) vi.findViewById(R.id.profileStepCountTV);
        TextView whereTv=(TextView) vi.findViewById(R.id.wheretextView);
        TextView descriptionTV = (TextView) vi.findViewById(R.id.descriptionmeeting);
        GoogleCalendar calendar = calendars.get(position);
        titleNameTV.setText(calendar.getTitle());
        descriptionTV.setText(calendar.getDescription());
        whereTv.setText(calendar.getEventlocation());
        return vi;
    }

}

Any answer will be helpfull for me to proceed.

A: Replace this code :
ContentResolver contentResolver = context.getContentResolver();

        Calendar c_start = Calendar.getInstance();
        c_start.set(2014,2,4,0,0); //Note that months start from 0 (January)
        Calendar c_end = Calendar.getInstance();
        c_end.set(2013,2,11,0,0); //Note that months start from 0 (January)

        String selection = "((dtstart >= "+c_start.getTimeInMillis()+") AND (dtend <= "+c_end.getTimeInMillis()+"))";

        String[] selectionArgs = new String[] {startString, endString};
        cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"),
                (new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation"})
                ,null,selectionArgs,selection);

With this:
Uri l_eventUri;
    Calendar calendar = Calendar.getInstance();
    if (Build.VERSION.SDK_INT >= 8) {
        l_eventUri = Uri.parse("content://com.android.calendar/events");
    } else {
        l_eventUri = Uri.parse("content://calendar/events");
    }
    ContentResolver contentResolver = context.getContentResolver();

    String dtstart = "dtstart";
    String dtend = "dtend";

    String[] l_projection = new String[] { "title", "dtstart", "dtend" };

    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
    // Date dateCC = formatter.parse("04/27/2013");
    Date dateCC = formatter.parse("11/13/2013");
    calendar.setTime(dateCC);

    long after = calendar.getTimeInMillis();

    SimpleDateFormat formatterr = new SimpleDateFormat("MM/dd/yy hh:mm:ss");

    Calendar endOfDay = Calendar.getInstance();
    Date dateCCC = formatterr.parse("17/13/2013 23:59:59");
    // Date dateCCC = formatterr.parse(startDate + " 23:59:59");
    endOfDay.setTime(dateCCC);

    cursor= contentResolver.query(l_eventUri, new String[] { "title",
            "dtstart", "dtend" }, "(" + dtstart + ">" + after + " and "
            + dtend + "<" + endOfDay.getTimeInMillis() + ")", null,
            "dtstart ASC");


text:
Q: How to raise a LaTeX warning from within Lua code? I want to raise a warning from within Lua code. With advice from the LuaTeX wiki and LaTeX 2 for class and package writers, I arrived at the following (working) solution:
\documentclass{article}
\begin{document}
Foo
\directlua{
myvar = "\noexpand\\PackageWarning{mypackage}{Hello, I am a warning.}"
tex.print(myvar)
}
\end{document}

This seems unnecessarily complex, considering that raising an error is as easy as:
\directlua{
tex.error("Hi, I'm an error!")
}

While I'm aware that tex.error is a generic TeX error and the warning I'm producing is a package-specific warning, I still think for both generic LaTeX warnings (if that exists?) and package-specific warnings (as well as package-specific errors, probably), there should be an easier way. Is there one?

A: Someone who is more familiar with Lua will almost certainly have better ideas...
egreg's idea from the comments makes things slightly easier: consider using the [[...]] string syntax so you don't need to escape the string (but there will still be issues if the string itself contains a ]] etc), and use eTeX's \unexpanded so you don't need to worry so much about putting \noexpand everywhere. See also some of the suggestions about \directlua on a different question.
As I previously mentioned in a comment, bypassing/emulating the LaTeX commands for this is probably not a good idea. LaTeX's commands for this are slightly more complicated than you might first think, and might get patched/hooked into. Even rewriting LaTeX in Lua (replacing eg \PackageWarning with something that invokes a Lua script/function) wouldn't necessarily help in the latter situation.
I think the best you could do would be to write your own Lua function that invokes LaTeX's \PackageWarning, taking care to escape parameters etc as appropriate. (Sorry, I'm not proficient enough to attempt that.)
Compare the terminal output from the following:
\documentclass{article}
\PackageWarningNoLine{mypackage}{Hello, I am a warning}
\PackageWarning{mypackage}{Hello, I am a warning}
\directlua{
texio.write_nl("term and log", [[\unexpanded{Package mypackage Warning: Hello, I am a warning.}]]);
tex.print([[\unexpanded{\PackageWarning{mypackage}{Hello, I am a warning}}]]);
}

\begin{document}
\end{document}

I have used "term and log" here because (as egreg explained), LaTeX normally writes to an \@unused stream that is never open, so the output appears both on the terminal and in the log file.
The output is
Package mypackage Warning: Hello, I am a warning.

Package mypackage Warning: Hello, I am a warning on input line 3.

Package mypackage Warning: Hello, I am a warning.

Package mypackage Warning: Hello, I am a warning on input line 1.

Note also that the line numbers from the Lua version are wrong, even when the real \PackageWarning command is invoked.
For reference, some relevant definitions from latex.ltx:
\def\set@display@protect{\let\protect\string}
\def\@spaces{\space\space\space\space}
\ifnum\inputlineno=\m@ne
  \let\on@line\@empty
\else
  \def\on@line{ on input line \the\inputlineno}
\fi
\DeclareRobustCommand{\GenericWarning}[2]{%
   \begingroup
      \def\MessageBreak{^^J#1}%
      \set@display@protect
      \immediate\write\@unused{^^J#2\on@line.^^J}%
   \endgroup
}
\def\PackageWarning#1#2{%
   \GenericWarning{%
      (#1)\@spaces\@spaces\@spaces\@spaces
   }{%
      Package #1 Warning: #2%
   }%
}
\def\PackageWarningNoLine#1#2{%
   \PackageWarning{#1}{#2\@gobble}%
}


text:
Q: Php Mysqli_fetch_assoc Error : "Warning: Illegal string offset 'name' in"
Warning: Illegal string offset 'name' in C:\xampp\htdocs\connection\index.php on line 31
  1",

Please can anyone help me.
<?php

include('config.php');

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_assoc($result);

?>

and in Body tag
<?php
foreach ($rows as $row) {
   echo $row['name'];
}?>

A: You should use mysqli_fetch_all() here to get all rows within $rows at once.
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn);
$rows = mysqli_fetch_all($result);

echo "<pre>";
print_r($rows); // Check your result

A: you can store the results in array and use it in the body as follow:
<?php

include('config.php');

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);

$rows = array();

while($row = mysqli_fetch_assoc($result)){
    $rows[] = $row;
}

and in Body tag
<?php
foreach ($rows as $row) {
 echo $row['name'];
}?>


text:
Q: strange Train and test set are not compatible error in weka I have read many solution about this error. But my problem is definitely different from the others: I have a "train" dataset(arff) and a "test" dataset(arff), both these two arff have an attribute "id"(string). It works well if I 'remove' "id" of these two arff at the same time(if I don't remove the id in "test" I will get an error); what confuse me is that my friend can do it by remove only the "id" in "train", so his output will contains the "id".
(since he didn't remove the "id" in the "test", the number of attribute will not be the same, and this is against what I read that the number of attribute should be exactly the same).
I really need an output that can contain the "id".
Maybe I did something wrong with the "remove"? I read somewhere said that the test feature may be superior to that of train. And also a paragraph talking about how to remove:"Instead of using a nominal ID attribute, declare it as STRING
attribute. With this you don't have to declare each possible value
like with NOMINAL attributes and it therefore doesn't matter what
strings are used in the test set that you're trying to use the trained
model on. In order to be able to work with this STRING ID attribute
you have to use the FilteredClassifier in conjunction with the Remove
filter (package weka.filters.unsupervised.attribute) and your original
base classifier. This setup will remove the ID attribute for the
learning process (i.e., the base classifier), but you'll still be able
to use it outside for tracking instances. "
http://weka.8497.n7.nabble.com/use-saved-model-td22857.html
Anyone have an idea?
Any help will be appreciated.
my 2 arff, left: train; right: test

left: output of myfriend with id such as test_subject1005 ; right: my output

A: Finally I got my solution. Just click directly the "supplied test set" and in the prompt interface click "Yes". That all! (It seems that I did not see this prompt before, so I did not try)


text:
Q: Stop Excel From Automatically Creating a Table When Mapping XML Elements When I drag a single-node from //root/node onto the spreadsheet a table is not automatically created and I get the drop-down option to place the heading on the left or top etc.
However, when I drag a single-node from //root/element/child/grandchild a table is automatically created, even though the single node (the grandchild) has no other child nodes. (However, child nodes do exist for other grandchildren under the child).
Given the way data is displayed in the schema I would like to stop the table from automatically creating so I can lay out the nodes I need by row, by dropping them in one-by-one underneath each other.
For illustration
/CoPolicy/CoEffectiveDt and /CoPolicy/CoExpirationDate when dropped in Excel shows like this:

However, /CoPolicy/CoLobs/CoLob/GLPolInput/GlEachOccLmt (et. al.) shows like the below even though they have only 1 item each and will always have only 1 item.

How can I get the 2nd example to stop automatically creating the table and to allow me to place each single-node in a row format like example 1? All my tricks have failed so far.


text:
Q: The matrix analogue of the Theorem about diagonalizable operators - Linear Algebra by Hoffman and Kunze, page 187 Here is the theorem and its "matrix analogue"  :
First of all, does the formulation of $X$'s follow from the fact that $T(X) = cX$ iff $AX = cX$, where $c$ is a characteristic value of $T$ and $A$ is the representative matrix of $T$? If so, I guess this is true only when $A$ represents $T$ relative to the standard basis of $V$ and $V=R^n$. Do I get this right?
Second, what is the relationship between the matrix $P$ and the similar matrices of $A$? I mean, what is the motivation for the construction of $P$? I think the writer's manner of telling is not explicit here.

A: Yes, he's switching from the case of a linear transformation that might not be a matrix to a linear transformation that does operate on a set of vectors in the standard way by matrix multiplication. For some reason books use letters near the end of the alphabet (often $S$, $T$) for the former and letters near the beginning of the alphabet (often $A$, $B$) for the latter.  So the "column matrices" (most people would call these "column vectors" or just "vectors") $X$ for which $(T - c_i I)X = 0$ in the theorem become, after taking $T = A$, vectors $X$ for which $(A - c_i I) X = 0$ which as you note is the same condition as $AX = c_i X$.  (Separately, what he calls "characteristic values" are more commonly called "eigenvalues" these days, and the nonzero vectors $X$ for which $AX = c_iX$ are called "eigenvectors."  I will do this below, but it's exactly the same notion as what he's talking about in different terminology.)
Regarding the second part of the question, it really comes down to the relationship between matrices as formal objects and their properties as linear transformations.  When acting on the standard basis, any matrix $P$ can be thought of as a linear transformation sending the $i$th standard basis vector $e_i$ to the $i$th column of $P$ (call it $v_i$).  To repeat the essential point, the statements that "the $i$th column of $P$ is the vector $v_i$" and "$Pe_i = v_i$" are equivalent.  This is the heart of the matrix-theoretic aspect of the problem.  It might be the definition of matrix multiplication, or it might be a consequence of it, depending upon how your book has set this up.
So now if $v_i$, the $i$th column of $P$, was chosen to be an eigenvector of $A$ corresponding to the eigenvalue $c_i$ (as was done when the author constructed $P$ by making eigenvectors of $A$ for its columns) then you know what $A$ does to $v_i$: we have $A v_i = c_i v_i$.  And if $P$ is invertible, what would $P^{-1}$ do to that vector?  From $P e_i = v_i$ you can deduce $e_i = P^{-1} v_i$, so you know that $P^{-1}(A v_i) = P^{-1}(c_i v_i) = c_i P^{-1} v_i = c_i e_i$.
So the composite linear transformation $P^{-1} A P$ sends $e_i$ to $v_i$ (via $P$), then $v_i$ to $c_i v_i$ (via $A$), and then $c_i v_i$ to $c_i e_i$ (via $P^{-1}$).  And there's only one matrix that sends $e_i$ to $c_i e_i$ for all $i$, namely, the diagonal matrix with the list of numbers $c_i$ down the diagonal.
There's a separate question: if you weren't into matrix diagonalization in the first place, how would it occur to you to construct the matrix $P$ and even think to perform those calculations about $AP$ or $P^{-1} AP$.  I don't have a good answer, except that once you sit down long enough with the interaction between function composition and matrix multiplication, it seems like a very good or even natural idea.  And at one time it was not evident to anybody that it would be helpful to think in terms of matrix algebra at all.  We can benefit from the fact that a lot of this has been solved by others, and we can just come in later and understand what they've done. It really does fit together.


text:
Q: how to add button value explicitly to request in jsp javascript i am trying to pass button value from jsp to servlet in struts framework while form is being disabled on click the search button..i am able to get all the value except search button value. its showing null for search button Please suggest how to handle it   :)  ??
Reply please

A: The browser will only send the value of the button if the user clicked that button when submitting the form.  If you need the value on the server regardless of whether the user clicked the button, try putting it in a hidden field instead.


text:
Q: Replace values in list while keeping the original I am starting in python and I have this little problem, I have 2 lists and I want to switch the 2 middle values to create 2 more list and have 4 in total, like this:
p1=[3, 5, 2, 1, 4, 6]
p2=[5, 1, 3, 6, 2, 4]
s1=[3, 5, 3, 6, 4, 6]
s2=[5, 1, 2, 1, 2, 4]

I made this code:
p1=[3, 5, 2, 1, 4, 6]
p2=[5, 1, 3, 6, 2, 4]
s1=p1
s2=p2

for i in range(2,4):
    s1[i]=p2[i]
    s2[i]=p1[i]

print(s1)
print(s2)

The result is wrong, seems that 'p' and 's' are linked, how can i change it?:
[3, 5, 3, 6, 4, 6]
[5, 1, 3, 6, 2, 4]

A: When you are doing this:
s1=p1

You are saying: s1 is a pointer to p1, if you modify p1 you are also modifying s1

*

*You can use the builtin list.copy() method (available since Python 3.3)

*You can slice it: new_list = old_list[:]
there are multiple ways of coping values of list, take a look at:
List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

A: copy() is all you need:
p1=[3, 5, 2, 1, 4, 6]
p2=[5, 1, 3, 6, 2, 4]
s1=p1.copy()
s2=p2.copy()

for i in range(2,4):
    s1[i]=p2[i]
    s2[i]=p1[i]

print(s1)
print(s2)


text:
Q: How can i optimize this c# code? I have converted my Datatable to json string use the following method...
public string GetJSONString(DataTable Dt)
{
    string[] StrDc = new string[Dt.Columns.Count];
    string HeadStr = string.Empty;
    for (int i = 0; i < Dt.Columns.Count; i++)
    {
        StrDc[i] = Dt.Columns[i].Caption;
        HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
    }
    HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
    StringBuilder Sb = new StringBuilder();

    Sb.Append("{\"" + Dt.TableName + "\" : [");
    for (int i = 0; i < Dt.Rows.Count; i++)
    {
        string TempStr = HeadStr;
        Sb.Append("{");
        for (int j = 0; j < Dt.Columns.Count; j++)
        {
            if (Dt.Rows[i][j].ToString().Contains("'") == true)
            {
                Dt.Rows[i][j] = Dt.Rows[i][j].ToString().Replace("'", "");
            }
            TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString());
        }
        Sb.Append(TempStr + "},");
    }
    Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
    Sb.Append("]}");
    return Sb.ToString();
}

Is this fair enough or still there is margin for optimization to make it execute faster.... Any suggestion...

A: There may well be ways of getting it to execute faster - but do you have any indication that you need it to execute faster? Do you have a good reason to believe this is a significant bottleneck in your code? If so, benchmark the code with some real data and profile the routine to work out where the time is going.

A: Before asking if you can optimise it to make it execute faster, the first question you need to ask yourself is, does it run fast enough for me? Premature optimisation is the curse of all of us (I know I've done it!). You could spend hours trying to micro-optimise this code, which might take it from taking, for example, 20ms to execute down to 15ms. Yes that'd be a reduction of 25%, but would 5ms really be worth 2 hours of your time? More importantly, would it provide enough of a benefit to your end users to warrant it?
Have you considered using the JsonSerializer from "Newtonsoft"? This may well be "quick enough", is fairly widely used and is thus more likely to be correct overall than anything I, or you, can write first time round.
Purely from a readability perspective (that may also allow the C# compiler / CLR to improve thing for you) you could consider changing long bits of string concatenation such as:
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";

To:
HeadStr += string.Format("\"{0}\" : \"{0}{1}¾\",", strDc[i], i);

But for any changes you do make. Measure, Rinse, Repeat =)

A: You could tidy up some bits:

*

*Use string.Format() to avoid long x + y + z sequences. This may or may not make things faster (it would be marginal either way).

*You usually don't need .toString() when concatenating.

You could also pass in the StringBuffer to be populated, so that the caller might have the opportunity to bundle up several such operations into a single StringBuffer.
These suggestions are focused more on tidiness than performance, which I think should be the real focus unless this code is presenting as a bottleneck in your profiling.

A: Why do you think it needs optimization? Is it really slow on some DataTables?
I'd just serialize DataTable with something like newton JSON serializer, if it's serializable at all.

A: Refactor your code, use a tool like ReSharper, JustCode etc to tidy it up a bit. Extract methods and use individual tests ( Test Driven Development-ish ) to find bottlenecks in your code and then tweak those.
But your first step should be: Refactor!

A: The problem with the code isn't speed, but that it's not cleaned up. I've done some clean-up, but you could probably do even more:
public string GetJSONString2(DataTable table)
{
    StringBuilder headStrBuilder = new StringBuilder(table.Columns.Count * 5); //pre-allocate some space, default is 16 bytes
    for (int i = 0; i < table.Columns.Count; i++)
    {
        headStrBuilder.AppendFormat("\"{0}\" : \"{0}{1}¾\",", table.Columns[i].Caption, i);
    }
    headStrBuilder.Remove(headStrBuilder.Length - 1, 1); // trim away last ,

    StringBuilder sb = new StringBuilder(table.Rows.Count * 5); //pre-allocate some space
    sb.Append("{\"");
    sb.Append(table.TableName);
    sb.Append("\" : [");
    for (int i = 0; i < table.Rows.Count; i++)
    {
        string tempStr = headStrBuilder.ToString();
        sb.Append("{");
        for (int j = 0; j < table.Columns.Count; j++)
        {
            table.Rows[i][j] = table.Rows[i][j].ToString().Replace("'", "");
            tempStr = tempStr.Replace(table.Columns[j] + j.ToString() + "¾", table.Rows[i][j].ToString());
        }
        sb.Append(tempStr + "},");
    }
    sb.Remove(sb.Length - 1, 1); // trim last ,
    sb.Append("]}");
    return sb.ToString();
}

A: I would suggest a different solution,if you are using .net 3.0 or 3.5
instead of doing this

*

*Convert datatable into xml

*use xmlserializer to convert the xml to your domain object

*Using JavaScriptSerializer(System.Web.Extensions.dll) to serialize the domain object to json string.


text:
Q: Tom can choose from $4$ soups, $5$ salads and $4$ drinks for his lunch. How many different combinations of a soup, a salad, and a drink can he make? Tom can choose from $4$ soups, $5$ salads and $4$ drinks for his lunch.  How many different combinations of a soup, a salad, and a drink can he make?
Any help is appreciated.
Combinations or Permutations?

A: if Tom wants one kind of soup with one kind of salad and one kind of drink then he has :
$4$ soups * $5$ salads * $4$ drinks $=$ $80$ different combinations


text:
Q: php - checking whether a variable is set/ is true/ exists In my code I am checking whether variables exist. But it is not turning out the way I expect it.
This is what I'm trying to do:

*

*Retrieve $result from database.

*Execute a block of code only if a result has been extracted (otherwise do nothing/skip over/move forward).

I used if(isset($result)) but it doesn't seem to be working, looks like the if is being executed, even though it shouldn't when there is no data in $result. (but with problems because there is no actual $result variable to use in this block)

A: Doesn't just if($result) work for you? If you have error reporting showing E_NOTICEs, then try if(isset($result) && $result)

A: Depending on how you are executing your query, there's a possibility you should be using empty() in place of isset().
From the documentation:

isset
Determine if a variable is set and is not NULL.
empty
Determine whether a variable is considered to be empty.

For example:
$var = '';

isset($var) would return true as it has been set, but empty($var) would return false because its value is an empty string.

A: Isset only works for non instantiated variables. When you set $result to the db response you are actually setting the variable.
You could instead use mysql_fetch_assoc ( resource $result ) or mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] ) depending on what you want to do. Both of those functions will return false if there is not a response.
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
http://www.php.net/manual/en/function.mysql-fetch-array.php

A: If you use something like mysql_query it will return a resource, or false on error. That means it will always be set.

A: To check if there is any data extracted, use this :
$connect = mysql_connect("127.0.0.1",$sql_username,$sql_password);
$data = mysql_query($sql_query,$connect);
$result = mysql_fetch_array($data);
if($result) { ... }


text:
Q: Android: where are downloaded files saved? I am trying to develop a "document manager"
I have the necessity of accessing the files downloaded from the internet, from Gmail, for other mail clients, from other internet sources...
I would like to understand where these files are stored exactly on Android:
1- if there is an SD
2- if there is no SD Card
so that I can show them to the user in my App at any time.
Any help very much appreciated.

A: Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard (or some variation of that name) which is usually symlinked to to a directory in /storage like /storage/sdcard0 or /storage/0  sometimes the emulated storage is mounted to /sdcard and the actual path is something like /storage/emulated/legacy. You should be able to use  to get the downloads directory. You are best off using the api calls to get directories.
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Since the filesystems and sdcard support varies among devices.
see similar question for more info how to access downloads folder in android?
Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard

A: In my experience all the files which i have downloaded from internet,gmail are stored in
/sdcard/download

on ics
/sdcard/Download

You can access  it using
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);


text:
Q: Scrolling a DetailViewer in SmartClient Using SmartClient:
I have a VLayout composed of a DetailViewer (that monitors selection changes in a ListGrid) and a HLayout (that holds some buttons).
Now, when the user selects rows in the ListGrid, the DetailViewer "grows" and creates a Scrollbar.
In consequence the bottom HLayout is also contained in the Scrollbar. I would like to avoid this. My intention is to have the bottom HLayout always visible (i.e. the Scrollbar would contain the DetailViewer only).
How can I do this?
(Also posted here.)

A: Set overflow:auto on the DetailViewer.

A: I am pursuing that there is only one VLayout and inside it there is one HLayout (with buttons) and a DetailViewer.
Now if you want your buttons to be always visible shift buttons on the top of VLayout and set overflow property as "visible" with some height say 50.  Now second child inside VLayout should be DetailViewer with overflow property as "auto", so if required DetailViewer will show scrollbars.
Secondly, you can switch the position of HLayout and DetailViewer but do not forget to set height and overflow properties.
Thanks
shaILU


text:
Q: What to do about mass down votes?
Possible Duplicate:
Mysterious downvotes (14 random downvotes in 5 minutes)

I just got four completely unrelated down votes to both questions and answers within two minutes and obviously no comments at all. This may be a coincidence but I don't think I have ever had that many votes on different questions in such a short timespan so I am inclined to think that this is not a coincidence.
Is there any way to limit that sort of behavior? I am not so much concerned with the rep loss. I can live with that, but the value of the voting system is reduced if people start using this as a tool of vengeance (or whatever it is).
This question seems to cover much of my concern, so I guess my question is simply: will this situation be detected and votes restored after a while? On of the answers seems to indicate that it will, but I can't seem to locate it in the FAQ.

A: Yes, SO already does that.
Check out Mysterious downvotes (14 random downvotes in 5 minutes) for an example in action
If there really is someone targeting you with mass down votes then the system will catch it.  The votes will disappear, your reputation will be restored.


text:
Q: MySQL query for showing only the max value length of each column I have a table with n columns and x rows.
I want to make a query to show a table with all columns and the max length value of that column (and the row id of that row with the max value length).
+--------+--------+----+
| column | length | id |
+--------+--------+----+
| a      |    123 |  1 |
| b      |    123 |  8 |
| c      |    123 |  6 |
| d      |    123 |  5 |
| e      |    123 |  3 |
+--------+--------+----+

a, b, c, etc. are the column names and length is the max length in that column and id is the row with the max value length of that column.
Something like this ? but then dynamicly for all columns:
SELECT MAX(LENGTH(`column_a`)) AS `length`, `id`
FROM `table` GROUP BY LENGTH(`column_a`)
ORDER BY LENGTH(`column_a`) DESC LIMIT 1

Like having the next query with two columns added (the max length and the row id)
SHOW COLUMNS FROM `table`

Maybe using also this query to fetch the column names of the particular table:
SELECT `column_name` AS `column`
FROM `information_schema`.`columns`
WHERE `table_name` = 'table'
AND `column_name` != 'id'
ORDER BY `ordinal_position`

Nearly there (thanks to Bill)... (only have to specify 'table') but now how to run _SQL al the same run...
SELECT CONCAT(GROUP_CONCAT(CONCAT('(SELECT \'', `column_name`,'\' AS `column`, LENGTH(`', `column_name`,'`) AS `length`, id ', 'FROM `', `table_schema`,'`.`', `table_name`,'` ORDER BY `length` DESC LIMIT 1)') SEPARATOR ' UNION ALL '), ';') AS _SQL
FROM `information_schema`.`columns`
WHERE `table_name` = 'table'
  AND `column_name` IN (
    SELECT `column_name`
    FROM `information_schema`.`columns`
    WHERE `table_name` = 'table'
    AND `column_name` != 'id'
    ORDER BY `ordinal_position`);

A: MySQL does not have any way to do what you want in a single query.  At the time you prepare a query, all references to columns must be fixed.
The best you can do is to use one query against INFORMATION_SCHEMA to produce a new dynamic SQL query which gets the information you want.
I tested this against MySQL 5.5.16:
SELECT CONCAT(GROUP_CONCAT(
  CONCAT('(SELECT \'',COLUMN_NAME,'\' AS `column`, LENGTH(`',COLUMN_NAME,'`) AS `length`, id ',
  'FROM `',TABLE_SCHEMA,'`.`',TABLE_NAME,'` ORDER BY `length` DESC LIMIT 1)')
  SEPARATOR ' UNION ALL '), ';') AS _SQL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (TABLE_SCHEMA, TABLE_NAME) = ('test', 'tt')
  AND COLUMN_NAME IN ('a', 'b', 'c');

This query produces the following output  (I added newlines for the sake of posting here):
(SELECT 'a' AS `column`, LENGTH(`a`) AS `length`, id
 FROM `test`.`tt` ORDER BY `length` DESC LIMIT 1)
UNION ALL
(SELECT 'b' AS `column`, LENGTH(`b`) AS `length`, id
 FROM `test`.`tt` ORDER BY `length` DESC LIMIT 1)
UNION ALL
(SELECT 'c' AS `column`, LENGTH(`c`) AS `length`, id
 FROM `test`.`tt` ORDER BY `length` DESC LIMIT 1);

The generated query returns the following result in my test:
+--------+--------+----+
| column | length | id |
+--------+--------+----+
| a      |     10 |  2 |
| b      |      9 |  1 |
| c      |      6 |  2 |
+--------+--------+----+

Note that this doesn't resolve ties.  If more than one row has the same longest string, it will report only one id, chosen arbitrarily.

Re your extra question:
You must execute these as two separate queries.  I said at the start of my answer that the column references must be fixed in the SQL string at the time you prepare your query.  You can't discover the columns dynamically and also query their data in the same query.

Re your comment:
The longest string returned by GROUP_CONCAT() is 1024 by default, which is only enough to generate this SQL query for 9 columns.  You can increase this limit:
SET group_concat_max_len = 1024*1024;

This increases the limit for the current database session only.  You can use SET GLOBAL ... to change it for all sessions.  If you want this to persist after restarting MySQL, set the value in your my.cnf file (no need to use SET GLOBAL in the config file).

A: If I understood what you need, something like this should work (tested on Mysql 5.1):
SELECT
    column, length, id
FROM
    (
     (SELECT 'a' AS column, CHAR_LENGTH(a) AS length, id
      FROM yourtable
      ORDER BY length DESC
      LIMIT 1)
     UNION
     (SELECT 'b' AS column, CHAR_LENGTH(b) AS length, id
      FROM yourtable
      ORDER BY length DESC
      LIMIT 1)
     UNION
     (SELECT 'c' AS column, CHAR_LENGTH(c) AS length, id
      FROM yourtable
      ORDER BY length DESC
      LIMIT 1)
     UNION
     (...)
) T

A: Solving this will be a bit tricky, so I am not going to write the exact SQL, but here is the general idea:

*

*Create a table variable to hold your results. It will have the same schema as you posted in your answer.

*Create another table variable to hold all of the column names you want to pivot on. You just need a table with a name column.

*Insert the column names into the temp table created in step 2:
insert into @TempTable (ColumnName)
select COLUMN_NAME from information_schema.columns where Table_Name = 'YourTable';

*Using a cursor, loop through each of the columns in the column name table variable.

*Within the loop, you are going to create and execute a dynamic SQL query, using the PREPARE STATEMENT function. Each iteration through the loop will insert one row into the result table for a single column name.
PREPARE STMT FROM @query;
EXECUTE STMT;
Here is a stab at the dynamic SQL that will need to be executed. The @columnName is the name of the variable from the loop.
declare @maxLength int;
select @maxLength =  max(length(@ColumnName)) maxlength from YourTable;
insert into @results (ColumnName, MaxLength, RowId)
select '@ColumnName', @maxLength, Id from YourTable where length(@ColumnName)) = @maxLength;

Alternatively, you can dump the data into Excel and use the pivot table feature :)

A: Try this:
SELECT
    length(concat('',a)) as maxlen,
    group_concat(if (length(concat('',a))=@maxlen_a,a,null)) as maxlenval
FROM
    (select @maxlen_a:=max(length(concat('',a))) from tablename) as aview,
    tablename
GROUP BY maxlen
HAVING maxlenval IS NOT null

UNION

SELECT
    length(concat('',b)) as maxlen,
    group_concat(if (length(concat('',b))=@maxlen_b,b,null)) as maxlenval
FROM
    (select @maxlen_b:=max(length(concat('',b))) from tablename) as bview,
    tablename
GROUP BY maxlen
HAVING maxlenval IS NOT null

... and so on for every column.
This also solves the problem of two different values of same length


text:
Q: Discrete Curve evolution algorithm i am trying to implement discrete curve evolution algorithm in c++ do any one help me with psudo code or c code or
some simple steps of your understanding

A: Discrete Curve Evolution is an algorithm to compute an everywhere convex curve from one that is concave.  It moves concave sections of the curve outward along their normal in discrete steps until all concavities are eliminated.  It is not a genetic algorithm, the term evolution refers to 'evolving' the position of the curve over time.
Having searched on this for quite some time the best source on the internet is here:
https://cis.temple.edu/~latecki/Software/Evo.zip
This is matlab code so it's not quite what you are looking for but you have three good options:

*

*Port it to C++ (usually not to hard with matlab as long as it doesn't use matrix prims.)

*Wrap the matlab code so you can call it from C (matlab provides libraries to do this)

*Compile it to an executable and call that from C (matlab also allows this)

Option 2 would require anyone that want's to run it to have a copy of the matlab dynamic library on their computer which may be undesirable.  I'm guessing option 3 would require this too, but I only have experience with options 1 and 2.  Porting matlab to c++ is usually not that bad; it depends on how much the code utilizes matrix primitives and matrix operations which are easy to use in matlab and hard to use in C++ (because they aren't built-in). Still, I'd recommend giving it the old college try!
If you're just looking for DCE, check out the file evolution.m.  That's the function that implements DCE.  The full skeleton pruning algorithm this comes from can only be described simply at a high level.  The individual steps and parts are QUITE complicated and DCE is only a small piece of that.
Hope this helps!  I will be working with this code myself so if I do end up using it in C++ in some way that might help you I will let you know.

A: I'm not exactly sure what you mean by Discrete Curve evolutionary algorithm, but if you mean a Symbolic regression algorithm, you can start by reading about symbolic regression (or genetic programming in general):
http://en.wikipedia.org/wiki/Symbolic_Regression
There's also some nice existing programs. The Eureqa one has an open API:
http://code.google.com/p/eureqa-api/


text:
Q: Press a button and do something based on your choosing in the dropdown menu? I tried with this, but it is not working, I believe the error is in around the if statement=>
import tkinter as tk

from docx import Document

HEIGHT = 500
WIDTH = 600

root = tk.Tk()
root.title("Generator")
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

#dropdown part
# Create a Tkinter variable
tkvar = tk.StringVar(root)
choices = { 'broker','consultant','recruit'}
tkvar.set('broker') # set the default option
popupMenu = tk.OptionMenu(root, tkvar, *choices)
popupMenu.place(x=260,y=95)

def helloCallBack():

   if tkvar == 'broker':
      document = Document()
      document.add_heading("broker")
      document.save('0034.docx')

button = tk.Button(text="Generate", font=40, command=helloCallBack)
button.place(x=230, y=380)

root.mainloop()

Yes well... this is my problem, when I open the document I see no changes, or no added heading... I would like to have the documents heading changed to what I choose in the dropdown. Can anyone help?
Kr.
Selfiatus1


text:
Q: Filesharing mac 10.6 with windows vista Ive followed all the tutorials on the net to no avail.
I can see my vista pc in finder on the mac but when I click on it tries to connect but fails. The same is true from vista, it can see the mac but i cant connect. Wont even offer a login box.
So I tried to troubleshoot by using a 3rd computer with xp. It joined the network and can access both the mac and vista on the same workgroup. Mac sees it and it shows under finder but i cant access it by clicking on the icon i have to access by using the ip of the xp machine...strange.
Ive turned off all my firewalls. The fact that xp can connnet to the others and vice versa boggles my mind why vista and mac cant connect directly.
Oh and pings indicates the same. I.e. xp has no problem but mac to vista and vice versa fails.
Can anyone help.


text:
Q: Is There a way to share data from one component to another component which are in different modules by using @Input decorator I have two different components in separate modules i am importing one module into another module and referring imported modules component html selector in the module's component, sample text is printing in <router-outlet> when i tried sending data using @Input decorator to the other component it is throwing an error saying
 Error: Template parse errors:
 Can't bind to 'themeingColors' since it isn't a known property of 'app-color-
 palette-container'. I got to know by the error that components should be under same module to get benefit by @Input
But my question is there a way we can achieve passing data by using @Input decorator even if the components are in different modules?

A: There are multiple ways of sharing data between components: Input/Output decors, shared service and passing the components as reference. If they are in separate modules(and if they are lazy loaded), you should use the shared service aproach. Where you instantiate a service on app initialization and use it as a global ''state'' container for such things as themes. But dont overuse it for everything cuz it get really messy.


text:
Q: Simpler way to count the number of duplicated rows in a text file I have a text file that looks like this:
abc
bcd
abc
efg
bcd
abc

And the expected output is this:
3 abc
2 bcd
1 efg

I know there is an existed solution for this:
sort -k2 < inFile |
awk '!z[$1]++{a[$1]=$0;} END {for (i in a) print z[i], a[i]}' |
sort -rn -k1 > outFile

The code sorts, removes duplicates, and sorts again, and prints the expected output.
However, is there a simpler way to express the z[$1]++{a[$1]=$0} part? More "basic", I mean.

A: More basic:
$ sort inFile | uniq -c
      3 abc
      2 bcd
      1 efg

More basic awk
When one is used to awk's idioms, the expression !z[$1]++{a[$1]=$0;} is clear and concise.  For those used to programming in other languages, other forms might be more familiar, such as:
awk '{if (z[$1]++ == 0) a[$1]=$0;} END {for (i in a) print z[i], a[i]}'

Or,
awk '{if (z[$1] == 0) a[$1]=$0; z[$1]+=1} END {for (i in a) print z[i], a[i]}'

A: If your input file contains billions of lines and you want to avoid sort, then you can just do:
awk '{a[$0]++} END{for(x in a) print a[x],x}' file.txt


text:
Q: React DnD in a Meteor app I am using react with my meteor app and I need to integrate this with a list of items.
There is a ItemList.jsx and a ItemRow.jsx since the item itself has text, links, images, ect.
ItemRow.jsx
    ItemRow = ReactMeteor.createClass({
        templateName: "ItemRow",

        propTypes: {
            item: React.PropTypes.object.isRequired,
            showPoolTitle: React.PropTypes.bool,
        },

        getInitialState: function() {
            return {
                editing: false,
                drop: this.props.item,
                pool: {},
            }
        },

        startMeteorSubscriptions: function() {
        Meteor.subscribe("ItemRow", this.props.item._id);
      },

        getMeteorState: function() {
        return {
          item: Items.findOne(this.props.item._id),
          pool: Pools.findOne(this.props.drop.poolId),
        };
      },

        toggleEditing: function() {
            this.setState({ editing: !this.state.editing });
        },

        render: function() {
            var content;
            if (this.state.editing) {
                content = <ItemRowEdit drop={this.state.item} done={this.toggleEditing}/>
            } else {
                content = <ItemRowShow pool={this.state.pool} item={this.state.item} edit={this.toggleEditing} showPoolTitle={this.props.showPoolTitle}/>
            }
            return (

                    {content}

            )
        },

    });

and ItemList.jsx
ItemList = ReactMeteor.createClass({
  templateName: "ItemList",

  propTypes: {
    items: React.PropTypes.object.isRequired
  },

  getInitialState: function() {
    return {
      items: this.props.items.fetch()
    }
  },

  render: function() {
    var items = this.state.items;

    return (

        {items.map(function(item) {
          return ( <ItemRow item={item}/> );
        })}

    );
  }

});

I am not using Meteor react for ItemList just yet but I want to be able to drag and drop reorder first so any help to get me on the right track is much appreciated!


text:
Q: Inconsistency with re.findall method I'm using regex to extract some pattern, however there seem to be findall method returns different results for same string and pattern at different times.
At first, it doesn't find any match object and returns empty list, then when I build the pattern object one group at a time (pattern object consist of three groups) and apply findall method at every time it returns true results.
And at the last step (which I would have same pattern as with the starting one) it returns expected results even though it is same pattern object as with the one it returned empty list
I'm not sure if I'm missing something, can someone address this mighty issue
I'm not well experienced with asking questions here on SO, if there is an unclear part please point out
In[98]: a[1]           # a string object from list "a"
Out[98]: 'c48: 1777'

In[99]: a_re= re.compile('r(c[0-9]+)(: )(.*)') # pattern object

In[100]: a_re.findall(a[1])
Out[100]: []

In[101]: a_re= re.compile(r'(c[0-9]+)')

Out[102]: a_re.findall(a[1])
Out[102]: ['c48']

In[103]: a_re= re.compile(r'(c[0-9]+)(: )')

In[104]: a_re.findall(a[1])
Out[104]: [('c48', ': ')]

In[105]: a_re= re.compile(r'(c[0-9]+)(: )(.*)')

In[106]: a_re.findall(a[1])
Out[106]: [('c48', ': ', '1777')]

A: It's just a minor typo, if you can even call it that. Put the r outside of the string like so:
a_re= re.compile(r'(c[0-9]+)(: )(.*)')

A: code:
import re

print(re.findall(r'(c[0-9]+)(: )(.*)','c48: 1777'))

output:
[('c48', ': ', '1777')]

Which reach the same result.


text:
Q: Is there a C++ way to invoke linux shell commands? In C there is popen() and system() to invoke external commands. Is there a more standardized way in C++ to do this using for instance STL and 'std::'?

A: No. it's the same as the C one.
#include <cstdlib> and then use std::system("whatever your command is").


text:
Q: Trimming a string until a value I ve got a column which has different sized strings, looking like:
abcd, efgh, ijkl2, 2345, xyzw

I need to trim it into 2 different columns, and get the string before the comma from right and then the other one, so I will have 2 other columns with:
2345    xyz

I ve tried to get only the first part of the string before the first comma:
RTRIM(LTRIM(RIGHT(A.[column],charindex(',',A.[column]+',')-1))) as 'aa'

RIGHT(A.[column], len(A.[column]) - charindex(',',A.[column])) as 'ab'

But I get it mixed, sometimes I get some of the values after the comma, but incomplete.
Any thoughts?
Thank you, I appreciate it.

A: you can use string_split if you are one sql server 2016...
try Something like this :
drop TABLE REC.TestTable;
CREATE TABLE REC.TestTable (id int identity, --Avoid using keywords for column names
                            str varchar(500));

GO

INSERT INTO REC.TestTable (str)
VALUES ('abcd, efgh, ijkl2, 123, ijk'),
       ('abcd, efgh, ijkl2, 4567, lmn'),
       ('abcd, efgh, ijkl2, 89, opqr')
;
GO

with tmp as (
select f1.*, f2.value, row_number() over(partition by id order by (select null)) position
from REC.TestTable f1 cross apply STRING_SPLIT(str, ',') f2
)
select f1.*, f2.value ValPos1, f3.value ValPos2, f4.value ValPos3, f5.value ValPos4, f6.value ValPos5
from REC.TestTable f1
left outer join tmp f2 on f1.id=f2.id and f2.position =1
left outer join tmp f3 on f1.id=f3.id and f3.position =2
left outer join tmp f4 on f1.id=f4.id and f4.position =3
left outer join tmp f5 on f1.id=f5.id and f5.position =4
left outer join tmp f6 on f1.id=f6.id and f6.position =5

A: Such string functions in SQL Server are really painful.  I like to use apply for such operations, because this makes it easier to keep intermediate results.
For this particular problem:
select v.str, v2.lastval, v3.secondlastval
from (values ('abcd, efgh, ijkl2, 2345, xyzw')) v(str) cross apply
     (select stuff(str, 1, len(str) - charindex(',', reverse(str)) + 2, ''),
             stuff(str, len(str) - charindex(',', reverse(str)) + 1, len(str), '')
             ) v2(lastval, rest) cross apply
     (select stuff(v2.rest, 1, len(v2.rest) - charindex(',', reverse(v2.rest)) + 2, ''),
             stuff(v2.rest, len(v2.rest) - charindex(',', reverse(v2.rest)) + 1, len(v2.rest), '')
             ) v3(secondlastval, rest);

Having said that, you should probably reconsider your data structure.  Storing lists of values in delimited strings is a poor data structure in SQL because SQL does not have very good string processing capabilities.  Instead, you should be using a junction/association table.


text:
Q: Firefox Temporarily Freezing on Most Web Page Load (NS_ERROR_OUT_OF_MEMORY) Frequently when I browse to a webpage in Firefox 3.6, the browser will freeze while loading (often the google analytics portion of a page). After about 15 seconds, it will give me the following message:
A script on the page may be busy, or it may have stopped responding. You can stop the script now, or you continue to see if the script will complete.

It then presents me with two options "Stop Script" and "Continue".
If I click "Stop Script", it presents the following message:
Error: Component returned failure code: 0x8007000e (NS_ERROR_OUT_OF_MEMORY)
[nsIXPCComponents_Utils.evalInSandbox]

I can then view the page as normal.
Does anyone have any ideas?
Thanks!
Jack

A: Clearly, a script associated with that web page isn't functioning well. Is it javascript, or something else? The error also isn't specific enough to identify exactly what is failing.
The NS_ERROR_OUT_OF_MEMORY weakly implies that the script is caught in an endless loop. (Each iteration of the loop takes another bit of memory, until the sandbox fills up.)
If you're familiar with scripting, you can get the Firebug plugin for Firefox. Firebug will allow you to examine and debug the script, and might lead to the specific error.
Good luck!
dafydd

A: Disable your Craigslist Addon. This worked for me.
I hope this helped.
D


text:
Q: Traefik v2 reverse proxy without Docker I have a dead simple Golang microservice (no Docker, just simple binary file) which returns simple message on GET-request.
curl -XGET 'http://localhost:36001/api/operability/list'

{"message": "ping 123"}

Now I want to do reverse proxy via Traefik-v2, so I've made configuration file "traefik.toml":
[global]
  checkNewVersion = false
  sendAnonymousUsage = false

[entryPoints]
    [entryPoints.web]
    address = ":8090"

    [entryPoints.traefik]
    address = ":8091"

[log]
    level = "DEBUG"
    filePath = "logs/traefik.log"
[accessLog]
    filePath = "logs/access.log"

[api]
    insecure = true
    dashboard = true

[providers]
  [providers.file]
    filename = "traefik.toml"

# dynamic conf
[http]
    [http.routers]
        [http.routers.my-router]
            rule = "Path(`/proxy`)"
            service = "my-service"
            entryPoints = ["web"]
    [http.services]
        [http.services.my-service.loadBalancer]
            [[http.services.my-service.loadBalancer.servers]]
                url = "http://localhost:36001"

Starting Traefik (I'm using binary distribution):
traefik --configFile=traefik.toml

Now dashboard on port 8091 works like a charm, but I struggle with reverse proxy request. I suppose it should look like this (based on my configuration file):
curl -XGET 'http://localhost:8090/proxy/api/operability/list'

But all I get it's just:

404 page not found

The question is: is there any mistake in configuration file or is it just a request typo?
edit:
My configuration file is based on answers in this questions:

*

*Simple reverse proxy example with Traefik

*Traefik v2 as a reverse proxy without docker
edit #2:
Traefik version info:
traefik version
Version:      2.4.9
Codename:     livarot
Go version:   go1.16.5
Built:        2021-06-21T16:17:58Z
OS/Arch:      windows/amd64

A: I've managed to find the answer.

*

*I'm not that smart if I've decided that Traefik would take /proxy and simply redicrect all request to /api/*. The official docs (https://doc.traefik.io/traefik/routing/routers/) says that (I'm quoting):

Use Path if your service listens on the exact path only. For instance, Path: /products would match /products but not /products/shoes.

Use a Prefix matcher if your service listens on a particular base path but also serves requests on sub-paths. For instance, PathPrefix: /products would match /products but also /products/shoes and /products/shirts. Since the path is forwarded as-is, your service is expected to listen on /products.

*I did not use any middleware for replacing substring of path

Now answer as example.
First at all: code for microservice in main.go file
package main

import (
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "{\"message\": \"ping 123\"}")
}

func main() {
    http.HandleFunc("/operability/list", handler)
    log.Fatal(http.ListenAndServe(":36001", nil))
}

Now, configuration file for Traefik v2 in config.tom file:
[global]
  checkNewVersion = false
  sendAnonymousUsage = false

[entryPoints]
    [entryPoints.web]
    address = ":36000"

    [entryPoints.traefik]
    address = ":8091"

[log]
    level = "DEBUG"
    filePath = "logs/traefik.log"
[accessLog]
    filePath = "logs/access.log"

[api]
    insecure = true
    dashboard = true

[providers]
  [providers.file]
    debugLogGeneratedTemplate = true
    # Point this same file for dynamic configuration
    filename = "config.toml"
    watch = true

[http]
    [http.middlewares]
        [http.middlewares.test-replacepathregex.replacePathRegex]
            # We need middleware to replace all "/proxy/" with "/api/"
            regex = "(?:^|\\W)proxy(?:$|\\W)"
            replacement = "/api/"

    [http.routers]
        [http.routers.my-router]
            # We need to handle all request with pathes defined as "/proxy/*"
            rule = "PathPrefix(`/proxy/`)"
            service = "my-service"
            entryPoints = ["web"]
            # Use of defined middleware for path replacement
            middlewares = ["test-replacepathregex"]

    [http.services]
        [http.services.my-service.loadBalancer]
            [[http.services.my-service.loadBalancer.servers]]
                url = "http://localhost:36001/"

Start microservice:
go run main.go

Start traefik:
traefik --configFile config.toml

Now check if microservice works correctly:

curl -XGET 'http://localhost:36001/api/operability/list'

{"message": "ping 123"}

And check if Traefik v2 does job well too:

curl -XGET 'http://localhost:36000/proxy/operability/list'

{"message": "ping 123"}


text:
Q: Add delay before pausing audio in jQuery I'm trying to fade in/out an audio file when the user hovers over a div.
The fade in works, but the audio is paused before the fade out is completed.Here is my current code:

$(function () {
    $('#playmusic').hover(
        function () {
            $('#music')[0].play();
            $('#music').animate({volume: 1}, 1000);
        },
        function () {
            $('#music').animate({volume: 0}, 1000);
            $('#music')[0].pause();
        }
    )
});

hover to hear audio

<audio id="music" preload="auto">
     <source src="https://upload.wikimedia.org/wikipedia/commons/e/ec/A_Tale_of_Distant_Lands.mp3" type="audio/mpeg">
</audio>

I think I need to add a .delay into my code so the audio is paused after the fade out occurs however the following is giving me an error:
$('#music').delay(1000).[0].pause();

Does anyone know where I'm going wrong?

A: If you want to delay the stop, can perform it with a setTimeout
Here is an example
setTimeout(function(){
   $('#music')[0].pause();
}, 1000);

The time is set in ms.
The delay function is used for jQuery effects including animations, to other thing better use setTimeout.

A: I recommend using the animation's complete callback to pause the audio. It fires after the animation, i.e. when the audio fade is complete.
One advantage of this method over using an independent timer is that the audio is paused as soon as the animation is done, regardless of the animation's duration.
Provide the callback function using this format:

.animate( properties [, duration ] [, easing ] [, complete ] )
complete
Type: Function()
A function to call once the animation is complete, called once per matched element.

Or, using an alternate format to specify options:

.animate( properties, options )

I also suggest using stop() to prevent queuing the animations. Otherwise, the accumulation of animations can get confusing when rapidly hovering on and off the trigger.
Here's a demonstration:

$(function() {

  let $music = $('#music');

  $('body').on('click', function() {
    $(this).addClass('clicked');
  });

  function playMusic() {
    $music
      .stop(true, false)
      .animate({
        volume: 1
      }, {
        duration: 1000,
        start: function() {
          this.play();
        }
      });
  }

  function pauseMusic() {
    $music
      .stop(true, false)
      .animate({
        volume: 0
      }, {
        duration: 1000,
        complete: function() {
          this.pause();
        }
      });
  }

  $('#playmusic').hover(
    playMusic,
    pauseMusic
  );

});
body {
  min-height: 100vh;
  transition: background-color 200ms;
}

body.clicked {
  background-color: #FFFFF5;
}

#playmusic {
  display: inline-block;
  padding: 0.25em 0.5em;
  background-color: #EEF;
  cursor: pointer;
  transition: background-color 200ms, opacity 200ms, margin-left 200ms;
  border-radius: 0.25em;
  visibility: hidden;
  opacity: 0;
  margin-left: -100%;
}

body.clicked #playmusic {
  visibility: visible;
  opacity: 1;
  margin-left: 0;
}

body.clicked #playmusic:hover {
  background-color: #DDFFDD;
}

Click the page first to interact with the document.

Hover to hear audio

<audio id="music" preload="auto" allow="autoplay" autoplay>
    <source src="https://upload.wikimedia.org/wikipedia/commons/e/ec/A_Tale_of_Distant_Lands.mp3" type="audio/mpeg">
</audio>


text:
Q: how to solve Kerio Control's Local Authority certificate issue with mobile applications? I'm using kerio control firewall in our company and as you know it has an option named:"Https decryption". As I want to track all of the data that users browse in the company, I have to turn it on.
I added the Local Authority certificate on all devices on the network and I have no problem tracking their browsing data.
My problem is that mobile applications like instagram, appstore and any other applications that use https for communication with their servers, does not work in our network.
When I turn https decryption OFF, these applications work perfectly, I would be happy to know the reason behind this and also a good solution for it.
Just to mention, I have imported kerio control's local authority certificate on mobile devices and turned on full trust as a root certificate option on both IOS & Android devices.

A: Many mobile apps are written to only accept a specific certificate authority, or even only a specific server certificate, as a security measure known as certificate pinning.
There is no workaround except for patching each app itself (e.g. removing pin-sets from the .apk manifest – there are several articles explaining how to do this, but they would need to be redone for every single app update), and after all, things like this are exactly what certificate pinning is meant to protect against.


text:
Q: In OS X how to avoid typing passwords twice if FileVault 2 is enabled? After erasing the startup volume with encryption enabled (FileVault 2) and restoring the previous backup, I found myself needing to type passwords twice: the first one is to unlock the drive and the second is to log in the system.
Is there a way to save one typing of the passwords? Automatic log-in?
Thanks!

A: In my case, parallels desktop was causing the issue (not kidding, see this post enter link description here). I uninstalled it and used Virtualbox instead…


text:
Q: How do I improve quality when using RMagick/ImageMagick to convert from SVG to PDF? I use Rubyvis to generate SVG plots, and then allow the user to save either to SVG directly, or to some other format using RMagick.
The SVG plots have a set size, which is specified in the SVG file. It seems to me, then, that it should be trivial to convert to a PDF of the same size.
Unfortunately, this appears not to be the case. I can produce a PDF in this manner, but it is much larger (dimension-wise) than the PDFs produced if I first open the SVG in inkscape and then print-to-file as a PDF.
Worse, the PDF image quality is terrible.
Am I missing some instruction for Magick? Here's the code:
image = Magick::Image::from_blob(svg_string_data) { self.format = 'SVG' }
image[0].format = 'PDF'
image[0].to_blob

I then write the value returned (the PDF blob) directly into a file.

A: The answer comes to you based on a tip from cptjazz on github.
First of all, the documentation for RMagick is often wrong. I doubt this is a version problem, because the ImageMagick-hosted docs are v2.12.0, and I'm using v2.13.1. Either way, here is what you need to know.
The docs claim you can use image[0]['pdf', 'use-cropbox'] = true, since true.to_s yields the String 'true'. In fact, it needs an explicit string, and the []= method takes only one key, not two.
I did not experiment with pdf:use-trimbox, mainly because I wanted an option that also works for postscript. For postscript, you should be able to amend it only slightly, and set ps:use-cropbox to 'true', but RMagick's docs are unclear as to how one may properly set the geometry on a PS, PS2, or PS3. (Normally in ImageMagick, one would set the density to '300x300' and the geometry to '24%', supposedly.) And for some reason, PS3-format output files do not scale as well as the PDFs produced by RMagick. But I digress.
Here is what I used for PDF:
image = Magick::Image::from_blob(svg_string) { self.format = 'SVG' }
image[0].format = 'PDF'
image[0]["use-cropbox"] = 'true'
image[0].to_blob

And here is what I used for PS:
image = Magick::Image::from_blob(svg_string) { self.format = 'SVG' }
page  = image[0].page.dup
image[0]["use-cropbox"] = 'true'
image[0].format = 'PS3'
image[0].density = '100x100'
image[0].page = page
image[0].to_blob

For some reason, setting a higher density makes the image smaller. Why that should be is a mystery.


text:
Q: Cannot deserialze the current JSON array into type I'm trying to deserialize following JSON data :
{
  "bids": [
    [
      "392031.00000000",
      "0.00254444"
    ],
    [
      "390000.00000000",
      "0.52917503"
    ],
     ......
    ],

   "asks": [
    [
      "392999.00000000",
      "1.00000000"
    ],
    [
      "393000.00000000",
      "0.31572236"
    ],
    .....
    ]
}

I've looked into similar question such as this one, but I'm not getting close result and also noticed that in that question the structure of JSON is not similar.
My code for deserialization is as below
public class OrderBookElement
{
    // I've also tried below commented code
    //[JsonProperty(PropertyName = "0")]
    //public double price { get; set; }

    //[JsonProperty(PropertyName = "1")]
    //public double volume { get; set; }

    List<double> values;
}
public class OrderBookResponse
{
    [JsonProperty(PropertyName = "bids")]
    List<OrderBookElement> bids { get; set; }
    [JsonProperty(PropertyName = "asks")]
    List<OrderBookElement> asks { get; set; }
}

Below is code that I use for deserialization
var ordBook = JsonConvert.DeserializeObject<OrderBookResponse>(jsonResponse);

This gives me error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RestAPI.OrderBookElement' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

A: The JSON you've shown would be represented by:
public class OrderBookResponse
{
    [JsonProperty("bids")]
    public List<List<string>> Bids { get; set; }

    [JsonProperty("asks")]
    public List<List<string>> Asks { get; set; }
}

The bids and asks properties in the JSON are each just an array of arrays of strings.
I'd suggest deserializing to a model which matches the JSON, then convert that into a more useful model separately. It may be possible to apply attributes to your class to persuade Json.NET to do what you want, but I tend to think that by the time there's a significant discrepancy (not just the property names), it's worth separating the two models out, one for serialization and one for use within the rest of your code.


text:
Q: Is it possible to generate a leveled character in borderlands 2? In borderlands 2 for steam,is it possible to generate a character at a specific level and story mission point for the standard multi-player campaign?
Reason: I played borderlands 2 some years ago fully by myself. Then I played it again with my brother. Now that I'm married I started playing it with my wife but we are proceeding slow. A friend then also got interested and wants to play with me and we work on catching up with my wife to play 3 of us. And now his girlfriend also wants to join and I'm really tired of playing the story from start. Is there a way for her to generate a character that is a good fit with ours? Means the levels and the story mission fit?
I noticed that the game files are all saved locally on the computer. So I guess it should be possible to manipulate them in a way that they think the character is a normal one?

A: Gibbed will help edit a character.
One way I got my wife's character to my level was to copy my save, then use Gibbed to change the character class. With a short amount of play, she got her character decked out in weapons she preferred.
There is also the option to start a character at level 30, if that would be easier than having to rely on an external program


text:
Q: Unable to access DOM elements of template in backbone View I have a view like this:
var InvoiceForm = Backbone.View.extend({
    template: _.template(addform),
    initialize: function () {
        this.$("#buyer").val("test");
    }
});

I have the template addform containing the buyer id element. This isn't setting the value. I know i am doing something stupid here :)

A: Backbone templates in Views aren't automatically rendered. In fact in the Backbone documentation, there are some examples how you could do that.
If you use templates in your view, which should be rendered on initialize you can write your code like this :
var InvoiceForm = Backbone.View.extend({
    template: _.template(addform),
    render: function() {
        this.$el.html(this.template());
        return this;
    },
    initialize: function () {
        this.render(); // Rendering your template in your this.el element
        this.$("#buyer").val("test"); // Setting the value of #buyer in your template
    }
});

You can later use this view like this:
var form = new InvoiceForm({ el: $("#wrapper_for_invoiceform") });

Check the demo in this fiddle : http://jsfiddle.net/hsn7J/

A: If you are trying to do this on a click event - to change to the 'test' value, you could do it with the following
initialize: function(){
            this.model.on('change', this.render, this);
        },

    render: function() {
            this.$el.html( this.template(this.model.toJSON()) );
            this.input = this.$('#buyer');
            return this;
        },

    events: {
     'click #buyer' : 'editValue',
    },

    editValue: function(){
        this.input.val("test");
    }


text:
Q: How to do a portable library properly in .NET c# I set my mind on creating a lib that i could use for different projects, including .net 4.5 console apps, windows store apps, windows phone 8. My lib are doing some socket programming, and if it was normal 4.5 i would use the TcpClient.
The first(Assumed) step would be to create a Portable Lib, but this ends quickly as TcpClient are not supported there.
What are the normal approach for creating such libraries? What would be my firsts step for creating a lib i can use for multiply targets?

A: Very well known issue.
There are couple of ways that you can get around that problem.

*

*Shared code files should be added a links in the relevant project. that way you can change is once and it will affect all the dependent projects. keep in mind that of course rebuilding all dependent project is a must in that case.
Right-click the dependent project, select Add->Existing Item - in the dialog form, drop down the Add button and select Add As Link.
You will have to use some C# Preprocessor Directives for distingushing between different platforms - for example, some namespaces and APIs could be different in Windows 8.

*Use partial classes and inheritance for extending types.
for example, let say that you have a type that one of it's methods should download a file from the internet and save it locally.
Let's assume that in Windows 8 and Windows Phone the API are different (they are actually), you can create the type with the private method deceleration in a common file, and create partial class that implement that method in every relevant project - one partial class for Windows Phone, and one partial class in Windows 8 and each will be built in it relevant context.
For more information about partial classes and methods, read here.
I hope that helps.
Anyway, specifically TcpClient that you've mentioned you want to use - If I remember correctly it is not supported in Windows Phone as all and not just in Portable Library :)

A: In the case of incompatible libraries (like TcpClient only available on x86) you should either; 1) find a different library that works on both devices or 2) find it's substitute for the other device and add some logic to make the proper code execute on the different devices.
In this case that isn't even relevant, portability is not possible. One device is x86, the other ARM. There is no way to make a library that works on both without separate builds. Because that's the case you may as well use compiler macros to dictate what gets build for each and then just use the TcpClient in the x86 version and the other library in the ARM version.


text:
Q: Flask uploading shapefiles into postgis I am trying to upload a shapefile into PostGIS. I am using Flask and have gotten the files from the user (.shp, .shx, .dbf and .prj) and saved them to temporary files before using PYSHP python library to access the shapes collection.
r = shapefile.Reader(tempfile_name + '.shp')
shapes = r.shapes()

What I want to do is combine the polygons in the shapes collection and add them to the database along with some other data as one record. Basically merging the polygons into a multipolygon. The relevant column of the PostGIS table is defined as:
footprint = db.Column(Geometry(geometry_type='MULTIPOLYGON', srid=27700))

I do not know how to proceed with the merging of the polygons and converting them to a format that can be written to the PostGIS database using SQLAlchemy and GeoAlchemy2. Advice on how to proceed would be gratefully received.
I have looked at geopandas and shapely but can seem to find the relevant information
I am using

*

*Flask 1.0.2

*Postgresql 9.6

*SQLAlchmey 1.2.7

*Geoalchemy2 0.4.2

Update 1.
Found a solution that seems to work, but it seems rather messy.
I loop through the shapes() of the shapefile.Reader and save each polygon to an array, before using cascaded_union of shapely library. Then use pygeoif library to convert the information to be saved in the postgis database.
poly = []
for shp in r.shapes():
  if shp.shapeType == 5:
    poly.append(shape(shp.__geo_interface__))
footprint_poly = cascaded_union(poly)

gshape = pygeoif.MultiPolygon(pygeoif.geometry.as_shape(footprint_poly))
project.footprint = 'SRID=27700;{0}'.format(gshape.wkt)


text:
Q: SSL certificate not working I'm going to put an application on a new server (after upgrading it from PHP 7 to PHP 8). I can connect to the server(Red Hat) only using VPN (pulse).
my purpose is to run the application on the browser.
when I connect to the server then I run curl localhost I get the error SSL certificate problem: self signed certificate in certificate chain when I run curl -k localhost I can see the content of the web page on the terminal.
I tried to access to the application through a web browser and the ip adress of the server but I get this site can't be reached
ssl virtual host context:
<VirtualHost _default_:443>

How can I access to the application using a web browser ?


text:
Q: Multiple wildcards in Azure RBAC I saw this in the documentation:
You can also have multiple wildcards in a string. For example, the following string represents all query permissions for Cost Management.
Microsoft.CostManagement/*/query/*

What does the first wildcard mean before the query?

A: It represents the resources under the Microsoft.CostManagement resource provider, e.g. externalBillingAccounts, externalSubscriptions.
With the action permission Microsoft.CostManagement/*/query/*, you will be able to query usage data under Microsoft.CostManagement, you can understand you have the sum of permissions Microsoft.CostManagement/externalBillingAccounts/query/* and Microsoft.CostManagement/externalSubscriptions/query/*, etc.
Reference - https://learn.microsoft.com/en-us/azure/role-based-access-control/resource-provider-operations#microsoftcostmanagement


text:
Q: can not convert string to float sklearn I wrote this program, but i get error:
ValueError: could not convert string to float

My code:
import sqlite3
from sklearn import tree

database = sqlite3.connect("database.db")
c = database.cursor()

x = []
y = []

for row in c.execute('SELECT * FROM cars'):
    x.append(row[0])
    y.append(row[1])

clf = tree.DecisionTreeClassifier()
ml = clf.fit(x,y)

edit: I read this link (https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html) but i do not know how to use label encoder in this app - please help me to use label encoder or solve this problem

A: An example how to use LabelEncoder properly:
I created a y list which contains some strings:
dummy_y = ['label1', 'label1', 'label2', 'label3', 'label77']

We want to encode each element in the list to a numeric value, LabelEncoder maps each string value to a corresponding numerical value.
First import the LabelEncoder class & create an instance of it:
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()

Now we can fit_transform our dummy list which means that the instance will first map each string to a value with fit and then will actually apply it with transform:
encoded_dummy_y = le.fit_transform(dummy_y)

will return:
array([0, 0, 1, 2, 3])

Where 0 corresponds to label1, 1 to label2 etc.


text: Q: send data to server when app is in background swift 3 I need to send the data from coreData to server after 30 minutes even the app is in the background. Currently i'm doing it with timer but timer gets stop working when my application enters background.


text:
Q: Targeting placeholder text using sass So I designed a flat signup form for a website to learn front-end developing. I used Mailchimp for the form, and this all seems to work. Now I have styled up everything how it supposed to be, however I cannot get this placeholder text to have a normal opacity. To me, it seems its opacity is lower than '1', or it does not show up completely 'white'.
I have tried a couple of things, but nothing works; "Opacity 1" and trying to select the placeholder with the vendor fixes mentioned in other posts. I also tried to come up with a mixin to target the vendor fixes (mentioned as a solution in previous posts), but nothing happened.
Thanks!

.newsletter-container {
  display: flex;
  height: 200px;
  background-color: #f4f4f4;
  align-items: center;
  justify-content: center;
}
.newsletter-container .newsletter-form {
  max-width: 700px;
  width: 100%;
}
.newsletter-container .newsletter-form .form-display {
  background: #f4f4f4;
  display: flex;
}
.newsletter-container .newsletter-form .form-display .mc-field-group {
  flex: 2;
}
.newsletter-container .newsletter-form .form-display input {
  background: #1d1c1c;
  border: 0;
  padding: 0;
  color: white;
  height: 50px;
  width: 100%;
  font-family: "Open Sans";
  font-size: 12px;
}
.newsletter-container .newsletter-form .form-display input[type="submit"] {
  flex: 1;
  border-left: 5px solid #f4f4f4;
  text-transform: uppercase;
}
.newsletter-container .newsletter-form .form-display input[type="text"] {
  padding-left: 10px;
}

      <form action="//facebook.us14.list-manage.com/subscribe/post?u=868cbba0c64a29c8fb08f6aef&id=eda72469b9" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

              <input type="text" value="" name="FNAME" class="" id="mce-FNAME" placeholder="Full Name">

              <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Email Adress">

            <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

<input type="text" name="b_868cbba0c64a29c8fb08f6aef_eda72469b9" tabindex="-1" value="">

      </form>

A: All are correct, except you need to specifically change the color of the input placeholder for different browsers, try:
WebKit, Blink (Safari, Google Chrome, Opera 15+) and Microsoft Edge are using a pseudo-element
::-webkit-input-placeholder {
    color: white;
}

Mozilla Firefox 4 to 18 are using a pseudo-class: :-moz-placeholder
Mozilla Firefox 19+ are using a pseudo-element: ::-moz-placeholder (double colon)
Internet Explorer 10 and 11 are using a pseudo-class: :-ms-input-placeholder.
Browsers <=IE9 & <=Opera12, does not support CSS selectors for placeholders (no surprise there!)
//affects all input placeholders across webkit browsers
::-webkit-input-placeholder {
    color: white;
}
//affects all input placeholders across webkit browsers

//no change in any of your other styles
.newsletter-container {
  display: flex;
  height: 200px;
  background-color: #f4f4f4;
  align-items: center;
  justify-content: center;
}
//no change in any of your other styles

Hope this helped..
Update:
This helped the OP.

Also check if the ::-webkit-input-placeholder is getting overridden by any other files like normalize.scss etc.