text:
Q: Does HBase uses a primary index? How does HBase performs a lookup and retrieves a record ?
e.g., what is the equivalent in HBase for the RDBMS's B-Trees?
[EDIT]
I understand how HBase resolves the -ROOT-, and .META. tables to find out which region holds the data. But how is the local lookup performed?
To better illustrated, here's an example:

*

*I am starting a search (get or scan) for record with key 77.

*HBase client figures that the key is contains in the 50-100 region,
held by RegionServer X.

*HBase client contacts RegionServer X to get the data.

How does RegionServer X finds out the location of record 77 ?
Does the RegionServer uses some kind of lookup table (e.g. like the RDBMS's B-Trees ?) for the keys of a region ?
Or does it need to read all contents of the StoreFiles, for records from 50 to 77 ?

A: TL;DR: it looks like HBase (like BigTable), uses as a structure similar to a B+ tree to do the lookup. So the row-key is the primary index (and the only index of any sort in HBase by default.)
Long answer: From this Cloudera blog post about HBase write path, it looks like HBase operates the following way:

Each HBase table is hosted and managed by sets of servers which fall
  into three categories:

*

*One active master server

*One or more backup master servers

*Many region servers

  Region servers contribute to handling the HBase tables. Because HBase
  tables can be large, they are broken up into partitions called
  regions. Each region server handles one or more of these regions.

There's some more detail in the next paragraph:

Since the row key is sorted, it is easy to determine which region
  server manages which key. ... Each row key belongs to a specific
  region which is served by a region server. So based on the put or
  delete's key, an HBase client can locate a proper region server. At
  first, it locates the address of the region server hosting the -ROOT-
  region from the ZooKeeper quorum.  From the root region server, the
  client finds out the location of the region server hosting the -META-
  region.  From the meta region server, then we finally locate the
  actual region server which serves the requested region.  This is a
  three-step process, so the region location is cached to avoid this
  expensive series of operations.

From another Cloudera blog post, it looks like the exact format used to save the HBase on the file system keeps changing, but the above mechanism for row key lookups should be more or less consistent.
This mechanism is very, very similar to Google BigTable's lookup (you will find the details in Section 5.1 starting at the end of page 4 on the PDF), which uses a three-level heirarchy to query the row-key location: Chubby -> Root tablet -> METADATA tablets -> actual tablet
UPDATE: to answer the question about lookups inside a Region Server itself: I don't know for sure, but since the row keys are sorted, and HBase knows the start and end keys, I suspect it uses a binary search or interpolation search, both of which are really fast - log(n) and log(log(n)) respectively. I don't think HBase would ever need to scan rows from the start row key to the one that it needs to find, since searches on sorted keys is well-known problem that has several efficient solutions.


text:
Q: TypeError: 'int' object is not callable error in python I am new to python, and have been doing a beginner's course on it.
I came across this piece of code during one of the lecture:
import datetime
DOB=input("Enter the DOB:")
CurrentYear=datetime.datetime.now().year()
CurrentAge=CurrentYear-int(DOB)
if(CurrentAge>=18):
    print("Your Age is {} and you are Adult".format(CurrentAge))
if(CurrentAge<18):
    print("Your Age is {} and you are not Adult".format(CurrentAge))
print("Condition has been verfied successfully")

This course that I am doing is from ~2018, and the instructor didn't have any error while compiling this code.

A: The issue is that the attribute year of datetime.datetime.now() is not a function, and so, it doesn't support year(). That's why it says that it is not callable. datetime.datetime.now().year is in int format, and since it is not a function, it is not callable (like this:.()).
Change CurrentYear=datetime.datetime.now().year() to CurrentYear=datetime.datetime.now().year.
The new code would be like this:
import datetime
DOB=input("Enter the DOB:")
CurrentYear=datetime.datetime.now().year
CurrentAge=CurrentYear-int(DOB)
if(CurrentAge>=18):
    print("Your Age is {} and you are Adult".format(CurrentAge))
if(CurrentAge<18):
    print("Your Age is {} and you are not Adult".format(CurrentAge))
print("Condition has been verfied successfully")

A: The issue is data types (hence TypeError). A data type may be a string, integer, or even a function (a function is something that is called, such as print(): notice the brackets).
You cannot put the brackets after an integer. That suggests you are trying to run it as a function.
The variable: datetime.datetime.now().year is an integer. You cannot run a function from an integer.

The correction would be from datetime.datetime.now().year() → datetime.datetime.now().year

The final code looks like this:
import datetime
DOB=input("Enter the DOB:")
CurrentYear=datetime.datetime.now().year
CurrentAge=CurrentYear-int(DOB)
if(CurrentAge>=18):
    print("Your Age is {} and you are Adult".format(CurrentAge))
if(CurrentAge<18):
    print("Your Age is {} and you are not Adult".format(CurrentAge))
print("Condition has been verfied successfully")

I have tested this thoroughly. Good luck with the rest of your Python course.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django : ModelForm with conditions I'm trying to create a form variable. As default Player have the level 0 and he can just change is name. Later when he is level 1, he can change is name and is avatar. When he is level 3, he can change is name, is avatar and is job. Etc...
Models.py:
class Player(models.Model):
    level = models.SmallIntegerField(default=0)
    name = models.CharField(max_length=50)
    avatar = models.URLField(default='http://default-picture.com/01.png')
    job =  models.TextField(null=True)

Fomrs.py:
class ProfileForm(forms.ModelForm):

class Meta:
    model = Player
    fields = ['name', 'avatar', 'job']
    widgets = {
        'name': forms.TextInput(),
        'avatar': forms.TextInput(),
        'job': forms.Textarea(),
    }

Views.py:
def game(request, id):
    user = get_object_or_404(Player, id=id)
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            return HttpResponse('Success')
    else:
        form = ProfileForm(instance=user)
    return render(request, "page/template.html",
            {'form': form})

Template.html:
{{ form }}

It's possible to add condition for the render of the form before send it to the render engime ? Or I need to do it in my Template with conditions ?
I just when to allow the instanced object to have more or less positibilies in terms of one of these parameters (in the exemple is the level of the player).

A: You can overwrite the form's __init__ method to remove or disable fields conditionally:
class ProfileForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.level < 3:
            self.fields['job'].disabled = True # still displays the field in the template
            # del self.fields['job'] # removes field from form and template
        if self.instance and self.instance.level < 1:
            self.fields['avatar'].disabled = True

A: Django pre_save signal can be used to solve this.
Before saving the model, the hook on pre_save will be called. You can write conditions in there to check if the user is allowed to change the fields.
You'll also need to store a copy of the model to compare the state in pre_save, it can be done through post_init hook.
from django.dispatch import receiver , Signal
from django.db.models.signals import post_init , pre_save

@receiver(pre_init , sender = Player)
def cache(sender , instance , **kwargs):
    instance.__original_name = instance.name
    instance.__original_avatar = instance.avatar
    instance.__original_job = instance.job
@receiver(pre_save , sender= Player)
def check_update(sender , instance , **kwargs):
    if instance.level == 1:
        #Revert changes to avatar and job, and keep changes in the name
    if instance.level == 2:
        #Revert changes to job , and keep changes in the name and avatar
    if instance.level == 3:
        #Keep all changes

This way you can keep track of all the updating fields.

A: You can achieve this customizing your form in its init method
To the situations described Before, you can do some as:
class ProfileForm(forms.ModelForm):

    class Meta:
        model = Player
        fields = ['name', 'avatar', 'job']
        widgets = {
            'name': forms.TextInput(),
            'avatar': forms.TextInput(),
            'job': forms.Textarea(),
        }

    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        # checking if an instance exist
        if self.instance.id:
            # then at this point you can set as read only the fields about each case

            if self.instance.level < 1:
                self.fields["avatar"].widget.attrs["readonly"] = True
                self.fields["job"].widget.attrs["readonly"] = True
            elif self.instance.level >= 1 and self.instance.level < 3:
                self.fields["job"].widget.attrs["readonly"] = True


text:
Q: Changing app entry point with Detox and React Native I would like to find out what the least evasive way is to change an app entry point for Detox testing in React Native?
For example, I would like to use Detox for Component testing and would like to skip the login flow of our app and directly launch the component I'm testing.
I suppose I could create a test App.js and manually change it to load that in the App.Registry for testing but there may be a better way.

A: Mock your entry point to a different one. You can follow our guide:
https://github.com/wix/Detox/blob/master/docs/Guide.Mocking.md


text:
Q: Caching in UI layer We've got a UI built using AngularJS (1.x) which interacts with a REST Service layer for all its data needs. The data in the UI is a simple object graph (JSON). The functionality in the UI is 99% display and just couple of cases where the UI allows user to update the data (which is saved to a DB by a backend REST service invoked by the Rest Service layer).
At present the UI layer makes call to REST layer which calls other back end REST services to get data (even if it already made such a call already).

*

*Is this a case where we should cache the data in the UI layer?

*Is the REST layer a better place to cache the data? why?

*What are the points to consider in this scenario?

*Are there any specific tool/library for caching in Angular 1.x apps?

The idea is to to reduce latency. Service layer hits incur a cost of seconds, this can be reduced to milliseconds if the ui avoids the backend calls.

A: You can use the $cacheFactory thats built into Angular and a HTTP interceptor to give you simple caching which works pretty well for most scenarios without changing much of your controller / service code!
The answer shown here has a great implementation that I have used before.
Note that this actually caches the HTTP response. Meaning any JSON in the response will have to be parsed every time you access it. However for 99% of cases this won't be a problem.


text:
Q: Lucene Index problems with "-" character I'm having trouble with a Lucene Index, which has indexed words, that contain "-" Characters.
It works for some words that contain "-" but not for all and I don't find the reason, why it's not working.
The field I'm searching in, is analyzed and contains version of the word with and without the "-" character.
I'm using the analyzer: org.apache.lucene.analysis.standard.StandardAnalyzer
here an example:
if I search for "gsx-*" I got a result, the indexed field contains
"SUZUKI GSX-R 1000 GSX-R1000 GSXR"
but if I search for "v-*" I got no result. The indexed field of the expected result contains:
"SUZUKI DL 1000 V-STROM DL1000V-STROMVSTROM V STROM"
If I search for "v-strom" without "*" it works, but if I just search for "v-str" for example I don't get the result. (There should be a result because it's for a live search for a webshop)
So, what's the difference between the 2 expected results? why does it work for "gsx-" but not for "v-" ?

