text:
Q: How raise an grandchildren array, at the level of children I have some problems with parent array that contains multiple children array. It will be necessary that the array children, does not contain themselves other children array, but if it is the case, then to raise these array grandchildren at the level of children.
[0] => Array (
    [0] => Array (
        [name] => ...
        [count] => ...
        [url] => ...
        [html] => ...
    )
    [1] => Array (
        [name] => ...
        [count] => ...
        [url] => ...
    )
    [2] => Array (
        [1] => Array (
            [name] => ...
            [count] => ...
            [url] => ...
            [html] => ...
        )
        [2] => Array (
            [name] => ...
            [count] => ...
            [url] => ...
        )
    )
    [3] => Array (
        [name] => ...
        [count] => ...
        [url] => ...
    )
    [4] => Array (
        [name] => ...
        [count] => ...
        [url] => ...
    )
);

In the example array["2"] contain 2 array, I want that the 2 array go up one level and so become brothers and not children.
Can you help me please with the right function ?
function transformMultipleArraysTo1(array $multipleArrays = null)
{
    $newArray = array();
    if (!isArrayEmpty($multipleArrays)) {
        foreach ($multipleArrays as $array) {
            if (is_array($array)) {
                foreach ($array as $singleArray) {
                    if (is_array($singleArray)) {
                        $newArray[] = $singleArray;
                    } else {
                        continue 2;
                    }
                }
                $newArray[] = $array;
            }
        }
    }
    return $newArray;
}

Many thanks

A: I came up with this solution, not the prettiest, but it works.
function RemoveThoseNastyGrandchildren(array $array = NULL){
  foreach ($array as $ckey => $child) {
    foreach($child as $gckey => $grandchild){
      if(is_array($grandchild)){
        $array[] = $grandchild;
        array_splice($array[$ckey],$gckey);
      }
    }
  }
  $length = count($array);
  for($i = 0; $i < $length ; $i++){
    if(!empty($array[$i][0]) && is_array($array[$i][0])){
      array_splice($array,$i,1);
      $i = -1;
      $length = count($array);
    }
  }
  //print("<pre>".print_r($array,true)."</pre>"); <---- To print it pretty uncomment
  return $array;
}

The First Loop:
will iterate through all relatives, looking for the potential grandchildren. If it finds one of these nasty grandchildren it'll append it to their parents, becoming a grandchildren again.

After that we just have to disensamble the former grandchildrens bodies, and that's what ...

The Second Loop does:
It's iterating through the changed array, looking for empty bodies.
Then return the freshly shaped array familytree and whooosh, you got rid of those GCs.


text:
Q: Loading a storyboard from a different Xcode project I have two different but related projects. Parent project A has a storyboard. Child project B, which (in theory) extends the functionality of A, needs to instantiate A's main storyboard in its AppDelegate. In my xcode workspace, I've included parent A within child project B, as a linked project and I can see all the files. I am using the following code in application:didFinishLaunchingWithOptions:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"iPhone.storyboard" bundle:[NSBundle mainBundle]];
MainViewController *vc = (MainViewController *)[storyboard instantiateInitialViewController];
_window.rootViewController = vc;
[self.window makeKeyAndVisible];

The code fails at runtime at the storyboardWithName line, I assume because iPhone.storyboard is not available immediately within B, and it doesn't know to look for it within A. The actual storyboard file is located in a different folder outside child project B's project folder on disk.

A: It has nothing to do with B and A. Files in the project can be located anywhere. Your error is at runtime. It has to do with the app you are building and running. Think about what this line says:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"iPhone.storyboard" bundle:[NSBundle mainBundle]];

So you are claiming here that there is a storyboard called iPhone.storyboard inside this app's main bundle. But there isn't. The app is building and you aren't doing anything to cause the storyboard to be copied into the app's bundle as part of that process. That's what you need to do.
To get the storyboard to be in the main bundle, add it to this app's Copy Bundle Resources build phase.
(Now, of course, there may be other problems, e.g. if classes referred to in this storyboard are not also part of this app. But that's not what your question was.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Onelogin user search - Is there an OR operator? I'm trying to fetch users using the search query, specifically users that a given string is their username\firstname\lastname or a prefix of their email. To do so in one query I need an OR operator.
In the API documentation it's missing and maybe not supported:
https://developers.onelogin.com/api-docs/1/users/get-users.
Example:
https://api.us.onelogin.com/api/1/users?firstname=${prefix}*&limit=10  - works
https://api.us.onelogin.com/api/1/users?firstname=${prefix}*|lastname=${prefix}*   - fails
On my OneLogin account in users UI there is an option to search with  this kind of query, and it successfully search for prefix with OR on multiple fields.
example
Does OR operator supported? Is there another way to do so with one query?


text:
Q: HDMI Display: Make the TV always show the current video playing When I connect my laptop to my TV via a HDMI cable it shows the laptop screen. This allows me to play videos on my laptop and view them on my TV screen.
But if I open another window, say an internet browser, then that window gets shown on the TV and the video gets covered up. Is it possible to make the TV always show the current video playing even if I open up another window?
This way I can still use my laptop whilst my kids are watching a video via the laptop and TV.

A: Sounds like your cloning the main laptop screen to the TV.
I'm assuming you're running Windows Vista/7/8 here. If not, let me know :)

*

*Right click desktop -> Screen resolutions

*Multiple displays: This should be "Extend these displays"