A: ClassicAnalyzer handles '-' as a useful, non-delimiter character. As I understand ClassicAnalyzer, it handles '-' like the pre-3.1 StandardAnalyzer because ClassicAnalyzer uses ClassicTokenizer which treats numbers with an embedded '-' as a product code, so the whole thing is tokenized as one term.
When I was at Regenstrief Institute I noticed this after upgrading Luke, as the LOINC standard medical terms (LOINC was initiated by R.I.) are identified by a number followed by a '-' and a checkdigit, like '1-8' or '2857-1'. My searches for LOINCs like '45963-6' failed using StandardAnalyzer in Luke 3.5.0, but succeeded with ClassicAnalyzer (and this was because we built the index with the 2.9.2 Lucene.NET).

A: (Based on Lucene 4.7) StandardTokenizer splits hyphenated words into two. for example "chat-room" into "chat","room" and index the two words separately instead of indexing as a single whole word.  It is quite common for separate words to be connected with a hyphen: "sport-mad," "camera-ready," "quick-thinking," and so on. A significant number are hyphenated names, such as "Emma-Claire." When doing a Whole Word Search or query, users expect to find the word within those hyphens. While there are some cases where they are separate words, that's why lucene keeps the hyphen out of the default definition.
To give support of hyphen in StandardAnalyzer, you have to make changes in StandardTokenizerImpl.java which is generated class from jFlex.
Refer this link for complete guide.
You have to add following line in SUPPLEMENTARY.jflex-macro which is included by StandardTokenizerImpl.jflex file.
 MidLetterSupp = ( [\u002D]  )

And After making changes provide StandardTokenizerImpl.jflex file as input to jFlex engine and click on generate. The output of that will be StandardTokenizerImpl.java
And using that class file rebuild the index.

A: StandardAnalyzer will treat the hyphen as whitespace, I believe. So it turns your query "gsx-*" into "gsx*" and "v-*" into nothing because at also eliminates single-letter tokens. What you see as the field contents in the search result is the stored value of the field, which is completely independent of the terms that were indexed for that field.
So what you want is for "v-strom" as a whole to be an indexed term. StandardAnalyzer is not suited to this kind of text. Maybe have a go with the WhitespaceAnalyzer or SimpleAnalyzer. If that still doesn't cut it, you also have the option of throwing together your own analyzer, or just starting off those two mentined and composing them with further TokenFilters. A very good explanation is given in the Lucene Analysis package Javadoc.
BTW there's no need to enter all the variants in the index, like V-strom, V-Strom, etc. The idea is for the same analyzer to normalize all these variants to the same string both in the index and while parsing the query.

A: The ClassicAnalzer is recommended to index text containing product codes like 'GSX-R1000'. It will recognize this as a single term and did not split up its parts. But for example the text 'Europe/Berlin' will be split up by the ClassicAnalzer into the words 'Europe' and 'Berlin'. This means if you have a text indexed by the ClassicAnalyzer containing the phrase
Europe/Berlin GSX-R1000

you can search for "europe", "berlin" or "GSX-R1000".
But be careful which analyzer you use for the search. I think the best choice to search a Lucene index is the KeywordAnalyzer. With the KeywordAnalyzer you can also search for specific fields in a document and you can build complex queries like:
(processid:4711) (berlin)

This query will search documents with the phrase 'berlin' but also a field 'processid' containing the number 4711.
But if you search the index for the phrase "europe/berlin" you will get no result! This is because the KeywordAnalyzer did not change your search phrase, but the phrase 'Europe/Berlin' was split up into two separate words by the ClassicAnalyzer. This means you have to search for 'europe' and 'berlin' separately.
To solve this conflict you can translate a search term, entered by the user, in a search query that fits you needs using the following code:
QueryParser parser = new QueryParser("content", new ClassicAnalyzer());
Query result = parser.parse(searchTerm);
searchTerm = result.toString("content");

This code will translate the serach pharse
Europe/Berlin

into
europe berlin

which will result in the expected document set.
Note: This will also work for more complex situations. The search term
Europe/Berlin GSX-R1000

will be translated into:
(europe berlin) GSX-R1000

which will search correctly for all phrases in combination using the KeyWordAnalyzer.


text:
Q: Please help me identify this noise on my ADC I have a CS4270 codec hooked up to a Raspberry Pi more or less according to the "recommended layout" in the datasheet (P7), shown below. This device sinks power from three different places (VA = power for analog subcircuits, VD = power for DSP, VLC = power for control port (I2C and clocks). Currently VA is sourced by an LT1965 (in turn powered from an Adafruit Powerboost connected to a LiPo battery) while VLC and VD are sourced from the Raspberry Pi's 3.3V output.

I am able to record from the device as expected using SoX on or arecord on the Pi, however I am confronted with a troubling amount of noise on the signal. These images are representative of what I'm seeing:
Full spectrum, 0-96kHz

Bottom of the spectrum, about 0-1kHz

In the top spectrogram, I see spikes of broadband noise repeating at about 33.3Hz, though the exact period seems to vary from recording to recording (I just saw some at about 50Hz in another recording). In the bottom spectrogram, I see narrowband noise at 50-60Hz and some bad harmonics. I haven't even started work on the signal chain leading into the ADC yet because these artifacts are everywhere on the board — I've plugged the inputs into ground, VA/2, even the codec's own midpoint reference voltage (VQ) and I see the same kind of thing everywhere, albeit with varying levels of intensity.
Clearly, 60Hz harmonics screams noise from the power main, but the whole setup is disconnected entirely from the wall (powered by battery at the moment).
Here's a shot of my actual current layout. In this case the ADC inputs are tied to VA / 2 through a simple passive filter (lower board), which in an ideal world would produce a bunch of zeroes on the ADC. The LT1965 is powered through a filter with a few decades' worth of caps and a ferrite bead — not strictly necessary but it did seem to help with actual mains noise. These particulars aren't super relevant since varying the power source or the input still results in the same artifacts.

I would really, really appreciate some assistance in identifying potential culprits for this noise. Is this something characteristic of the topology? Or is this to be expected on a $1 Chinese breadboard with jumpers everywhere, and I should just order a PCB with the same layout for further testing? Obviously this is difficult to debug remotely — my hope is that someone will see this and say, "aha! I've seen this before!"
EDIT: highly unlikely to be relevant, but here's the driver (mostly a wrapper around the CS4270 driver currently) that I am using, along with a device tree overlay that is almost identical to the HifiBerry DAC+ Pro one in RPi Linux. Unlikely to be part of the problem, but may be of interest to Linux nerds.

A: Proto-boards are hardware platforms quite sensitive to noise. Note that it is build with a lot of metalic rails inside. In addition the aerial wirings just catch extra EMI from air. You could at least minimise the noise amplitude by grounding the surrounding non used rails of the proto-board, as well as shielding the wire with brings the signal to the board, along with spreading ceramic capacitors at power rails close to the AD.


text:
Q: Dropdown menu imported inside a div (with jquery .load) doesn't work, why? I'm using the .load() jquery function to import a document inside a div.
Inside the imported document there is a form with a <select> tag.
The menu bar appears, but if I click on it the dropdown menu doesn't appear .
If i use the <select> OUT of the div (out the containor), the dropdown menu starts well.
What shouldI do?

A: As you're loading content dynamically, the click function doesn't work as the dropdown wasn't there in the first place on DOM ready.
Try changing your
.click(function() {}

to
.on('click', function() {}

Should work.


text:
Q: How can I get comments to display under All posts Right now I have an application where I want to retrieve the comments from posts. I dont know what is the best way to go about this.
What i currently have only displays posts that has comments, but it doesnt show Multiple Comments only a single one.
<Grid item xl={8}>
    {this.props.posts.map((post, index) =>
      <PostBodyTemplate key={index} postId={post.id}  onSubmit={this.handleSubmit} onChange={e => this.handleInputChange(e,post.id,post.userId,post.userIdName)} title={post.title} postBody={post.postBody}
           giphyUrl = {post.giphyUrl} userWhoPosted={post.userIdName} commentBody={post.commentBody} userIdName={post.userIdName} />
       )}
       {displayGifPicker ? (<AddGif selectedGif = {this.getGifState} />) : (<Button size="small" onClick={this.displayGifPicker} ><button>Add Gif</button></Button>)}
 </Grid>

The data is coming from The API that basically combines both the Posts And Comments table joining them by PostId, right now it only displays one comment and is only currently displaying Post that have comments.
router.get('/', (req, res) =>{
 sequelize.query( "SELECT comments.id, comments.postId,
 comments.commentBody, comments.giphyurl,
 comments.postPicture,comments.userId, comments.userIdto,
 comments.userIdName, comments.userIdtoName, posts.postBody, posts.title,
 posts.giphyUrl, posts.postPicture, posts.userId, posts.userIdName,
 posts.userIdto, posts.userIdtoName FROM comments INNER JOIN posts ON
 comments.postId = posts.id;")
.then(([results, metadata]) => {
res.json(results)
 })
})

Is there a better way I should go about this? The ideal solution to my problem would Grab all posts, display all post, if the post has comments then display all those comments also. The query I have only returns post that have comments, and mapping through them only shows one comment it doesnt display all..
To Get all comments currently i am just using a simple findAll, but this doesent display comments because the comments are in the comments table. Which is why i joined the tables in the previous query.
If it helps this is the component the props are sent to.
     export default function PostBodyTemplate(props) {
      const { onChange, onSubmit} = props
         const classes = useStyles();
        //  render() {
             return (
                <Grid item xs={12} xl={8} lg={8} style={fr}>
                <Card className={classes.card}>
                <CardContent>
                <Paper className={classes.root}>
                <Typography variant="h5" component="h2" style={fr}>
                      {props.userWhoPosted} Gave A VH5 To Julio {props.postId}
                  </Typography>
                    <Typography variant="h5" component="h3">
                      {props.title}
                    </Typography>
                    <Typography component="p">
                      {props.postBody}
                    </Typography>

                </Paper>
                </CardContent>
                <CardActions>
                <IconButton aria-label="add to favorites">
                    <FavoriteIcon />

Add Gif

                  </IconButton>
                  <IconButton aria-label="share">
                    <EcoIcon />

Add Photo

                  </IconButton>
                  <form onSubmit={onSubmit}>

                    <TextField
                               onChange = {onChange}
                                name='commentBody'
                                id="standard-full-width"
                                label="Reply To Post"
                                style={{ margin: 8 }}
                                placeholder="Reply to Post"
                                fullWidth
                                margin="normal"
                                InputLabelProps={{
                                shrink: true,
                                }}
                        />
                      {/*
<button>Send VH5</button>
 */}
                      {/* <Button onSubmit={onSubmit} size="small">Submit</Button> */}
                      <button onSubmit={onSubmit}>Submit VH5</button>
                    {/* <button onSubmit={onSubmit}>Submit Reply</button> */}

                  </form>
                  {/* <CommentInput onChange={onChange}/> */}
                  {/* <Button size="small">Submit</Button> */}
                </CardActions>
                <Paper className={classes.root} value={props.postId}>
                    <Typography variant="h5" component="h3">
                    {props.commentBody}
                    </Typography>
                    <Typography component="p">
                      {props.userIdName} replied to the post.
                    </Typography>
                </Paper>
              </Card>
              </Grid>
             )
        //  }
     }

A: What you need is to change your inner join to a LEFT JOIN to get all the posts whether or not they have comments. More about joins


text:
Q: Google App Engine inter module communication authorization In the Google Docs it says

You can configure any manual or basic scaling module to accept requests from other modules in your app by restricting its handler to only allow administrator accounts, specifying login: admin for the appropriate handler in the module's configuration file. With this restriction in place, any URLFetch from any other module in the app will be automatically authenticated by App Engine, and any request that is not from the application will be rejected.

so i did that, but unfortunately it does not work. I am requesting a url from module A on module B which is protected by the login: admin property
I can fetch that url in the browser which shows me the login page and after i continue as admin i can fetch my route.
How is it supposed to work? As far as i understand it should add a header to the request which includes some kind of authorization token.
If i fetch that same url within a request on module A i get the same redirect. urllib2 follows the 302 status code by default and the result is the login page.
I am running the environment using the gcloud preview app run command. Module A is a default module and module B is a Managed VM Container, might this be the problem here?

A: I can confirm this is occurring, and I've reproduced the issue. The issue is being tracked over in the App Engine public issue tracker. Follow there for any updates.
For now, I think it's much better to be manually-inspecting the X-Appengine-Inbound-Appid header, as this is managed by the infrastructure and can't be spoofed.
You could also implement OAuth, but that adds overhead you may not want or need on a small app.


text:
Q: When is `new Error()` better than `Error()`? The ES5 language spec clearly states that Error(foo) does the same thing as new Error(foo).
But I notice that in the wild, the longer new Error(foo) form is much more common.
Is there some reason for this?
Is there any situation where using new Error(foo) is preferable to using Error(foo)?

A:
Is there some reason for this?

It's simply the habit of always calling constructors with new. Consistency rules!
It's a good practice to do even when they work without new, and recommended by several style guides and related tooling. Btw, since ES6 Error is subclassible, and its subclasses will require new.


text:
Q: Find out if Flex component (tree) ist scrollable? How can you find out if a Flex Component (in my case the tree) is scrollable? I tried it like this
if (_listOwner.height < _listOwner.measuredHeight) {
  // so stuff
}

from within the tree's item renderer but didn't succeed. Access to the tree's scrollbar is private so that I can't get the info that way.

A: Found a solution by extending the tree class:
public class ExtendedTree extends Tree
{
    public function ExtendedTree()
    {
        super();
    }

    public function get isVerticalScrollable():Boolean
    {
        if (super.verticalScrollBar == null || super.verticalScrollBar.visible == false)
            return false;
        return true;
    }
}

A: Use the maxVerticalScrollPosition and maxHorizontalScrollPosition properties.


text:
Q: How do I restart a Unity session from the terminal? The command for restarting Gnome2 is:
sudo /etc/init.d/gdm restart

What is the equivalent for Unity?

A: The command unity can be used to restart unity. It restarts the window manager, so your open programs will stay intact and you will not be logged out.
If you run the command from a terminal app, you should add & disown to detach it from the terminal. If you don't, then the unity program will become a child process of the terminal app such that when you close the terminal, unity will also close.
It might also be worthwhile to add &> /dev/null (before the disown bit) so that text and error output does not clutter your terminal.
So, the command is:
unity &> /dev/null & disown

If you can't open the terminal application due to the desktop being extremely unresponsive (or any other reason), you can open a purely text-based terminal by hitting alt-ctrl-F1 through F6.
There you will get a text terminal, you have to login first.
Then you can run the command above, then hit alt-ctrl-F7 or alt-ctrl-F8 to come back to the graphical desktop.
This tends to fix "hanging" problems.
As a side note: since Unity is a compiz plugin, you can restart unity by restarting compiz using the command:
compiz --replace

If you run it from the alt-ctrl-F1 terminal, you will need a --display parameter
compiz --display :0 --replace

You'll still need to add & disown

A: In Ubuntu 13.04 you can use the following:
sudo service lightdm restart

A: The Upstart way is
sudo service lightdm restart for newer versions using lightdm
or sudo service gdm restart for older versions using gdm.
Update:
Another option, which isn't using the terminal but using a key combination, can be found at How to set keyboard combination to kill the X server?

A: In a terminal, run nohup compiz --replace. The nohup command will make sure compiz isn't closed when you close the terminal.

A: The command to restart GDM is sudo stop gdm followed by sudo start gdm, and should be done from a tty.
If you are trying to restart unity itself just run unity (but remember you need to do this from the run dialog.

A: You don't need to open a tty. In most cases Alt-F2 still works. Just enter "unity". That's it. No & disown needed.

A: I like to change GNOME's font size attribute depending on the monitor.  I've been shutting down the programs directly so the window position is saved.  I put this in the script which probably does pretty much the same thing:
    nautilus -q && sleep 2 && bgcmd nautilus -n
    pkill unity-panel
    pkill unity-window
    sleep 1
    unity-window-decorator &> /dev/null & disown


text:
Q: Specifying a non-NavigationWindow as the main window in App.xaml The following XAML in app.xaml works:
<Application.MainWindow>
    <NavigationWindow Visibility="Visible" Source="MainWindow.xaml"></NavigationWindow>
</Application.MainWindow>

But changing this to
<Application.MainWindow>
    <Window Visibility="Visible" Source="MainWindow.xaml"></Window>
</Application.MainWindow>

Means that I can't specify the Source.  Can anyone tell me how to specify the source for a non-navigation window?

A: Source is Dependency Property on navigation window and not available on Window.
In case you want to make MainWindow.xaml as startup window for your application i.e. MainWindow of application, you can specify StartupUri on Application itself:
<Application StartupUri="MainWindow.xaml">

In case you need to set Application MainWindow, you have to provide instance of window like this:
<Application xmlns:local="clr-namespace:ActualNamespace">
    <Application.MainWindow>
        <local:MainWindow/>
    </Application.MainWindow>
</Application>

Replace ActualNamespace with namespace where MainWindow resides.


text:
Q: Dashboard grid - Chart.JS and CSS- issue widening two small horizontal bar graphs - noob question I'm learning JavaScript, CSS, and Chart.JS.  I've been given some code to reverse engineer and learn. My final task is to widen the two horizontal graph divs to the left, without overlapping with the large vertical bar graph.

Basically, I just want my two small graphs to expand to the left in
width.  Codepen is here:
https://codepen.io/tenebris_silentio/pen/VwaGdaP

        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>
        <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>

    <meta content="width=device-width, initial-scale=1.0" name="viewport">
            <link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css" rel="stylesheet" type="text/css">

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Portfolio Review Overview</title>

                                Horizontal Bar Graph 2

                                <canvas class="doughnut-chart" id="doughnut">
                                </canvas>

                                Horizontal Bar Graph 1

                                <canvas class="pie-chart" id="pie">
                                </canvas>

Bar Chart

                                <canvas class="bar-chart" id="bar">
                                </canvas>

A: Given the nature of the grid display, you can't really expand the cards to the left without breaking the layout. What was needed was a readjustment in the grid-template for .dashboard-container.
Here is the updated codepen.
Here is a gist with the same contents of the pen but in a single html file.
There where some issues with margins and paddings, misuse of the fr unit in grid template properties and inconsistency in media queries breakpoints.


text:
Q: Non-clustered index creation on SQL Azure takes up insane amount of storage space I thought that a non-clustered / logical index consisted only of pointers to the actual records.
I have a table with a clustered index on the primary key (id), a datetime, and a varchar (and a few other columns I'm not indexing).
I used the command:
CREATE INDEX Index_CreatedDesc_AccountAsc ON MyTable (Created desc, Account asc)

The table has 500 million records.  I'm watching on the Azure database metrics in real time as it creates the index (it's ran for about 1 hour 30 minutes so far).
It started at 111GB, and now the table has increased in size to 120GB.  Why is it taking up so much space if it only needs to create pointers to the physical records/data pages?

A: It is not just pointers. In reality, Azure SQL database and SQL Server are creating a balanced tree or b-tree (more exactly a B-Plus tree) as is explained on SQL Server Internals book. B-trees start small and perfectly formed and grow nicely to enormous sizes. If you don't defragment them regulary they may get fragmented and consume more space as explained here.


text:
Q: Finding theme files based on code pieces on Mac with Finder not working / accurate Problem
I'm experiencing regularly the problem that my Mac isn't finding files based on given code pieces.
For example, I was just searching for the code
woocommerce_account_navigation

which I know is in a file called class-woocommerce-template-account.php. However, my Mac doesnt present this file in the results, while it even shows other files in the same enclosing folder that contain this code.
This is really frustrating and I wonder how other developers overcome this search problem?
I know for certain public themes & plugins, you can search github, which is great, but this option isn't available for non-public files that you have on your computer only.
I would very much appreciate any guidance from more experienced developers and Mac users.
Many thanks
David


text:
Q: Units in ring of integers of $5^{th}$ cyclotomic field Let $K=\mathbb{Q}(\omega)$ with $\omega$ a primitive $5^{\text{th}}$ root of unity. I'm trying to prove that
$$ \mathcal{O}_K^\times=\left\{\pm\omega^{a}\left(\frac{1}2+\frac{\sqrt{5}}2\right)^b: a,b\in \mathbb{Z}\right\}.$$
I've proven that $\sqrt{5}\in K$ by finding the discriminant. Since $r+s-1=1$ we also have that by Dirichlet's unit theorem
$$ \mathcal{O}_K^\times\cong \mu_K\times \mathbb{Z}.$$
Since $r+s-1=1$ there will be a fundamental unit and if $\frac{1}2+\frac{\sqrt{5}}2$ is a fundamental unit then we will be done - but this is where I am stuck. I know how to find fundamental units in quadratic number fields but I don't see how I'd extend that method to here.
Any help would be really appreciated.

A: Consider $$f: O_K^\times\to \Bbb{Z}[\varphi]^\times, z\to |z|^2$$
where $\varphi= \frac{1+\sqrt5}{2}$.

*

*$\ker f = \{ a\in O_K^\times,\forall \sigma\in Hom_\Bbb{Q}(K,\Bbb{C}),|\sigma(a)|=1\} = \mu_{10}$

*$\text{Im }f\subset \Bbb{Z}[\varphi]^\times \cap \Bbb{R}_{> 0} = \varphi^\Bbb{Z}$

*$\varphi^{2\Bbb{Z}}\subset \text{Im } f$

*$\varphi\not \in \text{Im } f$ because $f(z)\equiv z^2\bmod (\zeta_5-1)$ while $\varphi \equiv \frac12 \bmod (\zeta_5-1)$ is not a square in $O_K/(\zeta_5-1)\cong \Bbb{F}_5$.

*Whence $\text{Im } f = \varphi^{2\Bbb{Z}}$ and $$O_K^\times = \ker f\times \varphi^\Bbb{Z}$$


text:
Q: $f_U(t)=f_{X,Z}(t,1)+f_{Y,Z}(t,0)$ if $U=X $ if $Z=1$ and $U=Y$ if $Z=0$ Suppose $Z$ is a bernouli variable with parameter $p$. $Z,X,Y$ are independent random variables. Now $U$ be a random variable such that
$$U(\omega)=\begin{cases}X(\omega) & \text{when }Z(\omega)=1\\ Y(\omega) & \text{when }Z(\omega)=0\end{cases}$$
From this can we say that
$f_U(t)=f_{X,Z}(t,1)+f_{Y,Z}(t,0)$

A: Assuming that $X$ and $Y$ have densities $f_X$ and $f_Y$ we can compute $f_U$ as follows:
$$P(U \leq t)=P(X\leq t, Z=1) +P(Y\leq t, Z=0)$$ $$=pP(X\leq t)+(1-p)P(Y\leq t).$$ Differentiating this we get $f_U(t)=pf_X(t)+(1-p)f_Y(t)$ almost everywhere (w.r.t. Lebesgue measure).


text:
Q: How do I get all the child tag names of an XML document using c#? I am trying to find an efficient way to parse xml data into an SQL table.
This is a small example of the XML I will get, in reality there will be around 20-25 tags inside the property tag and hundreds of entries.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<entry m:etag="W/"28"">
<id>114</id>
<title type="text">Title 1</title>
<updated>2012-07-09T15:02:08+01:00</updated>
<author>
  <name />
</author>
<m:properties>
  <d:ContentTypeID>456</d:ContentTypeID>
  <d:ApproverComments>Correction to Title</d:ApproverComments>
  <d:Name>bar.pdf</d:Name>
  <d:Title>Title</d:Title>
  <d:DocumentOwnerId m:type="Edm.Int32">20</d:DocumentOwnerId>
  <d:DocumentControllerId m:type="Edm.Int32" m:null="true"></d:DocumentControllerId>
</m:properties>
</entry>
<entry m:etag="W/"28"">
<id>115</id>
<title type="text">Title 2</title>
<updated>2012-07-09T15:05:35+01:00</updated>
<author>
  <name />
</author>
<m:properties>
  <d:ContentTypeID>456</d:ContentTypeID>
  <d:ApproverComments>Correction of Title2</d:ApproverComments>
  <d:Name>foo.pdf</d:Name>
  <d:Title>Title 2</d:Title>
  <d:DocumentOwnerId m:type="Edm.Int32">20</d:DocumentOwnerId>
</m:properties>
</entry>

I will need to look at each 'entry' and pull out all the tag names inside the m: properties tag and set those as the columns for the SQL table.
I'm looking for a more efficient way to do this, rather than having to iterate through all entries' property tags then putting together a list of tag names that I then need to cross reference to make sure I get them all.
I have been trying to find a function along the lines of;
String TagNames = XMLDoc.getChildNode('properties').getChildNodeNames()

TagNames would equal "ContentTypeID, ApproverComments, Name, Title, DocumentOwnerID, DocumentControllerID"
Any help would be greatly appreciated.

A: Making the assumption you already have an XDocument, we'll name it doc, one approach might be this:
doc.GetElements("entry")
   .Select(e => e.GetElement("m:properties")
                 .GetElements()
                 .Select(ce => ce.Name.LocalName)
                 .ToList())
   .ToList();

That should give you a List<List<string>> for each entry.
You could even qualify the inner list with the id of the entry:
doc.GetElements("entry")
   .Select(e =>
   {
       var id = e.GetElement("id").Value;

       e.GetElement("m:properties")
        .GetElements()
        .Select(ce => string.Format("{0}|{1}", id, ce.Name.LocalName))
        .ToList()
    })
   .ToList();


text:
Q: Count all Users I have a simple question:
from ": 1337/users/count" I get the answer "404" although I have activated the authorization for "count" in "Roles & Premissions". Can someone give me a hint?
Please see screenshots!
Thanks in advance!


text:
Q: What defines an opaque type in C, and when are they necessary and/or useful? I've seen the concept of 'opaque types' thrown around a bit but I really haven't found a succinct answer as to what defines an opaque type in C and more importantly what problems they allow us to solve with their existence.  Thanks

A: It is the most generally used for library purpose. The main principe behind Opaque type in c is to use data though its pointer in order to hide data handling implementation. Since the implementation is hidden, you can modify the library without recompiling any program which depend on it (if the interface is respected)
eg:
version 1:
// header file
struct s;

int s_init(struct s **x);
int s_f(struct s *x);
int s_g(struct s *x);

// source file
struct s { int x; }

int s_init(struct s **x) { *x = malloc(...); }
int s_f(..) { ... }
int s_g(..) { ... }

version 2
// header file
struct s;

int s_init(struct s **x);
int s_f(struct s *x);
int s_g(struct s *x);

// source file
struct s { int y; int x; }

int s_init(struct s **x) { *x = malloc(...); }
int s_f(..) { ... }
int s_g(..) { ... }

From your program side, nothing changed! and as said previously, no need to recompile every single program which rely on it.

A: In my understanding, opaque types are those which allow you to hold a handle (i.e., a pointer) to an structure, but not modify or view its contents directly (if you are allowed to at all, you do so through helper functions which understand the internal structure).
Opaque types are, in part, a way to make C more object-oriented. They allow encapsulation, so that the internal details of a type can change--or be implemented differently in different platforms/situations--without the code that uses it having to change.

A: An opaque type is a type which is exposed in APIs via a pointer but never concretely defined.


text:
Q: how to display spreadsheet like table in android with horizontal and vertical scrollbars I want to display excel sheet on android screen with horizontal and vertical scrollbars..plz help me.I have searched so much on net.thanks

A: There are base classes for horizontal scroll views and vertical scrollviews, but not one where one can scroll in two dimensions at the same time.
I have found this blog in which Matt Clark have created a new TwoDScrollView class.
http://blog.gorges.us/2010/06/android-two-dimensional-scrollview/

A: Create a ScrollView and then inside of this place a HorizontalScrollView.  Now this will behave as on object that has both Vertical and Horizontal Scrolling properties.

A: I know GridView is not popular for your purpose. But it still gives us an easier way to build spreadsheet like UI.
As you said, GridView itself is not horizontally scrollable and will be extremely slow if number of controls in the gridview exceeds says 500.
But I think what you want to try is to fix size of the gridview that will display given rectangle area of data and to override its touch event to emulate scrolling actions. Thanks to base adapter and other techniques for gridview, your work will be minimal.
Good example of such a method is Dennis's work

A: PsuedoCode
Have a TableLayout inside a scrollview!!!
How to populate it->
For each row in spreadsheet
     TableRow tr = new TableRow()
     For each cell in row
       //Create a textview.//
     TextView trCell = new TextView()
     //Set TextView text, get text from spreadsheet current cell.//
     trCell.setText(cell.textvalue)
     tr.addview(trCell)
    }
  tableLayout.addView(tr) //Add tablerow to the tablelayout.//
}
Since table is in a scrollview, if table rows extend length of scroll view, scrollbars will appear.
If you need more info, I'll post my exact code. And if you still cant get it, ill upload my whole class to GitHub.


text:
Q: Laravel: js/app.js - Source-Map-Error :request failed with status 404 I'm fairly new to laravel and I get always this error message in the browser console

Source-Map-Error: request failed with status 404
  Ressource-Adress: http://[myurl]/js/app.js
  Source-Map-Adress: popper.js.map

And I have no idea where the problem is. When I try to access the app.js file through the URL it works.
I have a second project with the exact same setup where I don't get any errors. I can't figure out what I'm missing.

A: looks like you are missing a source map. what is your JS setup atm? i.e. what dependencies are you pulling in? Can we see source ?
Something like this might help
app.import('node_modules/popper.js/dist/umd/popper.js.map', { destDir: 'assets' });


text:
Q: How to remove the text from the table at the end of displaying table data I'm not really sure how to quote this question, but I'm making a clone of Reddit in Ruby on Rails.
On the index page I am displaying all of the posts I have in the table "Posts". But when I display them all, at the end of the last post a text shows up which is wrapped in square brackets and contains all of the information from the table. I just want to know how to remove this text.
Picture of problem
This is the code used to display the post:
 <%= @posts.each do |post| %>

    <%= link_to "s\\" + post.sub.name, sub_path(post.sub) %> Posted by <%= link_to "u\\" + post.user.username, profile_path(post.user.username) %> <%= time_ago_in_words post.created_at %> ago

<%= link_to post.title, sub_post_path(post.sub, post) %>

<%= truncate post.body, length: 200 %>

<% end %>

My posts controller:
class PostsController < ApplicationController
  before_action :authenticate_user!, except: [ :index, :show ]
  before_action :set_post, only: [:show]
  before_action :auth_subscriber, only: [:new]

  def index
    @posts = Post.all
  end

  def show
  end

  def new
    @sub = Sub.find(params[:sub_id])
    @post = Post.new
  end

  def create
    @post = Post.new post_values
    @post.user_id = current_user.id
    @post.sub_id = params[:sub_id]

    if @post.save
      redirect_to subs_path(@post.sub_id)
    else
      @sub = Sub.find(params[:sub_id])
      render :new
    end
  end

  private

  def set_post
    @post = Post.find(params[:id])
  end

  def auth_subscriber
    unless Subscription.where(sub_id: params[:sub_id], user_id: current_user.id).any?
      redirect_to root_path, flash: { danger: "You are not authorized to view this page" }
    end
  end

  def post_values
    params.require(:post).permit(:title, :body)
  end
end

A: <% @posts.each do |post| %>

    <%= link_to "s\\" + post.sub.name, sub_path(post.sub) %> Posted by <%= link_to "u\\" + post.user.username, profile_path(post.user.username) %> <%= time_ago_in_words post.created_at %> ago

<%= link_to post.title, sub_post_path(post.sub, post) %>

<%= truncate post.body, length: 200 %>

<% end %>

In ERB <%= is used to output the result of an expression to the buffer. #each in Ruby returns self so what you're seeing on the page is the result of implicitly calling #to_s on an array.
#each is always used for its side effects and not its return value. In the case of an ERB template each iteration writes to the buffer.
This can be somewhat hard to grasp but remeber that any plaintext in a template is written directly to the buffer - using each just does it n number of times.

A: Change <%= @posts.each do |post| %> for <% @posts.each do |post| %>, note the missing '=' in the second snippet.
When you include the '=' the output of .each is printed in the HTML, in this case the array of posts.


text:
Q: Insert data to table from another table containing null values and replace null values with the original table 1 values
I want to match first column of both table and insert table 2 values to table 1 . But if Table 2 values are null leave table 1 vlaues as it is .I am using Hive to dothis .Please help.

A: You need to use coalesce to get non null value to populate b column and case statement to make decision to populate c column.
Example:
hive> select t1.a,
      coalesce(t2.y,t1.b)b,
      case when t2.y is null then t1.c
      else t2.z
      end as c
     from table1 t1 left join table2 t2 on t1.a=t2.x;

+----+-----+----+--+
| a  |  b  | c  |
+----+-----+----+--+
| a  | xx  | 5  |
| b  | bb  | 2  |
| c  | zz  | 7  |
| d  | dd  | 4  |
+----+-----+----+--+


text:
Q: Ruby sometimes prints unicode-escaped chars instead of the chars themselves. Why? I use ruby 2.2.3p173, and Sublime 3. All my string already on encode('utf-8'). In Linux I have, what I expect. Try make output:
a = [ "Привет" ]
puts "puts=#{a}"
p "p=#{a}"
print "print=#{a}\n"

puts a[ 0 ]
p a[ 0 ]
print a[ 0 ] + "\n"
p a[ 0 ].encoding
p __ENCODING__

Output is:
puts=["\u041F\u0440\u0438\u0432\u0435\u0442"]
"p=[\"\\u041F\\u0440\\u0438\\u0432\\u0435\\u0442\"]"
print=["\u041F\u0440\u0438\u0432\u0435\u0442"]
Привет
"\u041F\u0440\u0438\u0432\u0435\u0442"
Привет
#<Encoding:UTF-8>
#<Encoding:UTF-8>

I expect:
puts=["Привет"]
"p=[\"Привет\"]"
print=["Привет"]
Привет
"Привет"
Привет

How I can print Array with several "utf-8" string in one line?

A: This is particularly observed on Windows.  On other *nix systems, it may work alright - For instance, on https://repl.it/ you see right output, as it is most likely hosted on a *nix system.
As per documentation, Array#to_s is

Alias for: inspect

Array#inspect invokes inspect on each of the array member, in this case, array members are all strings, thus String#inspect will be invoked.
String#inspect uses Encoding#default_external as specified in documentation for inspection results.

The default external encoding is used by default for strings created
  from the following locations:

*

*CSV

*File data read from disk

*SDBM

*StringIO

*Zlib::GzipReader

*Zlib::GzipWriter

*String#inspect

*Regexp#inspect

On Windows, default external encoding is not UTF-8, and hence, we see the escaped sequences in output of String#inspect.
p Encoding::default_external
#=> #<Encoding:IBM437>

We change the default external encoding to UTF-8, output will be proper:
Encoding::default_external = Encoding::UTF_8

a = [ "Привет" ]
puts "puts=#{a}"
#=> puts=["Привет"]

p "p=#{a}"
#=> "p=[\"Привет\"]"

A: Just try with irb console Or rails console .
It should be work.

Note: Kindly check also difference between p and puts
Hope this answer help you !!!


text:
Q: How to use CHtml's link function without linking to 'index'? I'm using the CHtml::link() function, and I have a problem with the index action.
The code in view:
echo CHtml::link('Watch it', array('video/index', 'id' => $id));

The urlManager part in config:
'urlManager' => array(
        'urlFormat' => 'path',
        'rules' => array(
            '<id>/<action>' => 'video/<action>',
            '<id>' => 'video/index'
        )
    )

What I want it to do is to create a link to:
http://localhost/123

Instead, it creates a link to:
http://localhost/123/index

How can I remove the '/index' part?
Creating a function that will handle this (replace '/index' with nothing) will be the best solution for this?

A: You can use Yii::app()->createUrl in chtml link function
echo CHtml::link('Watch it', Yii::app()->createUrl('video/index', 'id' => $id));

UPD Try this
'urlManager' => array(
        'urlFormat' => 'path',
        'rules' => array(
            '<id>' => 'video/index'
            '<id>/<action>' => 'video/<action>',

        )
    )


text:
Q: saving image file in mongodb using node gm (graphic magic) I am totally new in node and mongodb concepts. I am trying to save the image, file (meta data) saved successfully but its chunks are not saving.
I also read gm documentation but did not helped alot plus i am not facing any error. https://github.com/aheckmann/gm
here is my code
var writeStream = gfs.createWriteStream({
    filename: file.name,
    mode: 'w',
    content_type: file.type,
    metadata: {
        uid: uid,
        createdAt: Date.today().setTimeToNow()
    }
});
  gm(file.data).resize(200).filter('Catrom').quality(80).stream().pipe(writeStream);

and here is my file object which i am passing
file : { data: "blob:http://localhost:3000/2664926c-f5e3-4ed2-8c3e-0473fd759944", name: "photo.jpg", type: "image/jpeg"}

Help much appreciated :)

A: Finally I found the issue, we have to write the blob url after piping. Here is the change
gm(file.data).resize(200).filter('Catrom').quality(80).stream().pipe(writeStream).write(file.data);

Thanks :)


text:
Q: Converting an AnsiString to a Unicode String I'm converting a D2006 program to D2010.  I have a value stored in a single byte per character string in my database and I need to load it into a control that has a LoadFromStream, so my plan was to write the string to a stream and use that with LoadFromStream.  But it did not work. In studying the problem, I see an issue that tells me that I don't really understand how conversion from AnsiString to Unicode string works.  Here is a piece of standalone code that illustrates the issue I am confused by:;
procedure TForm1.Button1Click(Sender: TObject); {$O-}
var
  sBuffer: String;
  oStringStream: TStringStream;
  sAnsiString: AnsiString;
  sUnicodeString: String;
  iSize1,
  iSize2: Word;
begin
  sAnsiString := '12345';
  oStringStream := TStringStream.Create(sBuffer);
  sUnicodeString := sAnsiString;
  iSize1 := StringElementSize(sAnsiString);
  iSize2 := StringElementSize(sUnicodeString);
  oStringStream.WriteString(sUnicodeString);
end;

If you break on the last line, and inspect the Bytes property of oStringStream, you will see that it looks like this:
Bytes (49 {$31}, 50 {$32}, 51 {$33}, 52 {$34}, 53 {$35}

I was expecting that it might look something like
(49 {$31}, 00 {$00}, 50 {$32}, 00 {$00}, 51 {$33}, 00 {$00},
 52 {$34}, 00 {$00}, 53 {$35}, 00 {$00} ...

Apparently my expectations are in error.  But then, how to convert an AnsiString to unicode?
I'm not getting the right results out of the LoadFromStream because it is reading from the stream two bytes at a time, but the data it is receiving is not arranged that way.  What is it that I should do to give the LoadFromStream a well formed stream of data based on a unicode string?
Thank you for your help.

A: What is the type of the oStringStream.WriteString's parameter? If it is AnsiString, you have an implicit conversion from Unicode to Ansi and that explains your example.

Updated: Now the real question is how TStringStream stores data internally.
In the following code sample (Delphi 2009)
procedure TForm1.Button1Click(Sender: TObject);
var
  S: string;
  SS: TStringStream;

begin
  S:= 'asdfg';
  SS:= TStringStream.Create(S);  // 1 byte per char
  SS.WriteString('321');
  Label1.Caption:= SS.DataString;
  SS.Free;
end;

TStringStream uses internally the default system ANSI encoding (1 byte per char).
The constructor and WriteString procedures convert a string argument from unicode to ANSI.
To override this behaviour you must declare the encoding explicitely in the constructor:
procedure TForm1.Button1Click(Sender: TObject);
var
  S: string;
  SS: TStringStream;

begin
  S:= 'asdfg';
  SS:= TStringStream.Create(S, TEncoding.Unicode);  // 2 bytes per char
  SS.WriteString('321');
  Label1.Caption:= SS.DataString;
  SS.Free;
end;

A: In Delphi last versions you could use TEncoding:
TEncoding.UTF8.GetString(TEncoding.ANSI.GetBytes(MyString))

A: I think you want to use:
LoadFromStream(stream, TEncoding.ASCII);

If your single byte text is not ASCII but is based on a code page, then this might work:
LoadFromStream(stream, TEncoding.GetEncoding(1252));

where the "1252" is the code page that your single byte text is based on.

A: The stream format largely depends on the TStringStream.Encoding. In your exemple, the used codepage should be the same as sBuffer (See implentation from TStringStream.Create).
Since oStringStream.WriteString(sUnicodeStream); seems to save as single bytes, I'd assume sBuffer is an Ansistring or a RawByteString.
Now... why do the reading fails...  You have yet to supply us an example of how you do read back in that stream.


text:
Q: tornado asynchronous queue not waiting I modified the example queue with producer & consumer from this Tornado documentation, but it doesn't seem like the timeout parameter passed to get() is working at all, as the consumer doesn't wait 10 seconds before throwing the exception.  Ideally, the producer and consumer would run at the same time.  Also, I don't know whether to pass in the timeout parameter as seconds or milliseconds:
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.queues import Queue

q = Queue()

@gen.coroutine
def consumer():
    try:
        while True:
            item = yield q.get(timeout=10000)
            try:
                print('Doing work on %s' % item)
            finally:
                q.task_done()
    except gen.TimeoutError:
        print('timeout')
        return

@gen.coroutine
def producer():
    for item in range(5):
        yield q.put(item)
        print('Put %s' % item)
        yield gen.sleep(2)

@gen.coroutine
def main():
    # Start consumer without waiting (since it never finishes).
    IOLoop.current().spawn_callback(consumer)
    yield producer()     # Wait for producer to put all tasks.
    yield q.join()       # Wait for consumer to finish all tasks.
    print('Done')

IOLoop.current().run_sync(main)

and here is its execution:
Put 0
Doing work on 0
timeout
Put 1
Put 2
Put 3
Put 4

A: The timeout
As you can read in Tornado' Queue.get docs:

Returns a Future which resolves once an item is available or raises tornado.gen.TimeoutError after a timeout.

But it could be quite misleading, since timeout is actually a deadline. So it must be specified either with datetime.timedelta object:
import datetime
yield q.get(timeout=datetime.timedelta(seconds=1))

or absolute time:
timeout = 1.5  # in seconds, floats acceptable
deadline = IOLoop.current().time() + timeout
# in most cases IOLoop time is just time.time()
# I've used separate variables only for the notion

yield q.get(timeout=deadline)

In Toro, that was merged into Tornado, this argument was called deadline.
In your code you specified timeout 10000, that means deadline to Thu, 01 Jan 1970 02:46:40 GMT.
Consumer loop
Since you have try/except block on the whole function, including while loop, when TimeoutError occurs your consumer stop working. Move exception handling into while loop.
Working example:
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.queues import Queue

q = Queue()

@gen.coroutine
def consumer():
    i = 0
    while True:
        i += 1
        print('get cycle %s' % i)
        try:
            item = yield q.get(IOLoop.instance().time() + 3)
            try:
                print('Doing work on %s' % item)
            finally:
                q.task_done()
        except gen.TimeoutError:
            print('timeout')

@gen.coroutine
def producer():
    for item in range(5):
        yield q.put(item)
        print('Put %s' % item)
        yield gen.sleep(2)

@gen.coroutine
def main():
    # Start consumer without waiting (since it never finishes).
    IOLoop.current().spawn_callback(consumer)
    yield producer()     # Wait for producer to put all tasks.
    yield q.join()       # Wait for consumer to finish all tasks.
    print('Done')


text:
Q: State doesn't update immediately in React I know I have to use useEffect but I couldn't figure out a way to make this code to work. I want the state courses to be updated immediately every single time I'm adding a new course. The data variable in the getCourses function is updated, but the update of the state doesn't happen immediately.
function CourseList() {
const [courses, setCourses] = useState([]);
const [idProf, setIdProf] = useState();

this function gets the list of courses from the database and store it in courses
const getCourses = async () =>{
    const response = await fetch(`${SERVER}/api/courses`);
    const data = await response.json();
    setCourses(data);
    // -> here setCourses doesnt update the state, but data has the updated array of courses
}

this function adds a course and then adds the professor stored in idProf to this course
const addCourse = async(course) => {

    //...fetch with post method...//

    getCourses(); // here i call the method but when I'm trying to add the professor to the course on the next line, the state isn't updated yet
    addStudentCourse(idProf, course.cod);
}

I tried to use useEffect but it s updating the state only one time
useEffect(()=>{
    getCourses();
},[]);

the courses are not updated when this function is running
const addStudentCourse = async(idStudent,codCourse)=>{
    let id = -1;
    //searching for the id in courses
    for(let c of courses){
        if(c.cod == codCourse){
            id = c.id;
        }
    }
    console.log(id)// id is still -1, it cant find the course because the state wasnt updated yet
    if(id != -1){
        //..adding to the database..//
    }
}
return (

)

}

A: Your getCourses funciton is async, but you are not awaiting it. Try await getCourses().


text:
Q: Gradient versus Tangent I am in calculus 3 and I have a question on gradient versus tangent. I know that this has been answered several times before:
Difference between a Gradient and Tangent
But I still have much trouble understanding them.
Assume $z = x^2 + y^2$ (a sphere)
In the topic of directional derivatives and gradients, gradient is the steepest slope (or, more formally, the direction to move so that z increases most rapidly). AT THE SAME TIME, it is a normal to the level curve (to my understanding, it means when z is fixed at a particular value, a vector that is perpendicular to the tangent of a curve at a particular point. The gradient points to the concave side of the level curve).
Combining the two ideas above, I assume it is correct that a normal to the level curve is the same as the direction in which z will increase most rapidly (although I am unsure why it is true).
Somehow, then I thought that gradient points to the direction where a tangent line to the 3D object is, because gradient points to the direction of the steepest slope.
And then in the following topic of tangent planes, now it tells me that gradient is actually a normal line instead of a tangent line to a 3D object? What a surprise!
In the case of 2D, gradient is the slope of a line. therefore, I naturally think that in the case of 3D, gradient is also the slope (or, the vector that points to the steepest slope for z). It is not the case? What is wrong with my thinking?

A: It sounds like you still think of functions like $z$ here as though they are "plotted" along additional axes.  In my opinion, this is great for visualization but can be confusing: such a viewpoint adds structure to what you're picturing, structure that isn't actually there.
Instead, let $f(x,y)$ merely associate a number with any particular $(x,y)$ point on the 2d plane.  This is what is meant by a "scalar field"--a scalar value is assigned to every point in a region (here, the entire 2d plane).  In mathematics, this is sometimes simply called a function.
When you use this intrinsic viewpoint, the level curves of the function $f$ are literally that: curves on the 2d plane. Each curve has well-defined tangent and normal vectors.  The normal vector, called the gradient, does indeed point toward the direction of greatest increase.  It must: the tangent sure doesn't.  The tangent points along the level curve, which is not increasing or decreasing at all.
It seems to me you're getting confused precisely because you're still imagining the 2d function plotted with its values on a fictitious third axis.  When we're talking about tangent planes, we're moving to the case of functions on 3d space: a function $g(x,y,z)$.  The level curves for this function in 3d space are no longer curves: they are surfaces, and these surfaces have tangent planes.  The gradient still points perpendicular to these tangent planes.  And here, the idea of plotting this function $g$ with an additional axis breaks down because you can't imagine (easily) a 4d space.


text:
Q: i am not able to create a collection in ravendb, if i do not have any document in it I have created a document in ravendb. Using session.advanced.getmetadata(see in code) , i gave a name to Raven-Entity-Name in metadata, after that i deleted that document in same function.Then i saw collection is also removed.If i delete the document manually from raven studio then the collection remains in the database.How a collection persist even if there is no document from code part? thanks in advance !!
My c# code is :
public CreateCollectionResult CreateCollection(string databaseName, string collectionName)
    {
        CreateCollectionResult createCollectionResult = new CreateCollectionResult();

        Collection collection1234 = new Collection();
        try
        {
            using (var session = documentStore.OpenSession(databaseName))
            {
                Guid guid = new Guid("12345678-1111-1111-2222-000000000000");
                session.Store(collection1234, guid, "april-Days/10");
                session.Advanced.GetMetadataFor<Collection>(collection1234)[Constants.RavenEntityName] = collectionName;
                //session.Delete<Collection>(collection1234);
                session.SaveChanges();
                createCollectionResult.IsOperationSuccessfull = true;
            }
        }
        //exception if database not found
        catch (InvalidOperationException ex)
        {
            createCollectionResult.IsOperationSuccessfull = false;
            createCollectionResult.Error = ex;
        }
        return createCollectionResult;
    }

A: In RavenDB, collections are virtual, they are only there as long as you have at least one doc in that document.


text:
Q: Finding a pixel location in a field of view So I have a camera with a defined field of view a point of a place I would like to label in the image. I have both the lat and lon of the points and I know the angle between them however my equation for finding the pixel location is off. Attached is an image to help my explanation:

I can solve for each vector of the camera to the center of view and the point and the full angle of the field of view and the angle between the center of view and point.
Here is what Im currently using: [angle of the field of view(green angle)/ the angle between the vectors (the blue angle)] * 1024 (screen width)
With numbers: (14.182353/65) * 1024 = 223.426620 and on the image the pixel value should be 328...
Another way I tried it was using a bearing equation: [[the bearing of the point to the camera- the bearing of the left side of the field of view ]/field of view] * 1024
With numbers: ((97.014993-83.500000)/65) * 1024 = 212.913132 and the answer should be 328...
Can anyone think of a more accurate solution?

A: Try 512(1-tan(blue)/tan(green/2)), where blue is positive to the left.
If blue is to the right, you can treat it as a negative number, to get 512(1+tan(blue)/tan(green/2)).
Explanation:
Let C be the camera, d be the dot labeled 328, E be the center of the field of view, and L be the left end point of the field of view, so that you want to find dL.  Then (for blue going left):
dL+dE = EL = 512
tan(green/2)=EL/CE
tan(blue)=dE/CE

Then tan(blue)/tan(green/2) = dE/EL = (512-dL)/512, and you can solve for dL.
Going right would be similar (or you can work with negative distances, and everything works out fine).


text:
Q: How is electromagnetic interference possible when measuring voltage difference? This question is primarily concerned with audio but it's probably applicable to other areas as well.
As far as I understand, EMI is caused by electromagnetic waves adding power to wires as they transmit a signal. Let's say you are transmitting an audio signal and the reference voltage wire is at zero watts and the signal wire is at one watt.
Now imagine you have the world's worst EMI and it causes an extra watt to be added to the signal wire and the reference voltage wire. The difference between the wires is still two so the signal hasn't changed. What gives? Why does EMI cause nasty noises at the other end when it would presumably be changing both wires' power equally?

A:
Now imagine you have the world's worst EMI and it causes an extra watt to be added to the signal wire and the reference voltage wire. The difference between the wires is still two so the signal hasn't changed.

This is why differential wiring is often chosen. It does help to reject radiated interference.

What gives? Why does EMI cause nasty noises at the other end when it would presumably be changing both wires' power equally?

It won't change both wires' power (or voltage or current) exactly equally.
If one wire is slightly further from the source than the other (even by millimeters) then it will see a slightly lower E field from that source. At high frequencies, the signal reaching the further wire will be significantly out of phase with the one reaching the closer wire.
Furthermore, any AC magnetic field in the space between the two wires will induce an EMF in one direction on one wire, and in the opposite direction on the other, exactly a differential current signal. To combat this we can twist the wires so that the EMFs induced in one section of the wire pair oppose those produced in another section. But the twist is never perfectly uniform, and the field is never exactly uniform over the length of the wire pair.
Finally, your differential receiver can not perfectly reject common mode signals, so in your example, where a extremely large common mode interference signal is injected on the wire, imperfections in the receiver will cause this to confound your attempts at a differential mode measurement.

A: You are on the track of a valid idea, which is the basis of why differential signaling is often used - for example in the balanced signals on XLR connectors in professional audio which do things like help keep interference out of the microphone signals in a live show.
But common single ended systems do not evaluate a signal in comparison to its return, but rather in comparison to a local ground, which would not contain the same interference.
And even in a differential setup, the idea only works to the extent that interference is coupled into both the non-inverted and inverted sides of the differential pair equally and to the degree that the differential receiver successfully rejects common mode interference.  For example, if the induced voltage exceeds the input range of the differential receiver, it may cause problems regardless of it being equal on both sides of the pair.
Additionally, radio frequency noise may bypass the intended behavior of the differential amplifier, or may find paths of coupling in to the receiving circuit which bypass the differential amplifier itself.  So typically gear is also designed with elements which try to reject this higher frequency energy.

A: Suppose you have a ower wire 1 meter away from, and running parallel to, a twin-lead TV cable.
Assume the wire has 100 amps peak current surges, as the diodes rectify the power; assume the diodes turn on in 10 microSeconds, that speed of turnon defined by the inductance of the power system and the slewrate of the power voltage, and the q/kt of the silicon rectifier. This produces 10,000,000 amps per second dI/dT.
Now back to the twin-lead. Assume the twin-lead wires are 1cm apart, and the twin-lead runs parallel to the power wiring for 10 meters.
Can we predict the induced interferer? Yes. Use a formula for magnetically-induced voltage into a rectangular loop of wire, from an interfering wire which is in the same plane as the loop and (for easy math) parallel to one axis of the rectangular loop.
Vinduce = [ MU0 * MUr * Area / (2 * pi * Distance) ] *dI/dT
For air and copper (non-magnetic materials), this simplifies to
Vinduce = [2e-7 * Area / Distance ] * dI/dT
We ignore a small logarithm coefficient, so the causality becomes obvious
Now insert values
Vinduce = 2e-7 * (10 meters * 1cm )/1meter * 1e+7 amps/second
Vinduce = 2e-7 * (10 * 0.01 ) * 1e+7 =  2e-7 * 0.1 * 1e+7 = 0.2 volts
Can your system tolerate 0.2 volts on top of your sensor signal?

A: It is the pesky slow speed of light that causes these kinds of problems. It causes the physical lengths and shapes of the conductors to form antennas allowing radio frequency (RF) energy to be absorbed into and radiated out of the circuit. In the case of RF energy absorption, the components intended to protect against electrostatic discharge rectifies the RF energy forming an AM receiver. This effect starts to be an issue at frequencies above 100 KHz. As a first order approximation use 15 nH/inch for the inductance of a wire as long as the physical length of the wire is less than a twenth of a wavelength. The wavelength is the speed of light divided by the frequency.


text:
Q: Does this MSDN article violate MVVM? This may be old news but back in March 2009, this article, "Model-View-ViewModel In Silverlight 2 Apps," has a code sample that includes DataServiceEntityBase:
// COPIED FROM SILVERLIGHTCONTRIB Project for simplicity

/// <summary>
/// Base class for DataService Data Contract classes to implement
/// base functionality that is needed like INotifyPropertyChanged.
/// Add the base class in the partial class to add the implementation.
/// </summary>
public abstract class DataServiceEntityBase : INotifyPropertyChanged
{
/// <summary>
/// The handler for the registrants of the interface's event
/// </summary>
PropertyChangedEventHandler _propertyChangedHandler;

/// <summary>
/// Allow inheritors to fire the event more simply.
/// </summary>
/// <param name="propertyName"></param>
protected void FirePropertyChanged(string propertyName)
{
  if (_propertyChangedHandler != null)
  {
    _propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
  }
}

#region INotifyPropertyChanged Members
/// <summary>
/// The interface used to notify changes on the entity.
/// </summary>
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
  add
  {
    _propertyChangedHandler += value;
  }
  remove
  {
    _propertyChangedHandler -= value;
  }
}
#endregion

What this class implies is that the developer intends to bind visuals directly to data (yes, a ViewModel is used but it defines an ObservableCollection of data objects). Is this design diverging too far from the guidance of MVVM? Now I can see some of the reasons Why would we go this way: what we can do with DataServiceEntityBase is this sort of thing (which is intimate with the Entity Framework):
// Partial Method to support the INotifyPropertyChanged interface
public partial class Game : DataServiceEntityBase
{
    #region Partial Method INotifyPropertyChanged Implementation
    // Override the Changed partial methods to implement the
    // INotifyPropertyChanged interface

    // This helps with the Model implementation to be a mostly
    // DataBound implementation

    partial void OnDeveloperChanged() { base.FirePropertyChanged("Developer"); }
    partial void OnGenreChanged() { base.FirePropertyChanged("Genre"); }
    partial void OnListPriceChanged() { base.FirePropertyChanged("ListPrice"); }
    partial void OnListPriceCurrencyChanged() { base.FirePropertyChanged("ListPriceCurrency"); }
    partial void OnPlayerInfoChanged() { base.FirePropertyChanged("PlayerInfo"); }
    partial void OnProductDescriptionChanged() { base.FirePropertyChanged("ProductDescription"); }
    partial void OnProductIDChanged() { base.FirePropertyChanged("ProductID"); }
    partial void OnProductImageUrlChanged() { base.FirePropertyChanged("ProductImageUrl"); }
    partial void OnProductNameChanged() { base.FirePropertyChanged("ProductName"); }
    partial void OnProductTypeIDChanged() { base.FirePropertyChanged("ProductTypeID"); }
    partial void OnPublisherChanged() { base.FirePropertyChanged("Publisher"); }
    partial void OnRatingChanged() { base.FirePropertyChanged("Rating"); }
    partial void OnRatingUrlChanged() { base.FirePropertyChanged("RatingUrl"); }
    partial void OnReleaseDateChanged() { base.FirePropertyChanged("ReleaseDate"); }
    partial void OnSystemNameChanged() { base.FirePropertyChanged("SystemName"); }
    #endregion
}

Of course MSDN code can seen as "toy code" for educational purposes but is anyone doing anything like this in the real world of Silverlight development?

A: In order to make a View entirely independent of the Model you would need to reproduce types that in many cases are identical to the Model types in your ViewModel.
Example
A Model contains a Person type that have FirstName and LastName properties.  The visual design calls for a "List of people" so there is a View containing a ListBox that has a data template binding to property paths of FirstName and LastName.  The ItemsSource binds to a property of ViewModel that exposes a set instances of types that have a FirstName and LastName property.
So here is the question, should there be a "ViewModel version" of the Model Person type or should the ViewModel simply re-use the existing Person type from the Model?
In either case its quite possible that you would want the properties to be observable.
To consider
What are the objectives behind MVVM?  Quite often we like to present nice long lists of why a pattern exists but in this case there are really only 2.

*

*Separate visual design (note: not design) from code.

*Maximise the testable surface of the overall application.

Exposing Model types on the ViewModel doesn't form an obstacle to either of the above objectives.  In fact it aids testability since the number of types and members that need testing is reduced.
In my opinion I don't see that implementing INotifyPropertyChanged implies binding to visuals.  There may be other reasons why some service may want to observe changes in properties of a model object.
The key principle in the separation of Model from View is hiding of any specifics about the how the View presents the Model from the Model itself.  Adding a ForenameBackColor property to the Model would be probably be bad.  This is where the ViewModel comes in.
Bottom Line
Requiring the Model to expose observable properties is not breach of MVVM, its a simple and general requirement that does not require the Model to have any specific knowledge of any View or indeed that there are any "visuals" involved at all.

A: No, looks fine to me - DataServiceEntityBase is just the name of his base class which all his DTO's/business objects inherit from, nothing wrong with that setup (did that name throw you a little?). If he is putting his data in a ViewModel and then binding his View to the VM then you at least have the VVM part of MVVM.
The main thing i would be upset about is his naming of the FirePropertyChanged method - personally i would have called it OnPropertyChanged.


text:
Q: Determining initial voltage across a capacitor This one has got me stumped. I have a graph of voltage vs time and a corresponding power vs time graph. Taking the integral of the power vs time graph gives me the work done on the capacitor. Now the question says, consider the work done to be 0 now. Find the initial voltage across the capacitor with capacitance of 2 micro Farad
Now I'm using the equation U = .5 * C * V^2 and hoping something clicks but it doesn't seem to be working and I have no idea what else to do. This is the equation for my voltage vs time graph (earlier one when the work wasn't 0):
V = 2t, 0<t<4 micro seconds
V = -0.5t + 10, 4<t<7 micro seconds

Using that in this problem yields the following, correct?
V = 2t + v0, 0<t<4 micro seconds where v0 is the unknown initial voltage
V = -0.5t + 10, 4<t<7 micro seconds

Then its a matter of splitting the work done into two piecewise integrals using these two piece wise functions, doing the integration and ending up with something that helps me solve for v0, right? I am just looking to see if this is the avenue I should be going down. Is there a better way? What solution do you guys get?
Thanks


text:
Q: Probability density function (PDF) of a two-dimensional linear stochastic differential equation (SDE) with additive noise I am considering the same two-dimensional linear SDE as in a previous question:
\begin{cases}
dX_1 =\bigl(A_{11} X_1 + A_{12} X_2 \bigr)\,dt + \sigma \,dW_1,
\\
dX_2 =\bigl(A_{21} X_1 + A_{22} X_2 \bigr)\,dt + \sigma \,dW_2,
\end{cases}
where $W_1$ and $W_2$ are one-dimensional Wiener processes, the $A_{ij}$ are real, and so is $\sigma$.
Is a there a way to obtain an analytical expression for the (unconditional) PDF of $X_1$? Thank you for your help.


text:
Q: event handling in delphi I got a sample of code im trying to understand in delphi,can anyone explain this means below,i know it creates and sets events but im trying to understand why the (nil,true,false,'pishu') i want to know the significance of the nil,true,false and the word in inverted comma's it seems i can write any word in there.
var
  Form1: TForm1;
  h:thandle;
  st:string;
  fopen:textfile;
  countstr:integer;
implementation

{$R *.dfm}

procedure TForm1.Button2Click(Sender: TObject);
begin
   setEvent(h);
   CloseHandle(h);
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
h:=createevent(nil,true,false,'pishu');
resetevent(h);
end;

end.

procedure TForm1.Button1Click(Sender: TObject);
begin
h:=createevent(nil,true,true,'pishu');
 waitforsingleobject(h,infinite);

image1.Canvas.Brush.Color:=clblack;
image1.Canvas.Ellipse(random(image1.Width-100),random(image1.Width),random(image1.Width),random(image1.Width));
image1.Canvas.Brush.Color:=clyellow;
image1.Canvas.Ellipse(random(image1.Width-100),random(image1.Width),random(image1.Width),random(image1.Width));
image1.Canvas.Brush.Color:=clblue;
image1.Canvas.Ellipse(random(image1.Width-100),random(image1.Width),random(image1.Width),random(image1.Width));
image1.Canvas.Brush.Color:=clred;
image1.Canvas.Ellipse(random(image1.Width-100),random(image1.Width),random(image1.Width),random(image1.Width));
image1.Canvas.Brush.Color:=clgreen;
image1.Canvas.Ellipse(random(image1.Width-100),random(image1.Width),random(image1.Width),random(image1.Width));

//рисуем квадраты
image1.Canvas.Brush.Color:=clblack;
image1.Canvas.Rectangle(random(image1.Width-100),random(image1.Width),random(image1.Width),random(image1.Width));
image1.Canvas.Brush.Color:=clyellow;
image1.Canvas.Rectangle(random(image1.Width-100),random(image1.Width),random(image1.Width),random(image1.Width));
image1.Canvas.Brush.Color:=clblue;
image1.Canvas.Rectangle(random(image1.Width-100),random(image1.Width),random(image1.Width),random(image1.Width));
image1.Canvas.Brush.Color:=clred;
image1.Canvas.Rectangle(random(image1.Width-100),random(image1.Width),random(image1.Width),random(image1.Width));
image1.Canvas.Brush.Color:=clgreen;
image1.Canvas.Rectangle(random(image1.Width-100),random(image1.Width),random(image1.Width),random(image1.Width));

CloseHandle(h);
end;

end.

A: CreateEvent takes several parameters. It's defined on MSDN as HANDLE CreateEvent(
LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPTSTR lpName). The parameters are:
lpEventAttributes
==================
Ignored. Must be NULL.

bManualReset
============
Boolean that specifies whether a manual-reset or auto-reset
event object is created. If TRUE, then you must use the
ResetEvent function to manually reset the state to nonsignaled.
If FALSE, the system automatically resets the state to nonsignaled
after a single waiting thread has been released.

bInitialState
=============
Boolean that specifies the initial state of the event object.
If TRUE, the initial state is signaled; otherwise, it is nonsignaled.

lpName
======
Pointer to a null-terminated string that specifies the name of the
event object. The name is limited to MAX_PATH characters and can contain
any character except the backslash path-separator character (\). Name
comparison is case sensitive.

If lpName matches the name of an existing named event object, the bManualReset
and bInitialState parameters are ignored because they have already been set by
the creating process.

If lpName is NULL, the event object is created without a name.

If lpName matches the name of an existing semaphore, mutex, waitable timer,
job, or file-mapping object, the function fails and the GetLastError function
returns ERROR_INVALID_HANDLE. This occurs because these objects share the same
name space.

This explains why you can type almost anything as the "word with inverted commas" (the lpName).
For more information, you can see the MSDN web site's documentation on CreateEvent
here.

A: MSDN is your friend when it comes to API documentation questions .See this for answers to your question about CreateEvent.


text:
Q: Parameterizing a json for jmeter test I am running a HTTP request test in jmeter where I send a json input. For example:
{
 "attribute1":"lala"
 "attribute2":"lala"
}
I need to parametrize this so that for each thread iteration a different value for attribute1 and attribute2 is chosen, possibly from a csv or text file.
Is this possible?

A: Ofcourse it is possible!!
Add CSV Data Set Config

Update your file path

Parameterize with CSV column name
Update the column names in your JSON to parameterize.
if attr1 is the column 1 - then use ${attr1} to get the value from the CSV

Correction:
The json in abobe image should be
{
    "attribute1":"${attr1}",
    "attribute2":"${attr2}"
}


text:
Q: Access MFA enabled github with shell script I'm trying to clone a repository from the MFA enabled git repository. I have the username and token code. How can i use these in a shell script?
When we clone the repo from command line, it is asking for username and password (token key). But how can we do the same from shell script?

A: I just figured out that i can use the below command
sudo git clone https://{user-name}:{token-code}@{git-clone-link}

A: It's not a very good idea to hard-code the token in the URL, because anyone who can get access to your repository can find it.  Instead, it's better to use a credential helper and import the value from the environment, like so:
export GITHUB_TOKEN= # your token here
GITHUB_URL= # your URL here
git -c credential.helper='f() { echo username=token; password=$GITHUB_TOKEN; };f' \
    clone $GITHUB_URL

This is a secure way to pass tokens through the environment which won't result in them appearing in ps output for other users or anywhere else in the file.  You can, of course, set your token environment variable to acquire the token from some other method (like a command) as well.


text:
Q: Does freeing up disk space improve the performance of MySQL? We have a MySQL master server here which was not set up with any kind of management for the binary logs. Over time, the disk space (1 TB) was slowly filling up and it was noticed that the performance of the MySQL server was becoming worse. At the time, I didn't make any connection between disk space issues and performance. I took it upon myself to clean this up, backing up old binary logs and freeing up space on the server.
Now that the transition is (mostly) complete and the server has much more free disk space, I've noticed that the performance has increased. I don't have any numbers to back this up, but one thing that I have noticed is that certain transactions in some of our apps which used to time out on a semi-regular basis are now proceeding smoothly.
I can imagine a couple of explanations for the improved performance:

*

*The disk controller is not having to search as hard for free space

*MySQL is better able to optimize tables, indices, etc.

but I really don't know why. So I really have two questions:

*

*Can a lack of free disk space impact MySQL performance?

*If so, why?

A:
Can a lack of free disk space impact MySQL performance?

Certainly a lack of disk space at all can prevent writes from happening. Especially when storage is beginning to become full (>90%, as a minimal ballpark) and the disks are fragmented, it can take some time to search where writes can even occur when MySQL is trying to write to disk.
This would be true of any database platform or any application that writes to disk. This isn't so much a MySQL behavior as it is a storage behavior.
My suspicion is that you have different qualities of storage disks available to you filesystem(s) that contain the MySQL data. As your server became more full, you would be more frequently subject to the performance of your worst disks in terms of IO.
After purging your server of old binlogs you've likely been able to increase your storage-tier's performance with IO because it takes a shorter amount of time to find places to write. Shorter time to find places to write means faster transaction performance. Faster transaction performance means less timeouts and noticeable delays in application functionality.

A: Is the space used by database table files? if so, yes it could affect performance if the query must read data from disk. That is why it is always a good idea to defrag tables to free up unused space. Again the performance will be depended on what kind of disk your sever is using.

A: Well, I disagree with most of what has been said so far in the Q&A.
The OS, not the disk controller, decides where to put the next block.  The OS's algorithms are pretty linear.  The is a slight bit of overhead for huge tables versus tiny tables.
Fragmentation always happens.  The OS and controllers, especially RAID controllers, mitigate the issues.  Defragmentation is usually more trouble than it is worth.
Enterprise SSD devices employ "wear leveling" to prevent wearing out the drive too soon.  When the disk is "nearly full", this task can slow down the drive in general.  There is no corresponding problem with spinning drives or cheap SSDs.
Binlogs should be removed.  I like using something like expire_logs_days = 14 (2 weeks).
If you need to ALTER a table, and it needs to copy the table, then you do temporarily need enough disk space for an entire copy of the table.  So, keep the disk free space larger than the largest table.
"MySQL is better able to optimize tables, indices, etc." -- Aside from ALTER, I see no rationale for this comment.


text:
Q: std::vector Error shows up: "Cannot increment a vector past the end", while wanting to erase specific element I have a vector of classes, the class has a string name, among other private fields.
I want to implement a void delete(string name) function, which looks for the element based on the string (each class in a vector has a unique name).
However after simple testing, it gives me an error "Cannot increment past the end".
This is my function:
void delete_member(string member_name)
{
    int count = 0;

    for (auto it = member_list.begin(); it != member_list.end(); ++it, ++count)
        if (it->get_name() == member_name)
            member_list.erase(member_list.begin() + count);
}

As far as I have searched for an answer, it seems that the iterator shouldn't go past the .end() of the vector.
What is the flaw here? I am using the same loop to iterate over a vector for add_member(Member m) function which works completely fine

A: The issue is that you erase the element but you do not update the iterators. To avoid dealing with those, it is better to use STL algorithms. The standard usage is as follows
Pre C++20
member.erase(std::remove_if(member.begin(), member.end(), [&](const auto& val)
{
  return val.get_name() == member_name;
}), member.end());

In C++20
std::erase_if(member, [&](const auto& val)
{
  return val.get_name() == member_name;
});

A: You are invalidating it when you erase, so later uses of it are undefined, including incrementing and comparing it in the loop test.
You could
for (auto it = member_list.begin(); it != member_list.end(); )
    if (it->get_name() == member_name)
        it = member_list.erase(it);
    else
        it++

However there is a standard <algorithm> for this.
auto pred = [&](auto & member){ return member.get_name() == member_name; };
auto new_end = std::remove_if(member_list.begin(), member_list.end(), pred);
member_list.erase(new_end, member_list.end());

In C++20, it will be even easier
auto pred = [&](auto & member){ return member.get_name() == member_name; };
std::erase_if(member_list, pred);


text:
Q: Set 3D object behind the real world in Vuforia Augmented Reality I'm using Vuforia SDK for Unity3D in my AR application. The scenario of the app is similar to this demo:
When marker is recognized, the wall with some image on it (like a press wall) and different 3D objects in front of it should appear.
My problem is that I need this wall to be behind the physical world, so that a person standing on the physical marker could see the wall behind him and the rest 3D content in front of him.
I'm not sure if I can use Vuforia Smart Terrain feature, or can I make something like a room (with one wall) with Unity only?
I'd so appreciate if you could give me any resources to read or any ideas on the implementation.


text:
Q: Extending class hierarchy I have an abstract base class:
public abstract class BaseClass
{
    public double CommonMethodForAllSubClasses(double parameter)
    {
        //common implementation
        return 0;
    }

    public abstract double MethodThatMustBeDefinedInSubClasses(double parameter);
}

And a class hierarchy under it.
I want to make, in another assembly, an Extension class for Base class and its subclasses. I thought to do it with a static class with a methods which receive as parameter:
public static Method(this BaseClass, ...)

But I want this static Method to be defined for all subclasses from BaseClass. I know I can't do a static abstract method but I want to avoid to implement these methods in the class itself... And it would be very good that the compiler "tells me" that these methods must be redefined for sub-classes.

A:
But I want this static Method to be defined for all subclasses from BaseClass.

Your extension method would be callable from instance of derived class. But I guess that's not what you meant.

And it would be very good that the compiler "tells me" that these methods must be redefined for sub-classes.

Implementing it as a regular abstract method on the base class is the only way to achieve that.

A: Is this what you want?
public abstract class BaseClass
{
    protected abstract void MethodThatMustBeDefinedInSubClasses();
}

public class ChildClass : BaseClass
{
    protected override void MethodThatMustBeDefinedInSubClasses()
    {
        Console.WriteLine("Do");
    }
}

public static class BaseClassExtensions
{
    public static void DoExtension(this BaseClass foo) { }

    public static void DoExtension(this ChildClass bar) {}
}

You can specify the extension method for every derived class in the hierarchy and provide a specific implementation for it.
About the "compiler telling you" about a extension method, I think that's not possible, because the extension method is just "syntactic sugar". The extension method can be used like this:
var foo = new BaseClass();
foo.DoExtension();

But actually is just like a normal static class:
var foo = new BaseClass();
BaseClassExtensions.DoSomething(foo);

And the compiler cannot warning you that you should make a static class with a method that should accept a specific type.