Important: Click on your laptop screen above (press Identify if you're not sure which screen is which number) and tick "Make this my primary display". This ensures the task bar shows on your laptop screen.
Click apply.
You should now be able to drag your media player application across to the TV (usually the right, but check how they are arranged in the Screen resolutions form), whilst having your web browser on your laptop. You won't see the video at all on the laptop.
I have this as a permanent set-up for my desktop PC. Main monitor on my desk for doing stuff, and a TV on HDMI for watching videos.
You should also set the default sound output to your main speakers and not TV HDMI, then in your video application set that to output to your TV HDMI. Then you can have your TV just playing sound from the video. If you're not sure how to do this let me know too :)
Edit: Once you have dragged over the media player to your TV it may save its' position there. Media Player Classic certainly does this, and is ideal for your situation. (it can remember the monitor to use, where to be on the monitor i.e. full screen from ALT+TAB, and the sound output) Not sure if Windows Media Player or VLC behave like this.


text:
Q: Validation for a 10 digit phone number in dojo ValidationTextBox I'm working with dojo1.7 and here i'm looking for a simple regex or range/places that will validate a 10 digit phone number of dijit.form.ValidationTextBox.
I'd like to make sure that the number is exactly 10 digits, no letters, hyphens or parens or other special chars. Can someone help me out?

A: For exact 10 digits, you can use the RegExp \d{10}. Here is a working example:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Telephone Number Check</title>
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.7/dijit/themes/claro/claro.css">
    <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7/dojo/dojo.js" data-dojo-config="async: true, parseOnLoad: true"></script>
    <script>
        require(["dojo/parser", "dijit/form/ValidationTextBox"]);
    </script>
</head>
<body class="claro">
    <label for="tel">Enter your 10 digits telephone number:</label>
    <input type="text" name="tel" value=""
    data-dojo-type="dijit.form.ValidationTextBox"
    data-dojo-props="regExp:'\\d{10}', required:true, invalidMessage:'Invalid telephone number.'">
</body>
</html>

A: <input id="reverveAmount" required="true" style="width:50px" data-dojo-type="dijit.form.ValidationTextBox" data-dojo-props='maxLength:"3",constraints:{places:1,min:1,max:20}, regExpGen:function(){ return "\\d+" }, required:true, invalidMessage:"Number only"'>

It's work good for me.

A: To force a format you can override the filter method. The default filter method comes from _TextBoxMixin.js, which is where trim, uppercase, lowercase, and propercase are implemented.
This reformats a ValidationTextBox value as ###-###-####.
Just remove the two splice lines if you don't want hyphens. Of course you could implement the filter method in other ways, such as by using dojo/number.
declare('calpoly/form/FormattingPhoneNumber', [ValidationTextBox], {

    regExp:"\\d{3}-\\d{3}-\\d{4}",
    invalidMessage:"Please enter a 10-digit phone number",

    filter:function(val){
        val = lang.trim(val);
        var s = [];
        for(var i=0; i<val.length;i++){
            if(!isNaN(val[i])){
                s.push(val[i]);
            }
        }
        if(s.length!=10){
            // Not a 10-digit phone number, return what the user typed, regex will invalidate.
            return val;
        }
        s.splice(3,0,'-');
        s.splice(7,0,'-');
        return s.join('');
    }
});


text:
Q: Why the csv file in S3 is empty after loading from Lambda import os
import csv
import boto3

client = boto3.client('s3')

fields = ['dt','dh','key','value']
row = [dt,dh,key,value]
print(row)

# name of csv file
filename = "/tmp/sns_file.csv"

# writing to csv file
with open(filename, 'a',newline='') as csvfile:
    # creating a csv writer object
    csvwriter = csv.writer(csvfile)

    # writing the fields
    csvwriter.writerow(fields)

    # writing the data row
    csvwriter.writerow(row)
    final_file_name="final_report_"+dt+".csv"
    client.upload_file('/tmp/sns_file.csv',BUCKET_NAME,final_file_name)
    if os.path.exists('/tmp/sns_file.csv'):
        os.remove('/tmp/sns_file.csv')
    else:
        print("The file does not exist")

A: Python's with block is a context manager, which means, in simple terms, it will "clean up" after all operations within it are done.
In context of files "clean up" means closing file. Any changes you write to the file will not be saved on disk until you close the file. So you need to move upload operation outside and after the with block.


text:
Q: Django database authentication plugin error I had a Django project that I had worked on in the past for quite a while. Recently, I tried to reopen it and add some minor changes. What happened is that recently I also reinstalled MySQL(8.0) and of course, recreated my old database. But now when I tried to run the server or any other operation, I get the following error:

2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.

I tried the solution from other post, but it did not work for me. Here is also a full traceback of the error: https://pastebin.com/JqexqTtC

A: I had the same problem and I fix this issue with the first method:

*

*If you have access to database through workbench, mysql console... and you have permission to alter user so you can change auth_plugin for default
ALTER  USER 'your_user' IDENTIFIED WITH mysql_native_password BY 'your_password';

*If you don't have permission to it database so you can change mysql connector.
add link: https://www.codegrepper.com/code-examples/sql/raise+errors.NotSupportedError%28+mysql.connector.errors.NotSupportedError%3A+Authentication+plugin+%27caching_sha2_password%27+is+not+supported


text:
Q: Remove a namespace from XML using Oracle SQL 11g I am using Oracle 11g and I try to create XML data. One of the tags is:
<majorLine>

I use the below code to generate it:
l_major_line := DBMS_XMLDOM.createElement (l_domdoc, 'ns1:majorLine');

DBMS_XMLDOM.setattribute (l_major_line, 'xmlns:ns1','urn:xyz:ccw:config:msa:data');
DBMS_XMLDOM.setattribute (l_major_line, 'lineId', l_line_id);

It gives this output:
<ns1:majorLine xmlns:ns1="urn:xyz:ccw:config:msa:data"  linId = "12345">

The issue is, that I don't want the portion: "xmlns:ns1="urn:xyz:ccw:config:msa:data"
Instead I need:
<ns1:majorLine linId = "12345">

Please help. Thanks in advance.

A: Use dbms_xmldom.removeAttribute:
declare
  l_domdoc dbms_xmldom.DOMDocument;
  l_major_line dbms_xmldom.DOMElement;
  l_node dbms_xmldom.DOMNode;
  l_attrs dbms_xmldom.DOMNamedNodeMap;
  l_len pls_integer;
  l_name varchar2( 4000 );
  l_clob clob;
begin
  -- Sample data preparation.
  l_domdoc := dbms_xmldom.createDocument( 'xmlns:ns1', 'doc' );
  l_major_line := dbms_xmldom.createElement( l_domdoc, 'ns1:majorLine' );
  dbms_xmldom.setAttribute( l_major_line, 'lineId', 12345 );
  dbms_xmldom.setAttribute( l_major_line, 'xmlns:ns1', 'urn:xyz:ccw:config:msa:data' );

  -- Remove exact namespace.
  --dbms_xmldom.removeAttribute( l_major_line, 'xmlns:ns1' );

  -- Or remove generic namespace if the exact name is not known.
  l_node := dbms_xmldom.makeNode( l_major_line );
  l_attrs := dbms_xmldom.getAttributes( l_node );
  l_len := dbms_xmldom.getLength( l_attrs );
  for i in 1 .. l_len loop
    l_node := dbms_xmldom.item( l_attrs, i );
    l_name := dbms_xmldom.getNodeName( l_node );
    if lower( l_name ) like 'xmlns:%' then
      dbms_xmldom.removeAttribute( l_major_line, l_name );
    end if;
  end loop;

  -- Output.
  l_node := dbms_xmldom.makeNode( l_major_line );
  dbms_lob.createTemporary( l_clob, true );
  dbms_xmldom.writeToClob( l_node, l_clob );
  dbms_output.put_line( l_clob );
end;


text:
Q: pyinotify for watching new file creation in a folder I am watching a folder being_watched using the pyinotify module in python. But the files are being created faster than they can be processed by the Event Handler of the pyinotify. Is there a way around this problem, where all the new files created can be lined up or taken up later by the Event Handler?
Code snippet:
class EventHandler(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        print "Creating:", event.pathname
        #start_time=time.time()
        #reading the data
        with open(str(event.pathname)) as ofile:
            d = json.loads(ofile.read())
            for _id in d:
                if d[_id]["_comment"]>0:
                    inputdata.update({_id:{"la":d[message_id]["la"],"lo":d[_id]["lo"]}})

        try:
            getcdata(inputdata,outfile)
        except RuntimeError as e:
            logger.error('Caught a Rutime exception in the getcdatadriver . '+str(e.value))

def main():
    logger = logging.getLogger('mainloop')
    logger.setLevel(logging.DEBUG)
    fh = logging.FileHandler('getcdatadriver.log')
    logger.addHandler(fh)

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    sys.excepthook=Notify(logger,"Exception caught getcdatadriver mainloop").my_excepthook
    try:
        while True:
                watch_dir="./output_watchdir"
                wm = pyinotify.WatchManager()  # Watch Manager
                mask = pyinotify.IN_CREATE  # watched events
                handler = EventHandler()
                notifier = pyinotify.Notifier(wm, handler)
                wdd = wm.add_watch(watch_dir, mask, rec=True)
                notifier.loop()
    except (KeyboardInterrupt, SystemExit):
        print '\n! Received keyboard interrupt, quitting.\n'
        Notify(logger,"getcdatadriver stopped").send_exception_email('Received keyboard interrupt, quitting.')
    except RuntimeError as e:
        print 'Caught a Rutime exception in the getcdatadriver mainloop. '+str(e.value)
        Notify(logger,"Runtime Exception getcdatadriver mainloop").send_exception_email(str(e.value))


text:
Q: Highcharts - How to plot a X axis line on my bell curve (Standard Deviation Curve) I have one Highchart which is showing a Standard Deviation curve (Bell curve). I  would like to plot a x axis vertical line when x=0.(see my current graph).
When I  include the code to include the line the chart disappear, so I believe something I need to change,  obviously :-).
Just as information the chart works perfectly without the "plotLines:" inside xAxis.
Could you help me with this?
See my Script

<script>
var data = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;

var pointsInInterval = 5;

Highcharts.chart('container', {
    chart: {
        margin: [50, 0, 50, 50],
        events: {
            load: function () {
                Highcharts.each(this.series[0].data, function (point, i) {
                    var labels = ['4σ', '3σ', '2σ', 'σ', 'μ', 'σ', '2σ', '3σ', '4σ'];
                    if (i % pointsInInterval === 0) {
                        point.update({
                            color: 'red',
                            dataLabels: {
                                enabled: true,
                                format: labels[Math.floor(i / pointsInInterval)],
                                overflow: 'none',
                                crop: false,
                                y: -2,
                                style: {
                                    fontSize: '13px'
                                }
                            }
                        });
                    }
                });
            }
        }
    },

    title: {
        text: null
    },

    legend: {
        enabled: false
    },

    xAxis: [{
        title: {
            text: 'Data'
        },
        visible: false
    }, {
        title: {
            text: 'Bell curve'
        },
        opposite: false,
        visible: true
    },
    plotLines: [{
            color: '#FF0000',
            width: 2,
            value: 0
        }]

],

    yAxis: [{
        title: {
            text: 'Data'
        },
        visible: false
    }, {
        title: {
            text: 'Bell curve'
        },
        opposite: false,
        visible: true
    }],

    series: [{
        name: 'Bell curve asd',
        type: 'bellcurve',
        xAxis: 1,
        yAxis: 1,
        pointsInInterval: pointsInInterval,
        intervals: 4,
        baseSeries: 1,
        zIndex: -1,
        marker: {
            enabled: true
        }
    }, {
        name: 'Data',
        type: 'scatter',
        data: data,
        visible: false,
        marker: {
            radius: 1.5
        }
    }],
    exporting: {
        allowHTML: true,
        sourceWidth: 800,
        sourceHeight: 600
    }
});
</script>

A: Plot lines should be added as a property of an axis object:
xAxis: [{
        title: {
            text: 'Data'
        },
        visible: false
    }, {
        title: {
            text: 'Bell curve'
        },
        opposite: false,
        visible: true,
        plotLines: [{
            color: '#FF0000',
            width: 2,
            value: 0
        }]
    }
]

Live demo: http://jsfiddle.net/BlackLabel/4xcno5v9/
API Reference: https://api.highcharts.com/highcharts/xAxis.plotLines


text:
Q: Synchronizing the change in OWL file with Jena TDB dataset I am using JENA TDB to store a OWL file read as OntModel. The code for the same is :
public static void initializeModel(){
        dataset=TDBFactory.createDataset("Path/to/TDBDir");
        Model b = dataset.getDefaultModel();
        ontModel= ModelToOntModel(b);
        FileManager.get().readModel( ontModel, "Path/to/sourceOWL.owl");
        jListener= new JenaListener(ontModel,"MODEL");
        ontModel.register(jListener);
    }

Hereby I am facing a problem where if the owl file is change externally (specifically when we delete something form the owl file) when the application is not running and again re-run the application, the data set appears to be in an inconsistent state as per the owl file, as because the entities deleted from the owl file still persists in the ontModel   (as those old entries persists in the TDB), which is not desired in our case.
Is there any way to overcome this kind of problem? so that the dataset remains consistent with my OWL file? Or is the method as shown above is not the correct way of creating TDB?

A: TDB has it's own copy of the data - you need to tell it that the file is changed.  In fact, all readModel operations are taking some source syntax and creating (a copy) the RDF triples to be stored in-memory or in-database.
If your file is small, empty the database and reload.
If you file is large, then if you can obtain the changes in someway, then apply the changes to the database version.


text:
Q: Using streams how to replace a value of the nested list First half of the strings encountered in the inputs in the index position 1 are to be replaced with  the character "-"  using streams how can we perform the operations?
List<List<String>> arr = Arrays.asList(Arrays.asList("0", "ab"), Arrays.asList("6", "cd"),
    Arrays.asList("0", "ef"), Arrays.asList("6", "gh"),
    Arrays.asList("4", "ij"), Arrays.asList("0", "ab"),
    Arrays.asList("6", "cd"));

I have the above list I wanted replace the 1st position of each nested list value with "-" using loops I have done like this
    int j=0;
    while(j <arr.size()/2){
        arr.get(j).set(1, "-");
        j++;

        }

Sample output:[[0, -], [6, -], [0, -], [6, gh], [4, ij], [0, ab], [6, cd]]
But any one can explain how the same can be achieved using streams

A: The question is vague. Better to give the output format too so that someone can understand what you need and help you. However based on some assumptions and heuristics, I guess this what you need. If you want a different formatting, please let me know or change this answer accordingly.
Another point here is what you have tried so far is not clear. You have to give it a try upfront and mention what you have done when the question is posted.
List<List<String>> formattedStrings = source.stream()
    .map(sl -> IntStream.range(0, sl.size())
        .mapToObj(i -> i == 1 ? sl.get(i).charAt(0) + "-" + sl.get(i).charAt(1) : sl.get(i))
            .collect(Collectors.toList()))
    .collect(Collectors.toList());

A: I wouldn't use a Stream to do this, working on a sublist would be simpler:
arr.subList(0, arr.size() / 2).forEach(s -> s.set(1, "-"));

If you really need to work with streams (e.g. if you want to do additional filtering and mapping operations), you could do it with either an IntStream to work on the indexes:
IntStream.range(0, arr.size() / 2)
        .forEach(j -> arr.get(j).set(1, "-"));

or simply by limiting the number of entries you process:
arr.stream()
        .limit(arr.size() / 2)
        .forEach(s -> s.set(1, "-"));


text:
Q: How was this encoded? how was this encoded text was encoded and how to decode it :
first one :
ypyRnGbk9F2FpFpvg82oZg==
second :
J9ogXUFPvXPSgj+VSSEVOA==
third:
8Qm87EDRIB9J0imjma5g3JwUP6zRfdQgaecIJlc5RGePzGKIX0Nt4PKikixX0VYL
fourth :
OaSwAcMhjclCMPlRbbZ00A==
fifth :
pnt2lBNgWugh7LBMGbJArQ==
note : im just trying to make it easier if you could recognize any of those ,
i tried base 64 but didn't work
anyone have any idea

A: it looks like base64 to me - the padding (trailing =) is consistent with that.
and what do you mean by "didn't work"?  at least the first three decode fine for me (although i get binary data, not, say, ASCII).
to decode in python:
from base66 import b64decode
print b64decode('ypyRnGbk9F2FpFpvg82oZg==')

which will give you a "mess" because it's binary data.  that particular string might be utf16:
print b64decode('ypyRnGbk9F2FpFpvg82oZg==').decode('utf16')

which gives something with chinese(?) characters, but others are not.
you need to understand that the basic kind of data in computer is a byte (a number between 0 and 255).  that is what you are getting from b64decode.  ASCII is a way of using those numbers to represent western characters, and if this was ASCII then you'd see the text when python prints out the result.  UTF8 and UTF16 are more complicated ways of storing text in digits that you need to "decode" as above.
just to be clear, the binary data is the output from b64decode, so you might store it in a variable:
my_binary_data = b64decode('ypyRnGbk9F2FpFpvg82oZg==')


text:
Q: Can one extend the domain of the square root $\sqrt{\cdot}$ to $\mathbb R$? Is it even allowed to do that? I know that it is defined to only return the positive solutions and is a function as such, but can one extend the domain with it still being called a function?

A: It's a function from $[0,\infty) = \mathbb R^+$ to $\mathbb R$ (although not onto).
You can not extend a domain to where it is undefined.  But you can restrict it to where it is defined.
$\sqrt{}: \mathbb R^+ \to \mathbb R^+ \subset \mathbb R$ is a function.
Another way to put this is to note that part of the declaration of a function is a precise declaration of what the domain is.  So $\sqrt{}$ is a function upon the correct domain.  But the correct domain is NOT $\mathbb R$.
The declaration of the domain is often neglected, overlooked and misunderstood.  But it is a essential part of defining a function.  In fact, maybe the most important part.

A: If $f(x) = \sqrt{x}$ is considered will all real numbers as its domain, how do you define $f(-1)$?
Normally we do that by saying $f(-1) = i \in \mathbb{C}$ but you are asking about $f:\mathbb{R} \to \mathbb{R}$, I don't think there is a way to do that.


text:
Q: Is my website compatible with a specific browser? What's the best way of checking the compatibility of a website with a specific version of a browser.
For instance, I know how my website will be rendered on the latest version of FireFox which I've installed it before, but I don't know how it'd be shown on previous versions.
IE has an option to render a page like previous version but firstly I've heard that it's not as the same as the original version and secondly it's just IE and what about others?

A:
What's the best way of checking the compatibility of a website with a specific version of a browser.

Check it in that browser.  Only you know what "compatible" means, and what sort of compatibility you're willing to accept for your site.
There are some tools that can make it easier.  For example, CrossBrowserTesting.com can render your page in various browsers for easy inspection.  They also allow for running Selenium tests, and a VNC session for manually testing your pages.  There are many alternatives to CrossBrowserTesting.com as well.

A: you can make multiple versions of Firefox and Seamonkey co-exist with each other. Install them into separate directories and create a different profile for each browser you instal.
for chrome, the vast majority of people who uses the Chrome browser will be using the latest version, since that browser automatically updates itself whether you want it or not.
check out this website for more info about other browsers:
http://www.thesitewizard.com/webdesign/multiplebrowsers.shtml
hope this helps


text:
Q: Data Stacking Issue PHP So, I have a client who wanted me to make a bulk domain checker. He wanted it to take in an untimed amount of domains and output them in a downloadable .csv file.Everything works just like it should until you try to use it a second time.Then it reopens the file and appends the data ontop of it.So if you put in 500 domains the first time, it outputs 500 domains. If you put 500 domains in the second time, it outputs 1000 domains.Its turning out to be a real challenge.I tried using a temp file but then it outputs a black csv file.I tried using unlink() but it just deletes the file before you can download it.I'm guessing its a simple fix but I think it has to do with how I create the array for the fopen() function.Unfortunately, it's the only way to make the array so that it out puts correctly.(each domain stacking on top of each other in the same Colum of the csv file.) Using the 'a' method in the fopen() function is the only way to get all the domains in the file that I know of.
Any thoughts?
Here is the entire code:
<?php
$domnames = array('');

$domains = $_POST['domains'];
$domSep = explode(' ', $domains);
foreach ($domSep as $site) {
    $godaddycheck = 'https://in.godaddy.com/domains/searchresults.aspx?checkAvail=1&tmskey=&domainToCheck='.$site.'';
    $namecomcheck = 'https://www.name.com/domain/search/'.$site.'';
    $registercomcheck = 'http://www.register.com/domain/search/wizard.rcmx?searchDomainName='.$site.'&searchPath=Default&searchTlds=';

    if(isset($_POST)){
        if (gethostbyname($site) != $site) {
             array_push($domnames, "$site" . " | Unavailable");
        } else {
           array_push($domnames, "$site" . " | Available");
        }
        $full = array($domnames);

        // Open a file in write mode ('w')
        $fp = fopen('domain_avalibilities.csv', 'a');

        // Loop through file pointer and a line
        foreach ($full as $fields) {
            fputcsv($fp, $fields);
        }
    }
}
?>

    Download Results as CSV File


text:
Q: Add ellipses to overflowing text in SVG? I'm using D3.js. I'd like to find an SVG equivalent to this CSS class, which adds ellipses if text flows out of its containing div:
.ai-ellipsis {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  -moz-binding: url(<q>assets/xml/ellipsis.xml#ellipsis</q>);
}

This is my SVG:
<g class="bar" transform="translate(0,39)">
    <text class="label" x="-3" y="6.5" dy=".35em" text-anchor="start">Construction</text>
    <rect height="13" width="123"></rect>
</g>

It's generated as follows:
barEnter.append("text").attr("class", "label")
        .attr("x", -3).attr("y", function() { return y.rangeBand() / 2})
        .attr("dy", ".35em").attr("text-anchor", "start")
        .text(function(d) {
            return d.Name;
        });

Currently the text is overflowing and overlapping the rect element.
Is there any way I can say "if text is more than a certain width, crop it and add ellipses"?

A: This function does not depend on d3:
function textEllipsis(el, text, width) {
  if (typeof el.getSubStringLength !== "undefined") {
    el.textContent = text;
    var len = text.length;
    while (el.getSubStringLength(0, len--) > width) {
        el.textContent = text.slice(0, len) + "...";
    }
  } else if (typeof el.getComputedTextLength !== "undefined") {
    while (el.getComputedTextLength() > width) {
      text = text.slice(0,-1);
      el.textContent = text + "...";
    }
  } else {
    // the last fallback
    while (el.getBBox().width > width) {
      text = text.slice(0,-1);
      // we need to update the textContent to update the boundary width
      el.textContent = text + "...";
    }
  }
}

A: a wrapper function for overflowing text:
    function wrap() {
        var self = d3.select(this),
            textLength = self.node().getComputedTextLength(),
            text = self.text();
        while (textLength > (width - 2 * padding) && text.length > 0) {
            text = text.slice(0, -1);
            self.text(text + '...');
            textLength = self.node().getComputedTextLength();
        }
    }

usage:
text.append('tspan').text(function(d) { return d.name; }).each(wrap);

A: Just an update on the wrap function proposed by user2846569. getComputedTextLength() tends to be really slow, so...
EDIT
I diligently applied the advice by user2846569 and made a version with "binary" search, with some calibration and parametrized precision.
'use strict';

var width = 2560;

d3.select('svg').attr('width', width);

// From http://stackoverflow.com/questions/10726909/random-alpha-numeric-string-in-javascript
function randomString(length, chars) {
    var result = '';
    for (var i = length; i > 0; --i)
        result += chars[Math.floor(Math.random() * chars.length)];
    return result;
}

function wrap() {
    var self = d3.select(this),
        textWidth = self.node().getComputedTextLength(),    // Width of text in pixel.
        initialText = self.text(),                          // Initial text.
        textLength = initialText.length,                    // Length of text in characters.
        text = initialText,
        precision = 10, //textWidth / width,                // Adjustable precision.
        maxIterations = 100; // width;                      // Set iterations limit.

    while (maxIterations > 0 && text.length > 0 && Math.abs(width - textWidth) > precision) {

        text = /*text.slice(0,-1); =*/(textWidth >= width) ? text.slice(0, -textLength * 0.15) : initialText.slice(0, textLength * 1.15);
        self.text(text + '...');
        textWidth = self.node().getComputedTextLength();
        textLength = text.length;
        maxIterations--;
    }
    console.log(width - textWidth);
}

var g = d3.select('g');

g.append('text').append('tspan').text(function(d) {
    return randomString(width, 'a');
}).each(wrap);

View on JSFiddle.

A: function trimText(text, threshold) {
    if (text.length <= threshold) return text;
    return text.substr(0, threshold).concat("...");
}

Use this function to set the SVG node text. The value for the threshold (eg. 20) depends on you. This means that you will display up to 20 characters from your node text. All the texts grater than 20 characters will be trim and display "..." at the end of the trim text.
Usage eg. :
var self = this;
nodeText.text(x => self.trimText(x.name, 20)) // nodeText is the text element of the SVG node

A: I am not aware of an equivalent CSS class for SVG, but you can use foreignObject to embed HTML in SVG. This gives you access to this functionality and is more flexible in general (e.g. you can do automatic line breaking easily).
See here for a complete example.

A: Mauro Colella's excellent answer, in Typescript:
export const svgTextEllipsis = (textNode: SVGTextElement, padding = 0) => {
  const d3Node = d3.select(textNode);
  const targetWidth = Number(d3Node.attr("width")) - padding;
  const initialText = d3Node.text();
  const precision = 25;
  const maxIterations = 3;

  let textWidth = d3Node.node()?.getComputedTextLength() ?? 0;
  let textLength = initialText.length;
  let text = initialText;
  let i = 0;

  if (textWidth < targetWidth) return;

  while (
    i < maxIterations &&
    text.length > 0 &&
    Math.abs(targetWidth - textWidth) > precision
  ) {
    text =
      textWidth >= targetWidth
        ? text.slice(0, -textLength * 0.15)
        : initialText.slice(0, textLength * 1.15);
    d3Node.text(`${text}…`);
    textWidth = d3Node.node()?.getComputedTextLength() ?? 0;
    textLength = text.length;
    i += 1;
  }

  d3Node.text(d3Node.text().replace(/…+/, "…"));
};

A: If you write CSS it won't work on .
Instead of that write logic and append '...' in string.


text:
Q: How can i configure specific connection pool implementation with spring-boot & spring-data-mongodb? I am using spring-boot along with spring-data-mongodb.
But I have to configure a separate connection pool. Is it Possible?

A: Here all the properties that you can currently configure for mongodb in spring boot.
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
spring.data.mongodb.authentication-database= # Authentication database name.
spring.data.mongodb.database=test # Database name.
spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.
spring.data.mongodb.grid-fs-database= # GridFS database name.
spring.data.mongodb.host=localhost # Mongo server host.
spring.data.mongodb.password= # Login password of the mongo server.
spring.data.mongodb.port=27017 # Mongo server port.
spring.data.mongodb.repositories.enabled=true # Enable Mongo repositories.
spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. When set, host and port are ignored.
spring.data.mongodb.username= # Login user of the mongo server.

You can configure the connection pool properties by autowiring MongoClientOptionsFactoryBean.
http://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoClientOptionsFactoryBean.html


text:
Q: ¿Como hago que si está logueado no se muestre de nuevo "iniciar sesión" o si no esta logueado no aparezca "Cerrar sesión"? Tengo este error en php, supuestamente esto hace que si está logueado muestre el if, que es para salir, y si no muestre el else, que es para entrar o registrarse,
pero siempre muestra el if, como si se cumpliera:

if(isset($_SESSION['usuario']) && $_SESSION['usuario'] != "") {

echo 'Crea tu cuenta
      Ingresar';

}else{

echo 'Salir';

}

A: El código es correcto pero parece que la intención está al revés, igual revisa tus variables si tienes dudas con ellas; $_SESSION['usuario']
if(isset($_SESSION['usuario']) && $_SESSION['usuario'] != "") { //si existe la variable 'usuario' y no es igual a "" (suponemos que hay sesión) entonces...
  var_dump($_SESSION);
  echo 'Salir';

}else{ //si no hay variable usuario (suponemos que no hay sesión) entonces...
  var_dump(isset($_SESSION) ? $_SESSION : 'No se ha iniciado la sesión, intenta usar session_start(); primero');
  echo 'Crea tu cuenta'
      .' Ingresar';
}


text:
Q: Multiplet select statements, each one uses CASE and return two values i have the follwoing query:
SELECT COALESCE(income_adsense, income_adsense_u) AS "REV",
   CASE COALESCE(income_adsense, income_adsense_u)
       WHEN income_adsense THEN "REAL"
       WHEN income_adsense_u THEN "USER"
   END AS source
FROM revenue_report LIMIT 1;

which will return answer like this:
REV  |  source
376  |   REAL

now the query works fine but the problem is i want to execute this select couple of times for different entity (adsense in the example).
the best i could get is this:
SELECT rr.site_id, ws.website_name,
   CASE COALESCE(income_adsense, income_adsense_u)
       WHEN income_adsense THEN "REAL"
       WHEN income_adsense_u THEN "USER"
   END AS adsense_source,
   CASE COALESCE(income_taboola, income_taboola_u)
       WHEN income_taboola THEN "REAL"
       WHEN income_taboola_u THEN "USER"
   END AS taboola_source
FROM revenue_report rr
INNER JOIN websites ws ON ws.website_id = rr.site_id
WHERE (data_date BETWEEN '2017-03-18' AND '2017-03-18')
GROUP BY site_id
LIMIT 1

but the problem here is i'm missing the "REV" value from the upper example. I know it doesn't exists in the second query, but this is the last working attempt. any idea how can i add the "REV" value logic to the second query?
in the second query i will get this structure of result:
site_id|website_name|adsense_source|taboola_source

but here im missing the COALESCE result from the first query which in the example was 376

A: Well why can't you just include it in your SELECT list like
SELECT rr.site_id, ws.website_name,
   COALESCE(income_adsense, income_adsense_u) AS "REV", //Here
   CASE COALESCE(income_adsense, income_adsense_u)
       WHEN income_adsense THEN "REAL"
       WHEN income_adsense_u THEN "USER"
   END AS adsense_source,
   CASE COALESCE(income_gol, income_gol_u)
       WHEN income_taboola THEN "REAL"
       WHEN income_taboola_u THEN "USER"
   END AS taboola_source
FROM revenue_report rr
INNER JOIN websites ws ON ws.website_id = rr.site_id
WHERE (data_date BETWEEN '2017-03-18' AND '2017-03-18')
GROUP BY site_id
LIMIT 1


text:
Q: Remove a cloned element with JQuery I'm cloning a tr and setting it's data-id attribute. I'm then using that data-id to be able to open a modal and if the user clicks the Delete Button use an AJAX call to delete the row. I'm able to pass the data-id and successfully submit the AJAX and delete the item but on success when I try to do a remove on the row it doesn't work.
var clone = $('#sizeValueTemplate').clone(true);
clone.data('id', data.id);
clone.removeAttr('id');
clone.show().appendTo('#sizeValueTable');

A confirmation modal is shown and upon OK I delete the item. And then on Success:
$('tr[data-id='+id+']').remove();
$('#modalDeleteSizeValue').modal('hide');

Everything works with no errors except the tr is not removed. The process works for elements present on the page load.

A: The data function does not add data- style attributes to the element, which is why you can't look it up. You could try clone.attr('data-id', data.id); instead.

A: Setting a data using .data(key, value) will NOT insert it in the DOM. You need to use .attr('data-...', value) for it.
So, this would work:
clone.attr('data-id', data.id);


text:
Q: Proof that INF (the set of indices of Turing Machines that halt on infinitely many inputs) is not computably enumerable, I.e. $\not \in \Sigma_1^0$ I got curious about this today when looking for sets to proove aren't $\Sigma_1$ as exam prep.
Unlike with its complement, FIN, a run of the mill contradiction was not easy to come by (perhaps I'm being stupid), and the infinite domains of the functions don't necessarily intersect, so I see no way to diagonalise out. My next line of attack was to show:
$$a \in \text{INF} \iff \forall m \exists n,s: (n > m) \land \varphi_a^s(n) \downarrow$$
So INF is $\Pi_2$. If it's $\Pi_2$ complete, then INF $=_T 0''$, which contradicts that any $\Sigma_1$ set turing reduces to $0'$. But I've not had any luck prooving this completeness, nor the equivalent condition that FIN is $\Sigma_2$ complete.

A: Yes, INF is $\Pi^0_2$ complete. You can prove this by a small variation the same reduction from the reduction here.
You can also prove the weaker result that INF is not $\Sigma^0_1$ by diagonalization. Here is the construction, and then a verification.

Construction
Suppose $W$ is an arbitrary r.e. set. Let $e$ be a program that does the following. On input $k$, $e$ first simulates the enumeration of $W$ for $k$ timesteps.  If $e$ finds that its own index $e$ is not enumerated into $W$ within $k$ timesteps, then $e(k)$ halts. Otherwise, if $e$ is enumerated into $W$ in $k$ timesteps, then $e(k)$ does not halt. The circularity here (that $e$ knows its own index) is easy to resolve with the recursion theorem.

Verification
First suppose $e \in W$. Then there is some $k$ for which $e$ is enumerated into $W$ in $k$ timesteps. Then $e(n) \uparrow$ for all $n \geq k$, so $e \not \in \text{INF}$.
Conversely, suppose $e \not \in W$. Then $e(k)\downarrow$ for all $k$, so $e \in \text{INF}$.
Overall, $e \in W \leftrightarrow e \not \in \text{INF}$.
Here $W$ was an arbitrary r.e. set, so in particular INF cannot be an r.e. set, because we would obtain a contradiction if $W$ could be the set INF.

A: The diagonalisation method, which I figured out after Carl Mummert noted that it is possible:
Assume INF is $\Sigma_1$. Then we can enumerate its elements computably; for come computable $f$, we have INF $= \{ f(0), f(1), ...\}$.
Now construct a partial recursive function $g$ as follows:
First do one step of the computation for $\varphi_{f(0)} (0)$, then two steps of $\varphi_{f(0)} (0)$ and $\varphi_{f(0)} (1)$, then three of $\varphi_{f(0)} (0)$, $\varphi_{f(0)} (1)$ and $\varphi_{f(0)} (2)$ etc. Since the domain of $\varphi_{f(0)}$ is non-empty, this process will eventually halt for some argument $n_0$. Now we define that $g(n_0) =  \varphi_{f(0)} (n_0)+1$.
Repeat this process for $\varphi_{f(1)}$, and let the first argument (excluding $n_0$) which $\varphi_{f(1)}$ halts on be $n_1$. Then we define $g(n_1) = \varphi_{f(1)} (n_1)+1$.
Each time, we repeat this process, defining $g$ at a new (unique) $n_k$. We can always afford to ignore previous $n_i$ because the domain of every function under consideration is infinite, so they must still halt yet somewhere else.
To compute the function at a value, simply go through the construction until an $n_i$ is found which is the input. If no such $n_i$ is ever found, this process naturally diverges.
$g$ is defined on the infinite set $\{ n_0, n_1, n_2, ... \}$, hence $\exists e$ with $g(n) = \varphi_{f(e)} (n)$.
But $\varphi_{f(e)} (n_e) = g(n_e) = \varphi_{f(e)} (n_e)+1$
By the construction, $\varphi_{f(e)}(n_e) \downarrow$ and $g(n_e) \downarrow$, so the above implies $0=1$.
This is a contradiction, so INF is not $\Sigma_1$.


text:
Q: C# comparing similar strings I have a generic with some filenames (LIST1) and another biggeneric with a full list of names (LIST2).
I need to match names from LIST1 to similar ones in LIST2. For example
LIST1
- **MAIZE_SLIP_QUANTITY_3_9.1.aif**

LIST 2
1- TUTORIAL_FAILURE_CLINCH_4.1.aif
2- **MAIZE_SLIP_QUANTITY_3_5.1.aif**
3- **MAIZE_SLIP_QUANTITY_3_9.2.aif**
4- TUTORIAL_FAILURE_CLINCH_5.1.aif
5- TUTORIAL_FAILURE_CLINCH_6.1.aif
6- TUTORIAL_FAILURE_CLINCH_7.1.aif
7- TUTORIAL_FAILURE_CLINCH_8.1.aif
8- TUTORIAL_FAILURE_CLINCH_9.1.aif
9- TUTORIAL_FAILURE_PUSH_4.1.aif

I've read about Levenshtein distance and used an implementation of it in a Framework (SignumFramework Utilities).
It returns me distance=1 in lines 2 and 3. But in my case line 3 is a better match than line 2.
Is there another method better to compare similar strings? Something more flexible?

A: When comparing as strings, "9.2" is not a better match than "5.1" for "9.1". If you want the version numbers to be evaluated numerically, you have to parse the strings so that you can compare the string parts and the numerical parts separately.

A: Your similarity criteria could be a combination of several other criteria. One could be the Levenshtein distance, others might e.g be the longest common substring or prefix/suffix.
The longest common substring problem is actually a special case of edit distance, when substitutions are forbidden and only exact character match, insert, and delete are allowable edit operations (see here).
Further metrics for string similarity are described here.

A: A regular expression could be used to get the items that match the name. The version number could be collected in a regex group in the match and parsed into a .net object (e.g. decimal) that you could use to compare which one was closest.

A: There's a fairly exhaustive set of answers to this SO question.  At the bottom is link I put up to C# implementations for soundex, double metaphone, PHP similarity and levenstein.


text:
Q: Not able to get current timestamp from postgres using knes I am using knex and using raw query to get current time stamp of the postgres database. I am using
knex.raw('select now()').then(function(resp)
{
 console.log(resp)
})

but i am not able to get the desired result. Please tell the solution of what i can do.

A: This should do:
knex.select(knex.fn.now()).then(res => console.log(res[0].now));

Maybe you should also tell what is your desired result.
EDIT: edited query to actually fetch row and column from response, because select CURRENT_TIMESTAMP; returns following on postgres:
mikaelle=# select CURRENT_TIMESTAMP;
              now
-------------------------------
 2018-12-10 14:48:01.472945+02
(1 row)


text:
Q: Error extracting a substring using IndexOf method ? This is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace DownloadImages
{
    public partial class Form1 : Form
    {
        string f;

        public Form1()
        {
            InitializeComponent();

            string localFilename = @"d:\localpath\";

                using (WebClient client = new WebClient())
                {
                    client.DownloadFile("http://www.sat24.com/foreloop.aspx?type=1&continent=europa#",localFilename + "test.html");
                }

                f = File.ReadAllText(localFilename + "test.html");
                test();
        }

        private void test()
        {
            List<string> imagesUrls = new List<string>();
            int startIndex = 0;
            int endIndex = 0;
            int position = 0;

            string startTag = "http://www.niederschlagsradar.de/images.aspx";
            string endTag = "cultuur=en-GB&continent=europa";
            startIndex = f.IndexOf(startTag);

            while (startIndex > 0)
            {

                endIndex = f.IndexOf(endTag,startIndex);
                if (endIndex == -1)
                {
                    break;
                }
                string t = f.Substring(startIndex, endIndex - startIndex + endTag.Length);
                imagesUrls.Add(t);
                position = endIndex + endTag.Length;
                startIndex = f.IndexOf(startTag,position);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

The List in the end contain 63 indexes.
The first one for example,index 0 contains:
http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.precip&datum=201309151800&cultuur=en-GB&continent=europa

Index 5 for example,contains:
http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.precip&datum=201309160600&cultuur=en-GB&continent=europa

The last index is the problem,it contains the string i want like in the other indexes but it also contains the rest of the file content from this last index:
This is part of the last index:
http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.precip&cultuur=thumbnail&continent=europa" border="0"/>

<div

But the last index should be only:
http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.precip&cultuur=thumbnail&continent=europa

How can I solve it ?

A: You might want to use this cool tool:
HtmlAgilityPack
Some info:

*

*StackOverflow: How to use HtmlAgilityPack.

*BlogSpot.ru tutorial (extracting links from HTML page).

*Other useful stuff.

A: for scraping web page, htmlagilitypack is quite useful. Here is a helpful example with explanations:
http://codingfields.com/guides/htmlagilitypack/
This page explains few keys:
http://www.codeproblem.com/articles/languages/81-net-framework/74-html-parsing-in-c-using-html-agility-pack
This page is not bad, too:
http://beletsky.net/2010/09/crawling-web-sites-with-htmlagilitypack.html
This example illustrates replacing context: http://sparkingnaz.wordpress.com/2013/03/12/how-to-use-html-agility-pack-parsing-html-documents-with-the-html-agility-pack-to-extract-content-node-and-replace-content/


text:
Q: How do you list all the files managed by `puppet`? I need to make some changes to a system but I am not sure if the changes I make are managed by puppet or not. So I want to check to see if puppet is managing the files I wish to change.
How do you list all the files managed by puppet?

A: Ever since version 2.7.x you can do:
cat $(puppet agent --configprint resourcefile)
(source of solution)


text:
Q: Awaiting multiple levels of Futures? I have a getter for a singleton instance of a SQFlite Database, like this:
static Database _db;
static Future<Database> get db async {
    if( _db == null )
        _db = await openOrCreateDatabase();
    return _db;
}

Now, I want to perform a query on the db:
final List<Map<String, dynamic>> rows = await (await db).query(
    'mytable',
    where: 'id<?',
    whereArgs: [10]
);

I find the await (await db) ugly - is there a nicer way to "chain" two await's together in serial?

A: Since both operations returns a Future there is no other way that await for the two operations. To await multiple futures with a single await you need to add it to a list of futures and then use Future.wait but generally is more ugly and useless in this case.
      var futures = <Future>[];
      futures.add(operationThatReturnAFuture());
      futures.add(operationThatReturnAFuture());
      await Future.wait(futures);

Dart does not support this kind of chaining between await but i understand that looks odd on this case.
Maybe if you change the variable rows to a method the code will look a little cleaner.
For example something like:
getUser(int id) async {
    final db = await database;
    var res = await  db.query("User", where: "id = ?", whereArgs: [id]);
    return res.isNotEmpty ? User.fromMap(res.first) : Null ;
  }

A: An alternative is to use the old syntax then():
Future getDb() => db;
Future makeQuery(db) => db.query(
    'mytable',
    where: 'id<?',
    whereArgs: [10]
);

void doSomethingWithQuery(query){}

getDb().then(makeQuery).then(doSomethingWithQuery);

The code reads naturally this way, "get the database, then make a query, then do something else". I don't think async keyword is needed for getDb() and makeQuery(db) but I might be wrong.
As a side note, the get db method could be streamlined using the null-aware ??= operator:
static Future<Database> get db async => _db ??= await openOrCreateDatabase();


text: Q: How do I prevent a footnote bar from a graphics page with no footnote? I have a page with a graphic that fills the entire page.  The previous page has a footnote.  The horizontal line that separates the footnote from the text appears on both pages (the one with the text and footnote and the page with the graphic).  How can I prevent the footnote bar from appearing on the graphic page?


text:
Q: Core data not working on device but fine on simulator I am using core data for my application.It works fine on simulator but not retreiving the details on real device.Device is of iOS6.1.This is the code i am using:
- (NSManagedObjectContext *) getCurrentMangedContext
{
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"ForceData" withExtension:@"momd"];
    NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    NSURL *storeURL =  [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]URLByAppendingPathComponent:@"ForceData.sqlite"];

    NSError *error = nil;
    NSPersistentStoreCoordinator *persistantStroreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
    if (![persistantStroreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {

    }
    NSManagedObjectContext *managedContext = [[NSManagedObjectContext alloc] init] ;
    [managedContext setPersistentStoreCoordinator:persistantStroreCoordinator];
    modelURL = nil;
    return  managedContext;
}

This is how i am saving my login details and it is not giving any error.
 NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
  [request setEntity:entity];
  NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
    if (emailString != nil)
    {
       [newManagedObject setValue:emailString forKey:@"email"];
    }
    if (genderString != nil)
    {
        [newManagedObject setValue:genderString forKey:@"gender"];
    }
    if (fNameString != nil)
    {
        [newManagedObject setValue:fNameString forKey:@"firstName"];
    }
    if (lNameString != nil)
    {
        [newManagedObject setValue:lNameString forKey:@"lastName"];
    }
   if (userIDString != nil)
    {
        [newManagedObject setValue:userIDString forKey:@"userID"];
    }
  NSError *error = nil;
    if (![context save:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    // Insert User details to the user DB <--------------------------

And this is how i am retrieving:
- (User *) getActiveUser
{
    NSManagedObjectContext *context = [self getCurrentMangedContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
    [request setEntity:entity];

    NSError *errorFetch = nil;
    NSArray *array = [context executeFetchRequest:request error:&errorFetch];
    User *objUser = (User *) [array lastObject];
    NSLog(@"%@",objUser);

    return objUser;
}

But i am not getting the user details on device but getting on simulator.anyone faced this same?

A: In your case I'd suggest that ARC releases your managedObjectContext after executing the fetch request.
Make sure that you hold a strong reference to the appropriate managedObjectContext during the whole lifetime of your managedObject somewhere in your app (e.g. your  ApplicationDelegate). A NSManagedObject can't live without it's managedObjectContext. The Core Data project template shows how to do that.
Further information about ARC and strong references: https://developer.apple.com/library/mac/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html


text:
Q: python tkinter overrideredirect; cannot receive keystrokes (Linux) I have a python tkinter application which I want to run full screen. When I uncomment overrideredirect, the window manager (Gnome, Linux) will not be able to forward keystrokes to the application anymore.
(fragment, python)
# make it cover the entire screen
w, h = master.winfo_screenwidth(), master.winfo_screenheight()
self.root.geometry("%dx%d+0+0" % (w, h))
self.root.focus_set() # <-- move focus to this widget
self.root.bind('<Escape>', self.root.quit())
#self.root.overrideredirect(True)

I've found the window::or package for Tcl/Tk, which is supposed to resolve this bug. How would I go about installing this, and would it be possible to use it from within my python application?
http://www.binarism.com/tk/window/or/
http://www.binarism.com/tk/window-or-0.1.1.tgz

A: This works for the use case where you're using overrideredirect to get fullscreen, which is somewhat common:
#self.root.overrideredirect(1)
self.root.attributes('-fullscreen', True)

A: You might want to enter the callable self.root.quit instead of self.root.quit() when you do the binding to avoid calling the function. when you will press Escape the callable will be called (I know I know) with an event argument. If self.root.quit() does not accept any argument: use lambda: self.root.bind('<Escape>',lambda e:self.root.quit())


text:
Q: Hide loader from jwPlayer I want to hide/remove loader from jwPlay. Just want to display a black screen or custom loader.
I have checked the document but I am not getting any kind of stuff like this. Even I have tried to hide the loader from with the CSS but I don't find any HTML content of the loader.


text:
Q: Permissions Error using API command to get Workitems for a Pull Request I am trying to get all workitems, linked to all pull requests in a repo.
First, I run the API Command to get all Pull Requests:
   https://dev.azure.com/{organization}/{project}/_apis/git/pullrequests?api-version=5.1
That works just fine.
Then Looping through each Pull Request, I try to get all Work Items
https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/workitems?api-version=5.1
Even though I am an Admin, I still get this error:
innerException
:
null
message
:
TF401019: The Git repository with name or identifier {MY Repo ID} does not exist or you do not have permissions for the operation you are attempting.
typeName
:
Microsoft.TeamFoundation.Git.Server.GitRepositoryNotFoundException, Microsoft.TeamFoundation.Git.Server
typeKey
:
GitRepositoryNotFoundException
errorCode
:
0
eventId
:
300
Can Anyone help me figure out how to get these related work items for the pull requests?
API Web Pages:
https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull%20requests?view=azure-devops-rest-5.1
https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull%20request%20work%20items/list?view=azure-devops-rest-5.1

A: I figured out what was wrong.
When using the API call to get the workitems for a given Pull Request,  I was using the RepoID field that I got back from the previous command.
Instead of using RepoID as the Repo ID in the New Command to get work items, I had to use the Repo Name.
SO the solution is to use this:
value.0.repository.name
instead of this:
value.0.repository.id
from the first call to get pull requests.


text:
Q: Architecture of Wizard type Image Processing App We are building a wizard-style image processing software. It consists of three layers: GUI, Engine and Core_Algorithms.
Wizard: Each "panel" of the app asks the user to do something. Example: first panel asks the user to load some images, the next panel applies "seed region growing" (SRG) algorithm and asks the user to adjust the result by using "magic wand tool".
What happens behind the scene: All the algorithms are kept in the package "core" (and are completely independent of the GUI). All the data items (for the entire app) are stored in single class (Data.java).
Data.java
/*Stores ALL the necessary data items*/
public class Data{

    BufferedImage sourceImage, targetImage;
    BufferedImage srcGrownImg;
    Point srcPoint, tarPoint;//and many more data items for each algorithm and panel
}

Another class (Engine.java, which is extended from Data.java) uses those data items, runs appropriate algorithms (like SRG.java from "core" package) and stores the items (inside Data.java).
Each phase of wizard has the same instance of "Engine.java", so that they can set, run algorithms and get the results.
Engine.java
/*Runs algorithms inside "core"*/
public class Engine extends Data{
    public growSource()
    {
        SRG srgObj = new SRG(srcImg, srcSeeds);
        srcGrownImg = srgObj.runAndGetResult();
    }//and many more functions for each panel
}

Problem: The problem we are having is that "Data.java" and "Engine.java" are too long. Engine.java consists of functions which are short and sweet (3-4 lines) (but all the functions used by the entire wizard are stored inside it, thus making it really long).
Question: I want advice on how to break the code up, so that "Data.java" and "Engine.java" become shorter.

A: You may be able to apply the adapter pattern to evoke disparate implementations of a common interface, such as runAndGetResult(). The result is to have as many concrete implementations as there are ways to effect runAndGetResult().
This example illustrates he pattern for a single abstract function, eval(), but multiple interfaces may be implemented. A class literal is used as a runtime type token to obtain an implementation by name, but a registry is also possible.
In a GUI, the adapter might extend AbstractAction for use in buttons, menu items and other components that accept Action. For off-line processing, a list of adapters could be composed in the GUI and later evaluated in the prescribed order in another thread.


text:
Q: Unable to compile java class file in cmd I am in c:\new\control folder and want to execute c:\hello.java
I am trying c:\new\control> javac c:\hello.java
Its creating class file but  c:\new\control> java hello is giving me Error:could not find o load main class hello
In simple way i wan ask , i have class file in c:\ (say c:\hello.class)
I am in c:\user, how can i execute it???

A: By default, the .class file will be generated alongside the .java file. Options:

*

*Use -d . when compiling to generate the classes relative to the current directory (including creating subdirectories for packages):
> javac -d . c:\hello.java
> java hello

*Specify a classpath when running:
> java c:\hello.java
> java -cp c:\ hello

A: I hope you have created class with different name in your file hello.java.  So, try to find out class file with the name of class you mentioned in hello.java file after compilation.


text:
Q: GWT Create column with custom cell type I'm trying to use the code from https://stackoverflow.com/a/6966235/1339354 in my project. I defined the following class:
public class SeoClickableCell extends AbstractCell<WebmasterObject> {

public SeoClickableCell() {
    super("click", "keydown");
}

@Override
public void render(Context context, WebmasterObject value, SafeHtmlBuilder sb) {
     if (value != null) {
         sb.appendHtmlConstant("");
         sb.appendEscaped(value.getName());
         sb.appendHtmlConstant("");
     }
}

@Override
public void onBrowserEvent(Context context, Element parent, WebmasterObject value, NativeEvent event, ValueUpdater<WebmasterObject> valueUpdater) {
    if (value == null)
        return;

    super.onBrowserEvent(context, parent, value, event, valueUpdater);
    if ("click".equals(event.getType())) {
        //TODO
    }
}

};
But I'm trying to create a custom column in my CellTable. but the following code:
final SeoClickableCell cell = new SeoClickableCell();
    Column<WebmasterObject, String> nameColumn = new Column<WebmasterObject, String>(cell) {
        @Override
        public String getValue(WebmasterObject WebmasterObject) {
            return WebmasterObject.getName();
        }
    };

Tells me:

The constructor Column(SeoClickableCell) is undefined

And that I should make SeoClickableCell implement Cell or change the type of "cell".
I'm not sure if I'm grasping correctly the procedure to make custom cells/columns, so any help would be appreciated.

A: I solved it changing the type and implementation of SeoClickableCell to this:
public class SeoClickableCell extends AbstractCell<String> {

public SeoClickableCell() {
    super("click", "keydown");
}

@Override
public void render(com.google.gwt.cell.client.Cell.Context context, String value, SafeHtmlBuilder sb) {
     if (value != null) {
         sb.appendHtmlConstant("");
         sb.appendEscaped(value);
         sb.appendHtmlConstant("");
     }
}

@Override
public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater) {
    if (value == null)
        return;

    super.onBrowserEvent(context, parent, value, event, valueUpdater);
    if ("click".equals(event.getType())) {
        //TODO
    }
}

};
and making the column like this:
final SeoClickableCell cell = new SeoClickableCell();
    Column<WebmasterObject, String> nameColumn = new Column<WebmasterObject, String>(cell) {
        @Override
        public String getValue(WebmasterObject wbo) {
            return wbo.getName();
        }
    };


text:
Q: Cant write data to firebase database Android I am trying to send test data to my firebase database. In android studio I chose Tools > Firebase > Assistant FB > Realtime Database > Connect your app to Firebase(Connected) > Add the realtime database to your app(dependencies set up correctly).
Then I add sample code in my activity:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");

myRef.setValue("Hello, World!");

I set the rules in firebase:
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

But the data does not add to the realtime database. Maybe I need some permission? In logcat AS nothing error
UPD:
not add data
    private DatabaseReference mDatabase;
 mDatabase = FirebaseDatabase.getInstance().getReference();
        mDatabase.child("message").setValue("Hello, World!");

not add data too
Message mess = new Message("hello");
        mDatabase.child("message").setValue(mess);

class Message
@IgnoreExtraProperties
public class Message {

    public String mes;

    public Message(){}

    public Message(String mes) {this.mes = mes;}

}

A: Check and ensures your are submitting data to firebase else firebase will not write to your database.

A: I had the same problem as yours. Please go again to Tools -> Firebase -> Realtime Database -> and make sure that you Firebase is connected and Realtime Database is set up. Hope it helps.)


text:
Q: Cannot modify header information - headers already in checkout.php on line 84 I have spent days trying to fix this and cannot find any sort of output or white spaces before the two headers.
Any help would be greatly appreciated.
Thank you.
On jcart.php I cannot find any white spaces or output either.
<?php
include_once('jcart/jcart.php');
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST['userform']))
{
    // This query retreives the user's information from the database using
    // their email.
    $query = "
        SELECT
            id,
            email,
            password,
            salt
        FROM customers
        WHERE
            email = :email
    ";
    // The parameter values
    $query_params = array(
        ':email' => $_POST['email']
    );
    try
    {
        // Execute the query against the database
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch(PDOException $ex)
    {
        // Note: On a production website, you should not output $ex->getMessage().
        // It may provide an attacker with helpful information about your code.
        die("An error has occurred. Please e-mail X to report the problem.");
    }
    // This variable tells us whether the user has successfully logged in or not.
    // We initialize it to false, assuming they have not.
    // If we determine that they have entered the right details, then we switch it to true.
    $login_ok = false;
    // Retrieve the user data from the database.  If $row is false, then the email
    // they entered is not registered.
    $row = $stmt->fetch();
    if($row)
    {
        // Using the password submitted by the user and the salt stored in the database,
        // we now check to see whether the passwords match by hashing the submitted password
        // and comparing it to the hashed version already stored in the database.
        $check_password = hash('sha256', $_POST['password'] . $row['salt']);
        for($round = 0; $round < 65536; $round++)
        {
            $check_password = hash('sha256', $check_password . $row['salt']);
        }

        if($check_password === $row['password'])
        {
            // If they do, then we flip this to true
            $login_ok = true;
        }
    }
    // If the user logged in successfully, then we send them to the private members-only page
    // Otherwise, we display a login failed message and show the login form again
    if($login_ok)
    {
        // Here I am preparing to store the $row array into the $_SESSION by
        // removing the salt and password values from it.  Although $_SESSION is
        // stored on the server-side, there is no reason to store sensitive values
        // in it unless you have to.  Thus, it is best practice to remove these
        // sensitive values first.
        unset($row['salt']);
        unset($row['password']);
        // This stores the user's data into the session at the index 'user'.
        // We will check this index on the private members-only page to determine whether
        // or not the user is logged in.  We can also use it to retrieve
        // the user's details.
        $_SESSION['user'] = $row;
        // Redirect the user to the private members-only page.
        header("Location: checkout.php");
        die("Redirecting to: checkout.php");
    }
    else
    {
        // Tell the user they failed
        header("Location: checkout.php?msg=failedlogin");
        // Show them their email again so all they have to do is enter a new
        // password.  The use of htmlentities prevents XSS attacks.  You should
        // always use htmlentities on user submitted values before displaying them
        // to any customers (including the user that submitted them).  For more information:
        // http://en.wikipedia.org/wiki/XSS_attack
    }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

A: Sometimes it helps to put a ob_start(); at the top, dirty fix.
And how about common.php, any output or whitespace in that file?

A: When you are trying to send header information (its about header("Location: some.php");, the headers of page mustnt been sent before, headers may sent from any 'echo', or header function, or whitespaces before <?php tags.
If you can't handle the headers turn of the buffering at the top of your script by ob_start(); function.

A: Maybe the file is encoded in UTF-8 BOM? The BOM (Byte Order Mark) will start the session. Try saving the file without the BOM.
UTF-8 BOM signature in PHP files


text:
Q: How can I reshape the tensor tensor([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0])

I want to remove 0 from this tensor, which is a two-dimensional array, and make it a one-dimensional array.
How can I make this tensor with the tensor below?
tensor([[17],
        [93],
        [4],
        [72],
        [83],
        [67],
        [34],
        [21],
        [19])

A: Assuming that the tensor is a numpy array.
Firsly, flatten the matrix using x= x.flatten()
Then remove all occurences of zeros using x = x[x!=0]
Then reshape the array back in 2D using x = np.reshape(x, ( -1, x.shape[0] ))
This (x) would return you:
array([[17, 93,  4, 72, 83, 67, 34, 21, 19]])

A: In Tensorflow, you can simply use a boolean_mask:
import tensorflow as tf

tensor = tf.constant([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0]])
tensor = tf.boolean_mask(tensor, tf.cast(tensor, dtype=tf.bool), axis=0)

tf.Tensor([17 93  4 72 83 67 34 21 19], shape=(9,), dtype=int32)


text:
Q: Append multiple lines after a certain pattern to several JSON files I have several JSON files that look like this
{
"$schema": "someURL",
  "id": "someURL",
  "type": "object",
  "properties": {
    "copyright": {
      "id": "someURL",
      "type": "object",
      "description": "Setup for copyright link",
      "properties": {
        "translation": {
          "id": "someURL",
          "type": "string",
          "description": "someString"
        },
        "url": {
          "id": "someURL",
          "type": "string",
          "description": "someString"
        }
      }...

what I need to do is add a removable and appendable attribute to each item inside every instance of properties and set them to true. so the output should look like this:
{
    "$schema": "someURL",
      "id": "someURL",
      "type": "object",
      "properties": {
        "copyright": {
          "removable": true,
          "appendable": true,
          "id": "someURL",
          "type": "object",
          "description": "Setup for copyright link",
          "properties": {
            "translation": {
              "removable": true,
              "appendable": true,
              "id": "someURL",
              "type": "string",
              "description": "someString"
            },
            "url": {
              "removable": true,
              "appendable": true,
              "id": "someURL",
              "type": "string",
              "description": "someString"
            }
          }...

Is there a way to automate this? as in write a script that automatically adds these fields right below each item in properties?

A: using NodeJS I would write something like this:
const fs = require('fs');
let args = process.argv.map(val=>val));
let contents = fs.readFileSync(args[0]);

let obj = JSON.parse(contents);

const proc = (obj, append)=>{
    for (prop in obj)
    {
        let p = obj[prop];
        if (p.constructor!=Object)
            continue;
        if (append)
        {
            p.removable = true;
            p.appendable = true;
        }
        proc(p, prop=='properties');
    }
};

console.log(JSON.stringify(proc(obj), null, 2));

And then in bash do:
find -name '*\.json' -exec 'node proc.js {} > {}.new'

I didn't test anything, everything is from my head, but for starting point should be good enough.

A: Given that you want to apply the update to all objects that have a key named "properties", wherever they occur, I'd be inclined to use walk/1. In any case, to make things clearer and maybe easier, it will be helpful to define a helper function that will apply the update if the input is of the right type:
def update(obj):
  if type == "object" and has("properties")
  then .properties |= with_entries( .value += obj )
  else .
  end;

Using walk/1, the solution is now trivial:
walk( update({removable: true, appendable: true}) )

Robustification
It might be prudent to change the "then" line above to:
then .properties |=
  with_entries( if .value | type == "object"
                then .value += obj
                else . end)


text:
Q: Middleware not catching exceptions I want to use middleware to handle some special exceptions through all project. But the middleware is almost never called when an exception is raised and I don't understand a reason of this behavior.
Middleware class:
import logging
log = logging.getLogger(__name__)

class ExceptionMiddleware(object):
    def process_exception(self, request, exception):
        log.error("Сaught exception: %s"% exception)

My Middleware classes:
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
     # Exception middleware
    'middleware.ExceptionMiddleware',
 )

Maybe I found a reason. Instance of the specific class is created out of the all view as global value and exception is raised before some view is called. So another part of question, how I can catch those exceptions?


text:
Q: Does it make sense to use a varchar column as foreignkey reference? Given two tables books and authors where each of them already have a unique key which is of varchar type which identifys them throughout my ecosystem. Does it make sense to use those keys as Foreignkeys in the Many-To-Many-Table or should I invent a primary key in the tables authors and books which is of type int to avoid overhead? The length of those keys already existing is not more then 255.

A: I always prefer surrogate keys. It protects you from unkown changes in the future, because it is decoupled from application data.

A: I think the better way is to use int key as primary key. Firstly - you will avoid overhead, secondly - you will gain some performance.

A: int will be the better way.  you may have a large effort to redo existing data however - which may influence you to not make the change...
i would suggest that making this change earlier rather than later will be easier for you in the long run.

A: Creating a new Primary Key is a good idea,
as a primary key also enforces a not null constraint.

A: While I also think int keys are better, I don't think you should make any changes to your primary keys as it already works. Your varchar keys may make sense if it is, for exemple, ISBN codes for the books. If it's not broken, don't fix it.


text:
Q: How to addclass to a different element? Due to the great help of ori, I've got a script working exactly as I wanted. Unfortunately, due to my own limited jQuery knowledge - I can't get the next phase working!
Now I want to expand it further by assigning a function to a different element if the href matches.
The code that works, and correctly assigns a class is:
    <script type="text/javascript">
    $(function(){
    var matches;
   if( matches = location.href.match(/\?(pcat=\w+)/) ) {
    $('a[href*="' + matches[1] + '"]').addClass('active');
};
  });
</script>

This will successfully add the class 'active' to the original a href element. What I want to do now is instead of assign the class to the link, is to open accordion menu that contains the href links on page load.
So I was thinking something along the lines of:
    <script type="text/javascript">
    $(function(){
    var matches;
   if( matches = location.href.match(/\?(pcat=\w+)/) ) {
    $('a[href*="' + matches[1] + '"]').function() {
        $('p.menuheader').addclass('openheader');}
      );
    });

</script>

But It doesn't work, I think I've got syntax errors.
Any help would be much appreciated! :)

A: In your first example you correctly call addClass with a capital C.
In your second example you call addclass with a lowercase c which probably doesn't work.

A: Try this using each and closest method to find the containing element. Also change addclass to addClass.
$('a[href*="' + matches[1] + '"]').each(function() {
    $(this).closest('p.menuheader').addClass('openheader');}
});

A: If you mean that "accordion menu that contains the href links", why just not do like:
 $('a[href*="' + matches[1] + '"]').parent().addclass('openheader');


text:
Q: Using document.write with an  The code below works as is. I want to use this code to display specific Twitch streams based on the page that is loaded.
<script type="text/javascript">
    var stream = location.pathname;
    switch (stream) {
       case "/defatank":
          document.write("Defatank's Live Stream Page");
          break;
       case "/seeingblue":
          document.write("SeeingBlue's Live Stream Page");
          break;
       case "/shiroshii":
          document.write("Shiroshii's Live Stream Page");
          break;
       case "/theend66":
          document.write("TheEnd66's Live Stream Page");
          break;
       case "/wakawaka647":
          document.write("WakaWaka647's Live Stream Page");
          break;
       case "/xtheguythatplays":
          document.write("XTheGuyThatPlays' Live Stream Page");
          break;
    }
    </script>

When I try to replace

"Defatank's Live Stream Page"

with the object below it doesn't work and breaks the rest of the cases.
<object type="application/x-shockwave-flash" height="378" width="620" id="live_embed_player_flash" data="http://www.twitch.tv/widgets/live_embed_player.swf?channel=defatank" bgcolor="#000000"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="movie" value="http://www.twitch.tv/widgets/live_embed_player.swf" /><param name="flashvars" value="hostname=www.twitch.tv&channel=defatank&auto_play=true&start_volume=25" /></object>

I'm sure I'm probably using document.write wrongly or should be using something entirely different. Any suggestions?
EDIT:
Here is what the finished product looks like.
<script type="text/javascript">
    var stream = location.pathname;
    switch (stream) {
       case "/defatank":
          document.write("<object type="application/x-shockwave-flash" height="378" width="620" id="live_embed_player_flash" data="http://www.twitch.tv/widgets/live_embed_player.swf?channel=defatank" bgcolor="#000000"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="movie" value="http://www.twitch.tv/widgets/live_embed_player.swf" /><param name="flashvars" value="hostname=www.twitch.tv&channel=defatank&auto_play=true&start_volume=25" /></object>");
          break;
       case "/seeingblue":
          document.write("SeeingBlue's Live Stream Page");
          break;
       case "/shiroshii":
          document.write("Shiroshii's Live Stream Page");
          break;
       case "/theend66":
          document.write("TheEnd66's Live Stream Page");
          break;
       case "/wakawaka647":
          document.write("WakaWaka647's Live Stream Page");
          break;
       case "/xtheguythatplays":
          document.write("XTheGuyThatPlays' Live Stream Page");
          break;
    }
    </script>

I also tried removing the "" from document.write() and it still dont load and breaks the rest of the cases.

A: For your specific case the easiest fix (in my opinion) is to change the double quotes for the attributes in object to single ones (else it ends the document.write string). This should work
<script type="text/javascript">
    var stream = location.pathname;
    switch (stream) {
       case "/defatank":
          document.write("<object type='application/x-shockwave-flash' height='378' width='620' id='live_embed_player_flash' data='http://www.twitch.tv/widgets/live_embed_player.swf?channel=defatank' bgcolor='#000000'><param name='allowFullScreen' value='true' /><param name='allowScriptAccess' value='always' /><param name='allowNetworking' value='all' /><param name='movie' value='http://www.twitch.tv/widgets/live_embed_player.swf' /><param name='flashvars' value='hostname=www.twitch.tv&channel=defatank&auto_play=true&start_volume=25' /></object>");
          break;
       case "/seeingblue":
          document.write("SeeingBlue's Live Stream Page");
          break;
       case "/shiroshii":
          document.write("Shiroshii's Live Stream Page");
          break;
       case "/theend66":
          document.write("TheEnd66's Live Stream Page");
          break;
       case "/wakawaka647":
          document.write("WakaWaka647's Live Stream Page");
          break;
       case "/xtheguythatplays":
          document.write("XTheGuyThatPlays' Live Stream Page");
          break;
    }
</script>

The JavaScript interpreter needs to know where a string begins and ends and the quote marks are used to do that. You can use single or double quotes for JavaScript strings. If you want to use the same quote type in a string that you used to deliminate the string, then that quote characters must be escaped - otherwise the interpreter gets confused and thinks the string has ended early.
Some examples
1. "Good string"
1. "Broken "hi" string"
1. "Good 'hi' string"
1. "Good \"hi\" string"

The 2nd string will not work because the interpreter thinks it ended just before the word hi - as indicated by the double quotes.
The 3rd string is fine because it uses single quotes for hi instead.
The 4th string is also fine because it "escapes" the double quote characters to let the interpreter know the following character should be treated literally and not as JavaScript code.
There's a little more details on JavaScript strings here: http://www.w3schools.com/js/js_obj_string.asp
So in summary, as the HTML spec allows for single, double, or not quoted attributes, changing the double quotes to single resolves the issue.

A: You need to escape the quotation marks inside the string if you use quotation marks as delimiters. Usually I use apostropes to delimit a string that has quotation marks.
(Note however that the & characters in the attributes should be HTML encoded as & to make it correct HTML code.)
document.write('<object type="application/x-shockwave-flash" height="378" width="620" id="live_embed_player_flash" data="http://www.twitch.tv/widgets/live_embed_player.swf?channel=defatank" bgcolor="#000000"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="movie" value="http://www.twitch.tv/widgets/live_embed_player.swf" /><param name="flashvars" value="hostname=www.twitch.tv&channel=defatank&auto_play=true&start_volume=25" /></object>');

A: According to http://www.w3schools.com/jsref/met_doc_write.asp,
The write() method writes HTML expressions or JavaScript code to a document.

This means that you can't pass a DOMObject or regular Object into document.write. If that "object" you listed was actually a string, then you could pass it into document.write. If you're trying to add a DOMObject to the page, try using document.body.addChild(object);

A: You definitely do not want to use document.write. Instead, use the DOM methods to create and append the element:
var obj = document.createElement('object'),
    param = document.createElement('param');
object.setAttribute('type', 'application/x-shockwave-flash');
param.setAttribute('name', 'allowFullScreen');
obj.appendChild(param);
// rest of params and attributes
document.body.appendChild(obj);


text:
Q: Как связать 3 таблицы в SQL запросе? Здравствуйте, как связать 3 таблицы в SQL запросе ?
Имею вот такой запрос(связывает 2 таблицы)
SELECT categories.title, goods.name, goods.id
 FROM categories
 INNER JOIN goods
 ON categories.id = goods.category
 ORDER BY categories.id;

нужно связать  таблицу orders (orders.items_id связать с goods.id)
структура таблицы :

 categories|   goods      |  orders
 --------- |--------------|-------------
 id(Pk)    |  id(Pk)      |  id(Pk)
 title     |  name        |  items_id
 ----      |  category    |  ---

A: Если не ошибаюсь
SELECT categories.title, goods.name, goods.id
FROM (categories
INNER JOIN goods
ON categories.id = goods.category)
INNER JOIN orders
ON orders.items_id = goods.id
ORDER BY categories.id;


text:
Q: Getting picture data from iOS photo gallery I need to get metadata (EXIF and other) from images stored in the iOS photo gallery. Therefore I need the original picture data instead of an UIImage object.
At the moment I get the asset-image url using imagepickercontroll and ALAssetsLibrary as described here: display image from URL retrieved from ALAsset in iPhone
This url can be used to get an UIImage object but how can I get the original image so that I can process it's metadata?
Regards,

A: ALAssetsLibrary to retrieve all images here
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:assetURL
resultBlock:^(ALAsset *asset)  {
    NSDictionary *metadata = asset.defaultRepresentation.metadata;
    imageMetadata = [[NSMutableDictionary alloc] initWithDictionary:metadata];
    [self addEntriesFromDictionary:metadata];
}
failureBlock:^(NSError *error) {
}];
[library autorelease];

Refer more getting-metadata-from-images-on-ios link and get helped.


text:
Q: Git: use revert or checkout to undo pushed changes? Git is a phenomenal tool, but I have yet to wrap my mind around the best way to undo pushed changes.  Here's the situation.
I'm on a branch, and have pushed several commits to GitHub.  It has since been decided that I've gone too far down the rabbit hole, and we need to scrap several of the commits I've done, and start over.  Essentially, I need to reverse all of the pushed commits, back to a previous one.  Here are the two commands that I think are appropriate
git revert  # - creates a new commit that "undoes" the changes of one specific commit
git checkout 'commit SHA' # - sets the head to that specific commit, wherein I will re-push to the repo, undoing my changes... I think

So, am I right? Do I need to do a git checkout on the specific commit I want to return to? Or is there something in this convoluted process that I am not understanding?
Thanks.

A: There are two scenarios depending on the state of what you pushed:

*

*Nobody has used the pushed branch for anything yet. In that case you can use git reset to force the local branch to a specific commit - and then you can git push the branch with a --force parameter.

*If, however, there are someone who has based his work off on the branch you accidentally pushed, then you can't really reset it, as he will then be basing his changes off of a branch in limbo. This is where git revert comes into play. It will record an inverse patch effectively undoing earlier changes. The advantage here is that other can base their work on the branch with ease.
The choice of method depends on how your repository is and for how long the accidental patches have been up there. If there are few developers, communication and a reset is probably the answer. But have the thing lived for a long time, it is probably better to revert - unless you want to rewrite the whole history!
Another way to look at it is this: git revert is persistent whereas git reset / git push --force is destructive rewriting of the history. There is an appropriate time for both.
Finally, when I delve to follow Alice down the Rabbit hole and investigate what lies beyond, I usually do it on locally created branches. Then if I like the changes, I usually merge them into a test branch and let them stir a bit on the test branch, before I merge them to master. That way you avoid the problem a lot of the time. In Short, I often have 20-30 local branches, one for each feature I am working on. They tend to be tested individually first. Occasionally, I create a new branch test and merge everything into that branch and do all the tests together. To track conflicts across branches I use git rerere. The advantage is that I can decide when a feature is stable enough to push to others.

A: Try git reset: http://git-scm.com/docs/git-reset

A: As Horia pointed out correctly you'll need git reset.
Git checkout means you switch to another branch or by using checkout -b you can create a new branch and switch to it right away.


text:
Q: Openssl p12 certificate storage extract individual certificates preserving names I have a p12 storage of certificates, and there are a lot of certificates, they are related to a few different sites, so there are a lot of certs for one site. Im trying to extract them all in a way, that will preserve their names, because there is an important information on the name, identifying cert user by private data. But so far i tried this:
pkcs12 -in myDatabaseCerts.p12  -clcerts -nokeys -out publictheCerts.pem

This way i can get all certificates into one file.
And
openssl pkcs12 -in myDatabaseCerts.p12 -nocerts -out keys.pem

Is there a way i can extract all this data into individual file of crt and key and preserve their names automatically? So i would get the list in the end like:
John_Williams_ID_18321239.crt and John_Williams_ID_18321239.privatekey(or .pem)
I want to split the p12 into files like this because later i need to assemble each pair into individual p12 file, so basically convert the whole p12 storage, into many many individual files which contains only one key : certificate pair. Is there a way you can do this with openssl? Or only way would be to generate to separate files with key and certificate and parse them using some written script?

A: Much as you speculated, you can easily parse the output of openssl pkcs12 to split apart the pieces if and only if the identifier you want is the friendlyname and/or localkeyid, because those are the only two pieces of metadata usually provided. For example for the private keys using only friendlyName because it's easier and should usually be enough:
openssl pkcs12 -in combined -nocerts | awk '/friendlyName:/{n=$2} \
/^-----BEGIN.*PRIVATE/,/^-----END.*PRIVATE/{print >n".key"}'

This requires you to type the password of the input p12, and type twice a password for each output key; to avoid this you can add -passin and -passout options as per the man page (assuming it's okay for all output keys to use the same password). Or if it's okay to have the privatekeys NOT encrypted, add -nodes -- if you promptly put these back into new (and encrypted) p12 files and securely erase (e.g. shred) the unencrypted files that should be safe; otherwise you need to be very careful no unauthorized person can look at or get a copy of the unencrypted privatekeys.
The same thing can be done for the certificates, but you may not need to. If the only thing you want is to create individual p12 files as you described, and your privatekeys are all different, you can just do for each privatekey
cat $one.key allcerts | openssl pkcs12 -export (other options) >$one.p12

and it will put in each output p12 only the one cert from the input allcerts that matches the key.
Alternatively, instead of the pre-written openssl commandline, you can write a program using openssl library that does anything you like: poke around inside each of the bags and subbags (after decryption), pull out whatever data you like, modify it (perhaps translate special characters etc), and so on. That's a significantly bigger job, though.


text:
Q: URL Rewrite Module appendQueryString I'm having the following problem ..
The Rewrite is concatenating the querystring in the URL of the page where there is a postback.
That is, I have a search page with pagination and it works perfectly. But when I click to go to the second page the address is this:
http://localhost/aaa/bbb/search-result?q=ccc

for this
http://localhost/aaa/bbb/search-result?param1=aaa&param2=bbb-0&page=% 2fsearch-result

Have we set the appendQueryString to false. But without success ..
What do you suggest?

A: The solution is to override this tag < form id="form1" runat="server"> tag as shown in this link.
http://msdn.microsoft.com/en-us/library/ms972974.aspx Go to this url and search for "Handling Postbacks" I think that could help you