text:
Q: Как заинжектить в kotlin'овские Object'ы с помощью Dagger2? У меня есть некий логгер, который при достижении определенного количества логов отправляет их на сервер.
Сам класс логгера это Object. Мне нужно заинжектить в него репозиторий.
Судя по этому вопросу:
https://stackoverflow.com/questions/48413780/dagger-injection-not-working-for-object-in-kotlin
это сделать можно.
Application
сlass App : DaggerApplication(), HasServiceInjector {

    @Inject
    lateinit var serviceInjector: DispatchingAndroidInjector<Service>

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return appComponentBuilder.application(this).build()
    }

    override fun serviceInjector(): DispatchingAndroidInjector<Service> {
        return serviceInjector
    }

    private object AppHolder {
        val INSTANCE = App()
    }

    companion object {
        val appComponentBuilder = DaggerAppComponent.builder()
        fun getInstance(): App {
            return AppHolder.INSTANCE
        }
    }
}

AppComponent
@Singleton
@Component(modules = [AppModule::class, ActivityBindingModule::class, ServicesBindingModule::class, InteractorsModule::class, RepositoryModule::class, ToolsModule::class, AndroidSupportInjectionModule::class])
interface AppComponent : AndroidInjector<App> {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(application: Application): Builder
        fun build(): AppComponent
    }

}

Logger
object Logger {

    @set:Inject
    lateinit var repository: Repository

    init {
        //How to inject????
    }

    private fun send() {
        GlobalScope.launch {
            repository.sendLogs(someLogs)
        }
    }

    ....

}

Что и куда нужно добавить?

A: Созданием объектов и внедрением зависимостей занимается у вас даггер, поэтому стоит поручить создание синглтона Logger ему, а не делать это через котлин. Вы же свои репозитории не делаете object?
У вас даже есть отдельный ToolsModule. Можно провайдить Logger через него. Тогда Logger будет class и проблем с инжектом возникнуть не должно, ещё он будет синглтоном, как вы и хотели.


text:
Q: MapGuide open source : manipulating SDF data via java/jsp? I am relatively new to MapGuide open source technology. I would like to parse and modify data that is in SDF format so that my map displays this updated feature data (dynamically). How can i do so? I have MapGuide installed and configured on Linux. I went through the MapGuide Web API documentation but there were no examples on how to manipulate SDF data. Currently i am generating the SDF data in a different environment (in a Windows OS domain) by using scripts to query a spatial database and the query generates SHP files. I then transform those SHP files into SDF files (using scripts) before transferring them to the MapGuide server repository in the Linux OS environment. On the Windows OS end, I am able to edit the SHP files (in particular the dbf file just using a spread sheet) to change the values for the particular feature source. However this process is static and so i was hoping to be able to do so programmatically (using java / jsp) by parsing the SDF files for the particular feature source in the Linux domain.
Thanks

A: Okay.. from what i have learnt elsewhere...The  SDF data cannot be edited directly using the Java Web API, instead Mapguide uses FDO which is an abstraction layer for accessing spatial data using a common api. FDO on MapGuide Open Source
Hope this helps anyone with a similar question to my original question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AttributeError: 'Timedelta' object has no attribute 'dt' I have a df:
    id  timestamp                       data  group Date
27001   27242   2020-01-01 09:07:21.277 19.5    1   2020-01-01
27002   27243   2020-01-01 09:07:21.377 19.0    1   2020-01-01
27581   27822   2020-01-02 07:53:05.173 19.5    1   2020-01-02
27582   27823   2020-01-02 07:53:05.273 20.0    1   2020-01-02
27647   27888   2020-01-02 10:01:46.380 20.5    1   2020-01-02
...

and I would like to calculate the time difference between row 1 and row 2 in seconds. I could do it with
df['timediff'] = (df['timestamp'].shift(-1) - df['timestamp']).dt.total_seconds()

However, when I zoom in to look at only 2 rows, ie. row1 and row0, with code:
difference = (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).dt.total_seconds()

it returned error

AttributeError: 'Timedelta' object has no attribute 'dt'

Why is this happening?

A: By inspection the following is a Series:
type(df['timestamp'].shift(-1) - df['timestamp'])

Series has an accessor (dt) object for datetime like properties. However, the following is a TimeDelta with no dt accessor:
type(df.loc[0, 'timestamp'] - df.loc[1, 'timestamp'])

Just call the following (without the dt accessor) to solve the error:
difference = (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).total_seconds()

A: In case you end up here and want to extract days:
(df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).days

A: As @hpaulj said in the comments, dt is only associated with dataframe like object.
So to obtain total seconds you have to use difference = (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).total_seconds()


text:
Q: What video formats (hopefully WMV) support transparencies? I'm trying to animate my desktop application for a client.
I would like to animate the background with a loop and offer region specific animations on top of this (allowing transparencies to see the layered animations underneath).
Is this possible with WMV? If not, is it possible with another video format?

A: Quicktime movies support alpha channel transparency if the codec does.  The "Animation" codec is commonly used for that purpose.

A: I don't think it supports any of that, I think what you have to do is overlay stuff with transparency.


text:
Q: Query Professors and Salaries greater than the minimum of specific a department Given this Schema:
Professor_ID
Professor_Name
Dept_ID
Salary

Dept_ID
Dept_Name

A university uses 2 data tables, Professor and Departments, to store data about its professor and the departments associated with each major.
Write a query to print the name and salary for each professor:

*

*Professor does not work in the Art department

*Professor's salary is greater than smallest salary of any professor in the Art department

Sample Output:
Joe Smith  22066

Ken Doe 13411

Eliott Scott 19404

Scott Thompson 48299

I just tried something like this but it doesn't work:
SELECT Professor_ID, Professor_Name, Dept_ID, Salary
FROM Professors p
INNER JOIN Departments d
ON p.Dept_ID = d.Dept_ID
WHERE Dept_Name != 'Art'and Salary > (SELECT MIN(Salary))
   FROM Professors p
   INNER JOIN Departments d
   ON p.Dept_ID = d.Dept_ID
   WHERE Dept_Name = 'Arts and Humanities')

A: This will give you that
The portion of the final query tagged ---1 will give you all the salaries of professors that are not in art department
The portion of the final query tagged ---2 will compare the salaries of the professors selected in the first portion and compare it with the smallest salary of professors in Art using the query below:
select min(Salary) from From Professors p inner join Departments d on p.Dept_ID = d.Dept_ID  where Dept_Name = 'Art'

Final Query
--- 111
    select
    Professor_ID,
    Professor_Name,
    Dept_ID,
    Salary
    From Professors p  inner join Departments d on p.Dept_ID = d.Dept_ID
    where Dept_Name != 'Art'
--- 111
--- 222
    and Salary > (select min(Salary) From Professors p inner join Departments d on p.Dept_ID = d.Dept_ID  where Dept_Name = 'Art')
--- 222

A: Select p.name, p.salary from professor p inner join department d on p.department_id = d.id
where d.name <> 'Arts and Humanities' and p.salary > (
select min(p.salary) from professor p inner join department d on p.department_id = d.id
where d.name like '%Arts and Humanities%');


text:
Q: ViewPageIndicator - What is the use of GoogleMusicAdapter in SampleTabsStyled class? I am using ViewPageIndicator and ActionBarSherlock in my app. I rename SampleTabsStyled  class and use it in my app. Everything is going right. I want to know something

*

*Why does it has GoogleMusicAdapter subclass of SampleTabsStyled class?
2.What is the use of TestFragmentAdapter class? Can i rename it and reuse it?

A: the GoogleMusicAdapter class just sets different names for the tabs shown in the example, I think it would be clearer if the declaration of the CONTENT array was inside the nested class.
So, you can skip the use of that class and use directly the TestFragmentAdapter as you suggest.
Hope it helps!


text: Q: I am trying to prove that the cardinality of P(N) (the set of all finite subsets in N) is equal to the cardinality of N. Here, N refers to the set of all natural numbers, and P refers to the power set of N. Let the number of finite subsets be equal to F. I am having trouble representing the cardinality of the power set. :)


text:
Q: Populate Tableview with super class fields I have several classes that all inherit from one super class that need to populate several TableViews related to their class.
The super class is abstract and some of the getters and setters are final but still contains data needed to populate the cells.
Writing a new Callback class for each and every column is doable, but I'm looking for a way to implements this.
sample code
class SuperClass
{
  protected String name;
  protected double value;
  public final void setName(String name)
  {
    this.name = name;
  }
  public final void getName()
  {
    return this.name;
  }
  public final void setValue(double value)
  {
    this.value = value;
  }
  public double getValue()
  {
    return this.value;
  }
}

class SubClass1 extends SuperClass
{
  private int id;
  public void setId(int id)
  {
    this.id = id;
  }
  public int getId()
  {
    return this.id;
  }
}

class SubClass2 extends SuperClass
{
  private String location;
  public void setLocation(String location)
  {
    this.location = location;
  }
}

class SubClass3 extends SuperClass
{
  private ObservableMap<SuperClass> map;
  public ObservableMap<SuperClass> map()
  {
    return this.map;
  }
}

TableView
TableColumn<SubClass1, Integer> tc1_id;
TableColumn<SubClass1, String> tc1_name;
TableColumn<SubClass1, Double> tc1_value;
TableColumn<SubClass2, String> tc2_loc;
TableColumn<SubClass2, String> tc2_name;
TableColumn<SubClass2, Double> tc2_value;
TableColumn<SubClass3, String> tc3_name;
TableColumn<SubClass3, Double> tc3_value;

Here's a reference of what I was going to do...
Accessing Subclass properties in a JavaFX TableView ObservableArrayList
But just with the sample code, I'm basically rewriting 2 methods, 3 times each... and there's a bit more than that in the actual program. (Just a smidge more)

A: I think you are just asking how to reduce the amount of code you have to write. The solution is just the same as any such question: write a method that performs the repetitive part, and parametrize it with the parts that vary. So in this case, you just need to write a generic utility method to generate your table columns, taking the title of the column and the function that produces the property the cell value factory needs.
E.g. you could do something like
private <S,T> TableColumn<S,T> createColumn(String title, Function<S, Property<T>> prop) {
    TableColumn<S,T> column = new TableColumn<>(title);
    column.setCellValueFactory(cellData -> prop.apply(cellData.getValue()));
    return column ;
}

and then if your model classes use JavaFX properties, all you need is
TableColumn<SubClass1, Number> tc1Id = createColumn("Id", SubClass1::idProperty);

etc.
If you are not using JavaFX properties (which is the recommended approach), you can still do
TableColumn<SubClass2, String> tc2Loc =
    createColumn("Location", item -> new SimpleStringProperty(item.getLocation()));

or just create a method that accepts a Function<S,T> instead of a Function<S,Property<T>>.


text:
Q: How to write the similar code in PHP Laravel? How to write a similar code in Laravel. Below normal PHP code is working fine.
<?php
    foreach ($snippets as $post) {
        $userdata = App\Models\Constant_model::getDataOneColumn('users', 'id', $post->listed_by)->get();
        $userpicture = $userdata[0]->email;
?>
<?php echo $userpicture; ?>

<?php } ?>

But I want to change it like this in Laravel.
@foreach ($snippets as $post)
    $userdata = App\Models\Constant_model::getDataOneColumn('users', 'id', $post->listed_by)->get();
    $userpicture = $userdata[0]->email;
    {{$userpicture}}
@endforeach

The result I am getting is
$userdata = App\Models\Constant_model::getDataOneColumn('users', 'id', $post->listed_by)->get();
$userpicture = $userdata[0]->email;

A: When you use blade template, you cannot simply mix with a PHP code. Because, blade template is actually a HTML codes. The blade directive (@foreach, {{ }} etc) is actually a short hand for PHP code.
My suggestion is to handle the fetch data from the Controller, and View should be only for displaying the data. But if you insist, you could use the @php directive.
@foreach($snippets as $post)

    @php
       $userdata = App\Models\Constant_model::getDataOneColumn('users','id', $post->listed_by)->get();
       $userpicture = $userdata[0]->email;
    @endphp

    {{$userpicture}}

@endforeach


text:
Q: What is the probablity that a Rubik's cube is solvable if you randomly switch two squares? I am trying to learn how to solve a Rubik's cube and the 4x4 rubic cube at school is missing 4 squares, that got me thinking: if you randomly switched two squares, would it still be solvable?
I know that the flat picture (example of what I mean) where you slide a square around on the xy plane are solvable omitting if you switch the last two squares when it is in its identity location. For example if cut a picture into 16 squares and then removed the 16th (bottom righthand) and then you switched the 14th and the 15th square then it would be unsolvable.
I really don't know how to say that better mathematicaly

A: For the standard Rubik cube, the probability is zero if you switch two squares that are actually of different colour:
The Rubik cube has squares at face centers, which don't move at all; edge cubelets, which may rotate and move around, but always stay edge cubelets; vertex cublets, which may rotate and move around, but always stay vertex cubelets.

*

*If you switch two face centers, the cube becomes unsolvable because no suitable vertex cubelets will be available for at least one vertex.

*If you switch the two faces of the same edge cubelet, the cube becomes unsolvable because flipping such a cubelet is not en element of the group.

*If you switch two faces of the same vertex cubelet, the cube becomes unsolveable because that cubelet no longer fits (wrong orientation of the colours on it)

*If you switch squares between different edge cubelets, this would require to not alter the set of edge cubelets. E.g., you must not produce a second green-yellow edge. This means that you need to switch between two cubelets sharing a colour (say switch yellow and red between the gren-yellow and the green-red edge cubelet). If I remember correctly$^1$, it is not possible to switch two edge cubelets belonging to the same face while keeping their orientation correct (with respect to the common face)

*If you switch squares between differnt vertx cubelets, this makes the cube unsolvable. Indeed, knowing two of the squares of a vertex cubelet, its correct placement is already completely determined.

$^1$  This is the only point I'm not 100% sure of and would have to check.
EDIT: After checking at Wikipedia, I got rid of the doubts mentioned in the footnote: Even considering only position, not orientation of cubelets, the group operates only as $A_{12}$, not $S_{12}$ on the edges.

A: I'm posting a new answer, because existing answer deals with 3×3 cube, which is very different in this regard from a 4×4 cube.
To actually answer the question, YES a 4×4 cube will be solvable if you randomly exchange any two centers.
On a 4×4 cube, the parity of centerpieces permutation must always be the same as the parity of the cornerpieces permutation, however, odd and even parity of centers permutation is not distinguishable, as there are 4 identical centers of each color.
This can be demonstrated by a simple commutator-algorithm such as this one. This algorithm exchanges three centerpieces from the mechanical perspective, however, due to the fact that two of those are of the same color, the resulting effect is that only two centerpieces have been exchanged.


text:
Q: Animate table view performFetch like the missed calls in the iPhone phone app I have a UISegmentedController that controls a TableView.
when the selectedIndex is switched I am preforming a performFetch method with a new predicate that causes a change in the tableView content.
it works fine but i want it to animate in the same style that apple did in the phone application when you switch between all recents and only un answered calls.
appreciate any help.

A: O.K managed to do that -
I dont Know how apple do that but i seceded when i have realized that preforming new fetch is more expensive operation then that -
step 1:
in my case i have added a mutableArray that collects all the indexes of the cells i want to disappear when the user clicks the segmented controller.
in the CellForRaw function i inserted this little code:
- (void)configureCell:(PersonCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    // Configure the cell
    if([fetchedResultsController objectAtIndexPath:indexPath]!=nil){
    Person *person = (Person *)[fetchedResultsController objectAtIndexPath:indexPath];
    cell.person = person;
    cell.delegate=self;

        if (person.state!=0) {
            [activeIndexPaths addObject:indexPath];
        }
    }
}

that inserts the indexPath of the objects i want to filter to the Array for later use.
step 2:
the next function is called when a change made in the segmentedController -
-(void)ReloadTableViewWithNewPerdicate:(id)sender{

    UISegmentedControl *sc = (UISegmentedControl*)sender;
    //[theTableView beginUpdates];
    Person *person;
    switch (sc.selectedSegmentIndex) {
        case 1:
            for (int i=0; i<[activeIndexPaths count]; i++) {
                person=(Person*)[fetchedResultsController objectAtIndexPath:[activeIndexPaths objectAtIndex:i]];
                [fetchedResultsController.managedObjectContext deleteObject:person];
            }

            //[theTableView insertRowsAtIndexPaths:activeIndexPaths withRowAnimation:UITableViewRowAnimationRight];
            break;
        case 0:
            [fetchedResultsController.managedObjectContext rollback];
            break;

    }

This function delete the raws from the fetchedResultsController.managedObjectContext
and the:
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller{
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
}

functions are responsible for deleting the un needed raws.
and this is basically how you get the effect of the deletion.
step 3:
when the user taps the main segmentedController button the function calls:
            [fetchedResultsController.managedObjectContext rollback];

that literally  rolls everything back.
step 4:
Last importent step is to add the rollBack  function to the ViewWillDisAppear to make sure that the save function in your app delegate wont save the changes and delete the raws from the store.
hope it will help someone.
good day.


text:
Q: Solution Verification - Combinatorial Card-Picking I have a problem as such:

How many ways are there to choose nine cards out of a standard deck of 52 cards in such a way that every suit is represented in the selection at least twice?

Here's my solution:
Partition the set into the four suits - then pick two cards from each suit: there are ${13 \choose 2}^4$ ways to do this. Then there are $44$ cards left over, of which one has to be picked. ${44 \choose 1} = 1$. So the total number of ways the goal can be achieved is $44 \cdot {13 \choose 2}^4$.
The trouble is that this gives me something like $1.6$ billion ways, which seems unrealistically large. Have I made a mistake?

A: If you need that "every suit is represented in the selection at least twice" in the selection of 9 cards, so you have 3 cards of one suit and 2 cards of each other suit.
you can pick 2 cards out of 13 in ${13 \choose 2}$ different ways and you can pick 3 cards out of 13 in ${13 \choose 3}$ different ways. And if you have 4 different suits, so you need to multiply the answer by 4. There are $4 \cdot {13 \choose 2}^3 \cdot {13 \choose 3}$ different ways :)
542887488 :)


text:
Q: Mariadb is giving warning for this query and table Please create the following table,
CREATE TABLE test3 (

  meta_key varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  meta_value varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO test3 (meta_key, meta_value) VALUES
('utm_source', 'facebook'),
('lead_date', '20180915'),
('utm_source', 'facebook'),
('lead_date', '20180905');

then run the following query
select meta_value
from (select meta_value
      from test3
      where meta_key='lead_date') as q0
where date(meta_value)<CURDATE()   ;

you will get following warning while running them (use adminer to see them)
Level   Code    Message
Warning 1292    Incorrect datetime value: 'facebook'
Warning 1292    Incorrect datetime value: 'facebook'

Ideally, this should not have happened. Can someone explain what's wrong here?
Update
This query is actually part of a bigger set of queries. It has been reduced to this level to highlight the warnings.
The issue is not with CURDATE. if you write date(meta_value) is NOT NULL it will give warnings.
In fact, it will give warnings with all date related functions in where clause.
It does not seem that it could be an optimization issue.
Try the following queries with a join. At this point, the optimizer cannot optimize since I am comparing with another table.
It will still give a warning.
drop table if exists test3;
CREATE TABLE test3 (

  meta_key varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  meta_value varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO test3 (meta_key, meta_value) VALUES
('utm_source', 'facebook'),
('lead_date', '20180915'),
('utm_source', 'facebook'),
('lead_date', '20180905');

select meta_value
from (select meta_value
      from test3
      where meta_key='lead_date') as q0 , (select date('20200101') as
compare) as d
where date(meta_value)<compare  ;

Now try another query:
select meta_value
from (select meta_value
      from test3
      where meta_key='lead_date' limit 1000000) as q0
where date(meta_value)<CURDATE()  ;

This will not give an error.

A: You expect the subselect (select meta_value from test3 where meta_key='lead_date') to materialize only rows that contain values in meta_value that can be converted to the DATE data type, but this is not happening: the optimizer inlines the subselect and simultaneously applies two predicates: meta_key='lead_date' and date(meta_value)<CURDATE() to all rows in the table, which obviously fails for rows containing 'facebook' in meta_value.

A: Date format is '2018-09-15', not '20180915'.
Don't use subqueries when you don't need to.
select  meta_value
    from test3
    where  meta_key = 'lead_date'
    where  meta_value < '2020-01-01';

Have
PRIMARY KEY(meta_key)

In the long run, you will find EAV schema to be a pain.


text:
Q: isset in php not working in angularjs I am new to angularjs and I am having issue with using isset in php. I am developing a website using angularjs-1. I want to get the value of the parameter in the url but I can't do it. Here's my code:
app.config(function($routeProvider, $locationProvider){
    $locationProvider.html5Mode(true).hashPrefix('!');

    $routeProvider
    .when('admin/dashboard/gallery/folder'{
          templateUrl: '_pages/gallery-folder',
          controller: 'gfCTRL',
          resolve: {
                delay: function($q, $timeout){
                     var delay = $q.defer();
                     $timeout(delay.resolve, 1000);
                     return delay.promise;
                  }
          }
     });
});

app.controller('gfCTRL', function($scope, $rootScope){
     $rootScope.statechange = true;
});

And in my HTML:
Open

And in my PHP:
if(isset($_GET['lbl'])){
    echo $_GET['lbl'];
}else{
    echo "None";
}

For now, it only gives me the result of none. Why?

A: There is a way to check $_GET['lbl']; as var_dump($_GET['lbl']);
i would also make your check also check for nothing.
ex:
if(isset($_GET['lbl']) && $_GET['lbl'] !== "") // This also makes sure something is entered. Because any one can delete part of the $lbl=2
i would first check to see if $_GET is getting lbl with var_dump if not it might be spelling or something else. Always make a check to test your work in building.


text:
Q: How can I find what is sending out a confirm? I have an issue with a server I'm working with, and I need to figure out where a certain error is coming from. Specifically, I would like to know what script is having trouble. I get three consecutive confirm boxes alerting me of an error and asking if I want to continue when a certain part of a page starts to load.
Is there a way I can figure out where those are coming from, specifically within the Chrome Developer tools?
Thanks

A: Rightclick on your page, click "select element" and then take the console tab.

It will show u errors that have happened on this page and its source (bottom left). Click on that source to see the lines where the error was detected.
Excuse my not-so-decent drawing skills :)


text:
Q: git-svn: How to know current SVN revision of a git-svn working copy? I have a git-svn working copy and git log gives me no direct info about which SVN revision I'm on. I understand that once I rebase I should have all upstream logs converted into git log, but that still doesn't seem to give a REVISION NUMBER to me and I'd have to do text mining to find out.
Is there a simple command that I'm missing?

A: It shows up at the bottom of each commit message. There's a log line similar to this:
git-svn-id: http://svn.example.com/trunk/whatever@12345 [git-svn remote hash]

The 12345 is that commit's SVN revision


text:
Q: npm for javascript client side code I was reading a document about npm Developer Guide.
I was wondering if it is possible to write a web client application using javascript/css/html
 by using npm?
If yes,  are there some example on github?
For example my client web application depends on requirejs, jquery, underscore and backbone.
Can I use npm to automatically download, in the vendor directory, the latest version of requirejs, jquery, underscore and backbone ?
If not, are there other tools/methods to accomplish this goal?

A: Yeoman uses a package manager called Bower to manage dependencies - the Bower Github page gives an example of downloading jQuery for a project, so this might be useful for your projects.

A: Okay, now your question becomes clear. Yes, you can use NPM to help you develop JavaScript for the front-end. There are lots of tools available that will make your workflow much smoother. I mentioned jshint and uglifyjs already, but you have grunt to do a bunch of useful tasks, less and sass compilers, and the list goes on. To manage dependencies in CommonJS you'd typically use a package.json.

A: An example is my Pretty Diff tool.  It works equally well on the client side and I distribute it via NPM.  A well written JavaScript application will run absolutely anywhere there is a JavaScript interpreter regardless of the environment.  The way to accomplish this is to separate the application code from any APIs.  In the case of my application I use the following APIs:

*

*DOM - web browser

*WSH - Windows command line

*Node.js - Node.js

A: Long version:
npm is a manager for packages used by nodejs, which is a program for running javascript on serverside.
You can develop your own packages for nodejs and upload them to npm, or use it to install packages released by others, but those are only packages for nodejs, which is serverside, not clientside. So no, you cant use npm for what you want.
Version for really lazy people:
No, because npm is for nodejs, which is serverside, and thus it has nothing to do with clientside applications.
I hope this answers your question.


text:
Q: Can't import System.Net.Http on VB.Net page I'm trying to use HttpClient on a VB.NET page (Windows Server 2019 IIS 10), but getting BC30002 error. Tracing the error in IIS, I see warning BC40056 (Namespace not found) on line:
Imports System.Net.Http

Running gacutil, seems that the assembly is correctly installed on server:
>gacutil.exe /l system.net.http
Microsoft (R) .NET Global Assembly Cache Utility.  Version 4.0.30319.0
Copyright (c) Microsoft Corporation.  All rights reserved.

The Global Assembly Cache contains the following assemblies:
  system.net.http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL

Number of items = 1

Also tryed to add the following to web.config (should not be necessary and didn't help):
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>

Other assemblies load fine (including plain System.Net).
Where am I wrong ?

A: Finally understood that, even if .NET Framework 4.8 supports HttpClient, CLR is still at 4.0 version (that don't support HttpClient).
Optimal solution, as noted by user9938, would be migrating to .NET 6, but, for an old app where I just need to add a small integration, was easier for me to use old WebClient, instead of HttpClient. This works like a charm:
Imports System.Net
...
Using client As New WebClient()
   BackJson = client.DownloadString(APIUri)
End Using

WebClient is still supported (as of .Net 6.0.6), even if not recommended for new development.


text:
Q: c++ STL set difference Does the C++ STL set data structure have a set difference operator?

A: Not an "operator" in the language sense, but there is the set_difference algorithm in the standard library:
http://www.cplusplus.com/reference/algorithm/set_difference.html
Of course, the other basic set operations are present too - (union etc), as suggested by the "See also" section at the end of the linked article.

A: Once again, boost to the rescue:
#include <string>
#include <set>
#include <boost/range/algorithm/set_algorithm.hpp>

std::set<std::string> set0, set1, setDifference;
boost::set_difference(set0, set1, std::inserter(setDifference, setDifference.begin());

setDifference will contain set0-set1.

A: The chosen answer is correct, but has some syntax errors.
Instead of
#include <algorithms>

use
#include <algorithm>

Instead of
std::insert_iterator(result, result.end()));

use
std::insert_iterator<set<int> >(result, result.end()));

A: C++ does not define a set difference operator but you can define your own (using code given in other responses):
template<class T>
set<T> operator -(set<T> reference, set<T> items_to_remove)
{
    set<T> result;
    std::set_difference(
        reference.begin(), reference.end(),
        items_to_remove.begin(), items_to_remove.end(),
        std::inserter(result, result.end()));
    return result;
}

A: Yes there is, it is in <algorithm> and is called: std::set_difference. The usage is:
#include <algorithm>
#include <set>
#include <iterator>
// ...
std::set<int> s1, s2;
// Fill in s1 and s2 with values
std::set<int> result;
std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
    std::inserter(result, result.end()));

In the end, the set result will contain the s1-s2.

A: Yes, there is a set_difference function in the algorithms header.
Edits:
FYI, the set data structure is able to efficiently use that algorithm, as stated in its documentation.  The algorithm also works not just on sets but on any pair of iterators over sorted collections.
As others have mentioned, this is an external algorithm, not a method.  Presumably that's fine for your application.

A: Not as a method but there's the external algorithm function set_difference
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_difference(InputIterator1 first1, InputIterator1 last1,
                              InputIterator2 first2, InputIterator2 last2,
                              OutputIterator result);

http://www.sgi.com/tech/stl/set_difference.html

A: Apparently, it does.
SGI - set_difference

A: All of the answers I see here are O(n). Wouldn't this be better?:
template <class Key, class Compare, class Allocator>
std::set<Key, Compare, Allocator>
set_subtract(std::set<Key, Compare, Allocator>&& lhs,
             const std::set<Key, Compare, Allocator>& rhs) {
    if (lhs.empty()) { return lhs; }
    // First narrow down the overlapping range:
    const auto rhsbeg = rhs.lower_bound(*lhs.begin());
    const auto rhsend = rhs.upper_bound(*lhs.rbegin());
    for (auto i = rhsbeg; i != rhsend; ++i) {
        lhs.erase(*i);
    }
    return std::move(lhs);
}

That seems to do the right thing. I'm not sure how to deal with the case that Compare's type doesn't fully specify its behavior, as in if Compare is a std::function<bool(int,int)>, but aside from that, this seems to work right and should be like O((num overlapping) • log(lhs.size())).
In the case that lhs doesn't contain *i, it's probably possible to optimize further by doing an O(log(rhs.size())) search for the next element of rhs that's >= the next element of lhs. That would optimize the case that lhs = {0, 1000} and rhs = {1, 2, ..., 999} to do the subtraction in log time.

A: can we just use
 set_difference(set1.begin(), set1.end(), set2.begin(). set2,end(),std::back_inserter(result)).


text:
Q: Xcode 5 error: "Malformed or corrupted AST file: mismatched umbrella header in submodule" After adding StoreKit to my Xcode 5 project, I now see...
"Malformed or corrupted AST file: mismatched umbrella header in submodule"
...whenever I've imported any header from StoreKit.  I haven't changed those system headers, and clearing derived data and the usual Clean Build Folder fix doesn't work either, nor does restarting Xcode change anything.
I see in the Clang sources where the error is being reported, but I can't tell why. Here's the relevant Clang code from http://clang.llvm.org/doxygen/ASTReader_8cpp_source.html:
case SUBMODULE_UMBRELLA_HEADER: {
03728       if (First) {
03729         Error("missing submodule metadata record at beginning of block");
03730         return true;
03731       }
03732
03733       if (!CurrentModule)
03734         break;
03735
03736       if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
03737         if (!CurrentModule->getUmbrellaHeader())
03738           ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
03739         else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
03740          Error("mismatched umbrella headers in submodule");
03741           return true;
03742         }
03743       }
03744       break;
03745     }

It evidently compares my imported umbrella header
#import <StoreKit/StoreKit.h>

to something else, but I can't determine what that something else is.
Has anyone else encountered this, and hopefully found a way to resolve it?

A: I was able to encounter this problem, following the direction mentioned by John above doesn't work for me. I was able to solve this problem by doing the following:

*

*close all open XCode projects.

*Delete all the folders inside Derived Data folder.

How to go to Derived Data folder? just right click on your Product build and show finder, browse through the hierarchy of folders and look for Derived Data.
Hope this helps. This seems to be a bug in Xcode? but not sure.

A: This solved it for me:

*

*go to project build settings

*scroll down to LLVM 5.1 Language Modules

*set Enable Modules (C and Obj C) to NO

A: In Xcode go to Window->Organizer->Projects select your project and press delete button next to Derived data. Just did it (and it worked) with information the following question:
fatal error: malformed or corrupted AST file - Xcode

A: In your Project folder there would be couple of folders named Derived Data and build. Just remove those folders and the problem would be resolved. These folders get created automatically once you open your XCode.


text:
Q: Download google spreadsheet use google spreadsheet api I have a working example that I got here. https://developers.google.com/google-apps/spreadsheets/ I need to download some files from user's google doc.
import com.google.gdata.client.spreadsheet.*;
import com.google.gdata.data.spreadsheet.*;
import com.google.gdata.util.*;

import java.io.IOException;
import java.net.*;
import java.util.*;

public class MySpreadsheetIntegration {
public static void main(String[] args)
  throws AuthenticationException, MalformedURLException, IOException, ServiceException {

SpreadsheetService service =
    new SpreadsheetService("MySpreadsheetIntegration-v1");

// TODO: Authorize the service object for a specific user (see other sections)

// Define the URL to request.  This should never change.
URL SPREADSHEET_FEED_URL = new URL(
    "https://spreadsheets.google.com/feeds/spreadsheets/private/full");

// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();

// Iterate through all of the spreadsheets returned
for (SpreadsheetEntry spreadsheet : spreadsheets) {
  // Print the title of this spreadsheet to the screen
  System.out.println(spreadsheet.getTitle().getPlainText());
}
}
}

Now I need to download some spreadsheets. How do I do it with google spreadsheet api?

A: Download spreadsheets
Use the google drive api to download spreadsheets. You can download as CSV, PDF etc.
Code sample: how to download with drive api - Getting a merged cell width on Google Spreadsheet API
Update with Spreadsheet-api (gdata)
To update the spreadsheet with data, use the Spreadsheet-api. See this google example http://gdata-java-client.googlecode.com/svn-history/r51/trunk/java/sample/spreadsheet/cell/CellDemo.java
Update with google-apps-script
You can also use the more powerful google-apps-script to update a spreadsheet (server side java script).


text:
Q: QR Code Web Service I am working on an mobile web app where people will be able to "check-in" (in a sense) by scanning a QR code at a location and it will direct to a certain URL and if the user is logged into the phone app then their attendance will be logged. The codes will be generated using a PHP library (different QR code / URL for every location).
My fear is that the user will see the URL in the browser when they scan the code and be able to enter it manually without scanning.
Anyone have any ideas to prevent this? This will be a mobile web app, and not a hybrid app in the market (read: no PhoneGap)

A: I have been using PHP QR Code encoder by Dominik Dzienia.
http://phpqrcode.sourceforge.net/
Example:
include('qr/qrlib.php');

$text = 'my text';
QRcode::png($text);
echo $text;

A: I guess one possibility would be some basic form of encryption.
create a hidden input containing some random string
  <?php
  $rnd=md5(rand());
  session_start();
  $_SESSION['rnd']=$rnd;
  ?>

  <input type="hidden" value="<?php echo $rnd; ?>">

md5 the hidden input with the qr code in javascript with http://www.myersdaily.org/joseph/javascript/md5-text.html and return the result along with the qr code.
then server side you can md5 the returned qr code with the same random string and check the result matches. If it does then you give the user a positive result.
since the random string changes every page load there is no way too cheat it

A: Your situation as described might best be handled through an HTACCESS file as opposed to a PHP method. In using a HTACCESS file you can utilize MOD_REWRITE to eliminate the trailing information behind a URL such as session variables or other information (file name and extension - such as index.html) so that the browsed url will display as the parent path, for example:
http://www.yoursite.com/clients/abc123/index.html
would display as:
http://www.yoursite.com/clients/abc123/
or other ways depending on how your rewrite rule is set. I am by no means a expert on HTACCESS and the MOD_REWRITE rules, so i will recommend the following page and its related links at the bottom as a good place to start.
guide to HTACCESS and MOD_REWRITE


text:
Q: Setting GPU fan speed using free ATI driver? Is it possible to set the GPU fan speed using the default free ati driver?
My card (X1900) was deprecated in the fglrx drivers a while back.
The free drivers seem to work with 3D, Compiz and such, but running graphics intensive programs makes my GPU heat up and produce artifacts, while the GPU fan never seems to increase. (When set to 100% in Windows it makes a massively louder noise.)

A: Ok because no one else is willing to say anything. lm-sensors is the package in ubuntu that will help with your quest the first thing to find out is whether lm-sensors detects your gpu temperature sensor as this is what will probably control the speed of the GPU cooler fan. To test whether your gpu temp is detected you will need to paste this command in a terminal first.
sudo sensors-detect

This will go through a sensor detection script it will then output a section of code to add to your modules file which will load additional modules specific for your system. It should look some thing like this.
#----cut here----
# I2C adapter drivers
i2c-viapro
i2c-isa
# I2C chip drivers
eeprom
it87
#----cut here----

you will need to add this to etc/modules/ you can open it with
gksudo gedit /etc/modules

I suggest you take a look at the howto by DeMus on the Ubuntu forums as it goes in to much more detail you can check it here.
lm-sensors howto
after you have got the output of the sensors command paste it at paste.ubuntu.com and add the link to original question and I will be able to see if you are going to be able to continue to the next level Quest!
Good luck!


text:
Q: Connect geom_points by lines wíth keeping distance In ggplot2, I want to make an easy geom_point() scatter plot, with the dots connected by a line. However, I want the lines not to touch the point, as for example in this graph but I do not seem to manage at all in ggplot2.

A: This is a hack but this might help

x=1:20
y=rnorm(20)
data=data.frame(x,y)
library(ggplot2)

ggplot(data,aes(x,y))+
  geom_line()+
  geom_point(size=4,color="white")+
  geom_point()+
  theme_bw()


text:
Q: How to scroll to the bottom of an image on hover Hi i am just curious to know the best way to go about being able to scroll to the bottom of an image on hover. The image is in a wrapper with overflow hidden applied to it as its quite long. Ideally a smooth scroll to the bottom is what I am looking for to see the rest of the hidden image.
I have been playing around with jquery trying to get it to work but i have got into a muddle. Not sure if I am on the right track with my code or not really.
Appreciate any help

$('#image-wrap img').on('hover', function() {
  var target = $(this),
    height = target.height(),
    scrollHeight = target.prop('scrollHeight');

  target.animate({
    scrollTop: scrollHeight - height
  }, 2000);
});
#main-wrapper {
  width: 600px;
  margin: 0 auto;
}

#box-wrapper {
  position: relative;
}

#box {
  width: 100%;
  height: 400px;
  border: 1px black solid;
  position: relative;
}

#image-wrap {
  overflow: hidden;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
}

#image-wrap img {
  position: absolute;
  top: 0;
  width: 100%;
}

A: You can use simply CSS3. On hover add transition transform: translateY(-100%), but it's not smart like the jquery solution.

#main-wrapper {
  width: 600px;
  margin: 0 auto;
}

#box-wrapper {
  position: relative;
}

#box {
  width: 100%;
  height: 400px;
  border: 1px black solid;
  overflow: hidden;
}

img {
    transition: all 2000ms ease-out;
}

#box:hover img {
    transform: translateY(-100%);
}

A: I understand now how you would like to it to be.
HTML

$(document).ready(function(){
  $('#img-holder').mouseenter(function(){
    var x = $('img').height();
    x = x-400;
    $('img').animate({'position':'absolute','top':'-'+x}, 300);
  });
   $('#img-holder').mouseleave(function(){
     $('img').css({'position':'relative','top':'0'});
   });
});
#img-holder{
  width:100%;
  height:400px;
  border:2px solid;
  overflow:hidden;
  position:relative;
}

The idea is making the position of the img absolute and give it a value to display the bottom part.
Here is a working DEMO

A: Please try the following:

$('#image-wrap img').hover(function() {
  $('html, body').animate({
        scrollTop: $(this).offset().top + $(this).outerHeight()
    }, 2000);
});
#main-wrapper {
  width: 600px;
  margin: 0 auto;
}

#box-wrapper {
  position: relative;
}

#box {
  width: 100%;
  height: 400px;
  border: 1px black solid;
  position: relative;
}

#image-wrap {
  overflow: hidden;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
}

#image-wrap img {
  position: absolute;
  top: 0;
  width: 100%;
}

A: So I guess you want to scroll the whole page (kinda like using your mouse-wheel)?
You could do something like this:
$('#image-wrap img').on('hover', function() {
  var target = $(this),
    height = target.height(),
    scrollHeight = target.offset().top;

    $('body,html').animate({
         scrollTop:scrollHeight+height-500
    },500);
});

This would then scroll the page, so the last 500px of the image are visible. If that doesn't solve your problem, an example with the whole page would be helpful.

A: If the image is hidden, you cannot interact with it. If it is visible, you can use scrollTo() like this.

*

*Capture the current scroll position using scrollTop()
var pos = $('your image container').scrollTop();

*Grab the height of the image container
var height = $('your image container').height();

*Add the two values
var moveto = pos + height;

*Autoscroll to the position
window.scrollTo( 0, moveto );


text:
Q: java.lang.IllegalArgumentException: Receiver not registered: android.support.v7.app.AppCompatDelegateImplV14$AutoNightModeManager$1 I got a strange exception in a crash-report and am searching for a way to address it. This happens with appcompat 24.2.1
java.lang.IllegalArgumentException: Receiver not registered: android.support.v7.app.AppCompatDelegateImplV14$AutoNightModeManager$1@35ab2dd
at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:780)
at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1195)
at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:576)
at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:576)
at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:576)
at android.support.v7.app.AppCompatDelegateImplV14$AutoNightModeManager.cleanup(SourceFile:345)
at android.support.v7.app.AppCompatDelegateImplV14.onStop(SourceFile:117)
at android.support.v7.app.AppCompatDialog.onStop(SourceFile:119)
at android.app.Dialog.dismissDialog(Dialog.java:369)
at android.app.Dialog.dismiss(Dialog.java:345)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(SourceFile:161)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:764)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

As a info from questions here the only BroadcastReceiver I use:
    <receiver
            android:name=".InstallListener"
            android:exported="true">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER"/>
        </intent-filter>
    </receiver>

public class InstallListener extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String rawReferrerString = intent.getStringExtra("referrer");
        if (rawReferrerString != null) {

            final Intent newIntent = new Intent(context, PassImportActivity.class);
            newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            newIntent.setData(Uri.parse(rawReferrerString));

            context.startActivity(newIntent);
        }
    }

}

A: Ok so two things. One, are you calling unregisterReceiver(..) anywhere in your code? if so, edit your original question and show where you are calling that.
And second thing, in your AndroidManifest.xml, change this:
<receiver
    android:name=".InstallListener"
    android:exported="true">
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER"/>
    </intent-filter>
</receiver>

to this:
<receiver
    android:name=".InstallListener"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER"/>
    </intent-filter>
</receiver>

Note: enabled is set to true.
Try this out.


text:
Q: How to constrain template parameters I want to create a template that accepts only certain type parameters. For all the remain types I wish to produce a compile time error message. So I write the following
------Version 1------
template <typename T_,bool isError = true>
struct Error {
    static_assert(!isError, "Invalid Type");
};

template <typename T_>
struct Wrapper : Error <T_> {
private:
    T_ value_;
};

template <>
struct Wrapper<int> : Error<int, false> {
private:
    int value_;
};

int main()
{
    Wrapper<int> wi;
    Wrapper<long> wl;  // I get the Invalid Type.
}

Since I didn't use type parameter T_ I've removed it and code stopped working.
------Version 2------
template <bool isError = true>
struct Error {
    static_assert(!isError, "Invalid Type");
};

template <typename T_>
struct Wrapper : Error <> {
private:
    T_ value_;
};

template <>
struct Wrapper<int> : Error<false> {
private:
    int value_;
};

int main()
{
    Wrapper<int> wi;   // I get Invalid type ?????
    Wrapper<long> wl;  // I get the Invalid Type.
}

My questions are. Why is this happening after removing the type argument? Is this solution "clean"? Or exist better ways to achieve my intentions?

A: Once you have:
template <typename T_>
struct Wrapper : Error <> {
private:
    T_ value_;
};

We can see that Error<> is fully specified (that is, all template parameters are known), unlike before where it was still dependent. Because of that, the compiler will actually go ahead and instantiate Error<> unconditionally, which means this code will never compile (even if Wrapper isn't mentioned at all). When Error still depended on T, it was a dependent type, so it was only instantiated case by case when a Wrapper<T> needed it.
I would probably separate out the trait a little differently:
template <class T>
struct my_trait : std::false_type {};

template <>
struct my_trait<int> : std::true_type {};

template <class T>
struct Wrapper {
    static_assert(my_trait<T>::value, "");
};

int main()
{
    Wrapper<int> wi;
    Wrapper<long> wl;  // I get the Invalid Type.
}

If you really want to reuse the error message, you can do something like this:
template <typename T>
struct Error {
    static_assert(my_trait<T>::value, "Invalid Type");
};

template <class T>
struct Wrapper {
  static constexpr auto unused = Error<T>{};
};


text:
Q: how to cancel the background running thread in my iphone app i wrote like:
    [self performSelectorInBackground:@selector(backgroundImageLoading) withObject:nil];
to load image background but know i need to stop this when i refresh the view but i don't have any idea how to do

A: See NSOperation and NSOperationQueue.
Its also to do the process concurrently as like background thread. Here in NSOperation you have cancel method available to stop the operation.

A: The threads should not be forced to kill. look out the reasons here. It may help you to find the solution.


text:
Q: Gridview - convert textboxcell to comboboxcell and back I have a question about datagridviewcell.
i have created textboxcolumn in datagridview. when ever i click the particular cell the cell should change to datagridviewcomboboxcell. Also i need to add the item in combobox collection.
when i go to another cell then, the new cell get datagridviewcombobox cell and existing cell should change to datagridviewtextbox cell...

A: You could change the DataGridViewTextBoxCell to DataGridViewComboBoxCell in the CellBeginEdit event and change it back in CellEndEdit event.
Try this:
        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {   DataGridViewComboBoxCell cb=new DataGridViewComboBoxCell();
            cb.Items.Add(dataGridView1.CurrentCell.Value);
            //add your other itmes here;
            dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = cb;//change the DataGridViewTextBoxCell to DataGridViewComboBoxCell
        }

        delegate void settexthandler(DataGridViewCellEventArgs e); //use delegate to prevent reentrant call

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView1.BeginInvoke(new settexthandler(settoTextBox), new object[] { e });
        }

        void settoTextBox(DataGridViewCellEventArgs e)
        {
            DataGridViewTextBoxCell tb = new DataGridViewTextBoxCell();

            tb.Value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = tb; //set it back to DataGridViewTextBoxCell with newly selected value
        }


text:
Q: Automatically add quotes I would like to create a new environment which will behave similar to quote, but with quotes added. I tried something like this:
\newenvironment{newquote}{\itshape\color{blue!20!black!30!green}\begin{quote}"}{"\end{quote}}

But that produces space beetween quotes and text which I don't want.

A: I'd be tempted to look at the csquotes package to do what you want. However, for the matter in hand I suspect you are using input such as
\begin{newquote}
  He who plants a garden plants happiness.
\end{newquote}

which means there is a space added at the end of the line. Try
\newenvironment{newquote}
 {\itshape\color{blue!20!black!30!green}\begin{quote}"\ignorespaces}
 {\unskip"\end{quote}}

or add a % to kill the end of the line in your source:
\begin{newquote}%
  He who plants a garden plants happiness.%
\end{newquote}

A: Perhaps this is overkill. Some time ago I was looking for something simular. I wrote a small script that was able to show small quotes to introduce a chapter in a book I am writing. The code:
\newcommand{\chapterquote}[2]{
  \begin{figure*}[htb]
    \centering
    \begin{tikzpicture}
      \node[text width=12cm,anchor=center] (Q) at (0,0) {\Large\textit{#1}};
      \node[gray,anchor=north east] (Ql) at (Q.north west) {\Huge\textbf{``}};
      \node[gray,anchor=north west] (Qr) at (Q.south east) {\Huge\textbf{''}};
      \node[black!80,anchor=north east] (Qa) at (Qr.north west) {\small - #2};
    \end{tikzpicture}
  \end{figure*}
}

You will need the to use tikz package. As an example:
\chapterquote{To be, or not to be}{William Shakespeare}

This produces something like:

Feel free to experiment with this custom command. You can for instance modify the color and size.


text:
Q: Unit testing - getting TypeError: You provided an invalid object where a stream was expected I'm trying to do a unit test where an effect uses a service to fetch results from an API, then fires either a success action, or an error action. I keep getting the error TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.. Not entirely sure what needs to be changed to get this working.
Including the error check test and relevant code.
Angular
Angular CLI: 7.1.4
Node: 10.5.0
OS: win32 x64
Angular: 7.1.4
... animations, cli, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.10.7
@angular-devkit/build-angular     0.10.7
@angular-devkit/build-optimizer   0.10.7
@angular-devkit/build-webpack     0.10.7
@angular-devkit/core              7.0.7
@angular-devkit/schematics        7.1.4
@angular/cdk                      7.2.0
@angular/material                 7.2.0
@ngtools/webpack                  7.0.7
@schematics/angular               7.1.4
@schematics/update                0.11.4
rxjs                              6.3.3
typescript                        3.1.6
webpack                           4.19.1

Test
describe('ResultsEffects', () => {
    let store: jasmine.SpyObj<Store<FeatureState>>;
    let ebs: jasmine.SpyObj<EBSService>;
    let snackbar: jasmine.SpyObj<SnackBarService>;

    beforeEach(() => {
        store = jasmine.createSpyObj('store', ['pipe']);
        ebs = jasmine.createSpyObj('EBSService', ['getPollResults', 'getUserHasVoted', 'getSettings']);
        snackbar = jasmine.createSpyObj('SnackBarService', ['notify']);
    });

    describe('fetchResults', () => {
        it(`should dispatch 'FetchPanelResultsError'`, () => {
            const fetchAction = new FetchPanelResults();
            const error = { statusText: 'ERROR' };
            const errorAction = new FetchPanelResultsError({ error: error.statusText });
            const values = {
                a: fetchAction,
                e: errorAction
            };
            const source = cold('a', values);
            const expected = cold('--e', values);
            const actions = new Actions(source);

            ebs.getPollResults.and.returnValue(throwError(error));

            const effects = new ResultsEffects(
                actions,
                store,
                snackbar,
                ebs
            );

            expect(
                effects.fetchResults$({
                    debounce: 20,
                    scheduler: getTestScheduler()
                })
            ).toBeObservable(expected);
        });
    });
});

Effect
@Effect()
fetchResults$ = ({ debounce = 500, scheduler = asyncScheduler } = {}) => this.actions$.pipe(
    ofType<SetPanelResults>(PanelResultsActionTypes.FETCH_PANEL_RESULTS),
    // need alternate method for this
    // withLatestFrom(this.featureState$),
    // map(([_, state]) => state.twitch.token),
    debounceTime(debounce, scheduler),
    switchMap((token) =>
        this.ebs.getPollResults(token).pipe(
            map(res => new SetPanelResults(res.data.results)),
            catchError(error => of(new FetchPanelResultsError({ error: error.statusText })))
        )
    )
)

Service
getPollResults(token: string): Observable<PollResultsFetchData> {
    const options = {
        headers: ebsHeaders(token)
    };

    return this.http.get<PollResultsFetchData>(`${this.ebsURL}/poll/results`, options);
}

Update: Added debounce to trigger the error with marbles. Still need alternative to withLatestFrom.

A: Based on the comments:
The problem is that withLatest from isn't really returning anything because you don't have a feature state. This is because you mock out the store with jasmine.createSpyObj('store', ['pipe']).
To solve this use the "real" ngrx store or use the mock store, which was implemented in NgRx 7.

A: For me that error started to happen regularly for a couple of months (Angular 7) on Live Reload during development. I was fixing it just by re-opening browser with a few seconds pause.
Today re-opening didn't help and I occasionally figured out, that re-saving one of source file (even without actually changing it) helps out and error dissapears. Re-saving triggers project in-memory build recompilation by webpack and live reload


text:
Q: A limit involving the hypergeometric function I'm trying to evaluate the following (discrete) limit:
$$ \lim_{k \rightarrow +\infty} \frac{_2 F_1(-k,ky,ky+1,-t^{1/k})}{2^k} $$
where $y>0$ and $t>0$ are some fixed real numbers. My idea was to use some transformation for the hypergeometric function which may lead to something easier to calculate, or maybe (if the first argument of $_2 F_1$ becomes a number which is not a negative integer) where the limit can be interchanged with the infinite sum via Tannery's Theorem. However, I have not been able to find any transformation which can be used to do this. Does anybody know how to evaluate this limit?


text:
Q: Mysql Now () is not workig phpmyadmin I am working on mysql with PHP,I am trying to calculate and fetch estimated time
My following query (static) is working but whenever i try to use dynamic (Use now() in mysql) then not working,
working query is
SELECT TIMESTAMPDIFF(MINUTE,'2019-10-30 16:10:00',ADDTIME(serviceStarted, SEC_TO_TIME(duration*60))) as estimatedTime FROM usr_booking WHERE bookingId='5';

i just repaced current datetime to NOW(),but following query is not working
SELECT TIMESTAMPDIFF(MINUTE,NOW(),ADDTIME(serviceStarted, SEC_TO_TIME(duration*60))) as estimatedTime FROM usr_booking WHERE bookingId='5';

Why NOW() not working in mysql ?


text:
Q: No such file or directory @ rb_sysopen for external URL / Rails 6.11 / Ruby 3 This was working fine in Rails 6 but now upgrading Rails and Ruby to 6.11 and 3, it's triggering this "classic" error. Basically, to be short, for example this external URL direct to Firefox logo, using the Rails console:
require 'open-uri'
open("https://brandemia.org/sites/default/files/inline/images/firefox_logo.jpg")

Traceback (most recent call last):
        4: from (irb):1:in `<main>'
        3: from (irb):2:in `rescue in <main>'
        2: from (irb):2:in `open'
        1: from (irb):2:in `initialize'
Errno::ENOENT (No such file or directory @ rb_sysopen - https://brandemia.org/sites/default/files/inline/images/firefox_logo.jpg)

In the app same error. Before the Rails and Ruby upgrade (with Ruby 2.5.8 and Rails 6.0.3.1) this was working perfectly fine.

A: open-uri used to (before Ruby 3.0) overwrite Kernel#open with its own version which also supports reading from external URLs rather than simply opening local files or running commands.
Mixing those two use-cases was quite dangerous and had the potential for serious vulnerabilities if the passed URL was not ensured to be safe everywhere (including third-party code using Kernel#open).
As such, this behavior to overwrite Kernel#open was deprecated in Ruby 2.7 and finally removed in Ruby 3.0. To open an external URL, you can use the following code instead:
URI.open("https://brandemia.org/sites/default/files/inline/images/firefox_logo.jpg")

A: I am not exactly sure where the change comes from, but
require 'open-uri'

uri = 'https://brandemia.org/sites/default/files/inline/images/firefox_logo.jpg'
URI.open(uri) # ! instead of open without URI

should work.
Update
open-uri did declare Kernel#open until the 3.0 release. Apparently that was deprecated in 2.7. From now on, you need to call URI.open . See the commit here: https://github.com/ruby/open-uri/commit/53862fa35887a34a8060aebf2241874240c2986a .


text:
Q: Isomorphism of Hecke algebra $H(G_1 \times G_2)$ with $H(G_1) \otimes H(G_2)$ Let $G$ be a  topological group of totally disconnected (td) type.  This means that the identity of $G$ has a fundamental system of neighborhoods consisting of open compact subgroups.  Then $G$ is locally compact, and has a Haar measure.  We give $C_c^{\infty}(G)$, the vector space of locally constant functions of compact support into $\mathbb{C}$, the structure of an (associative, not necessarily unital) algebra over $\mathbb{C}$ by setting
$$f_1 \ast f_2(g) = \int\limits_G f_1(x)f_2(x^{-1}g) dx$$
As an algebra, we write $H(G)$ instead of $C_c^{\infty}(G)$.
Let $G_1, G_2$ be groups of td type.  In the article Decompositions of Representations into Tensor Products (D. Flath, Corvallis proceedings), it is written that
$$H(G_1 \times G_2) \simeq H(G_1) \otimes_{\mathbb{C}} H(G_2)$$
I'm trying to understand why this is true.  I have tried to show that $H(G_1 \times G_2)$ satisfies the same universal property as $H(G_1) \otimes_{\mathbb{C}} H(G_2)$ in the category of algebras.  To do this, I need to define algebra homomorphisms $\phi_i: H(G_i) \rightarrow H(G_1 \times G_2)$ and show that for any algebra $A$, $\delta \mapsto (\delta \circ \phi_1, \delta \circ \phi_2)$ gives a bijection from $\textrm{Hom}_{\mathbb{C}-\textrm{alg}}(H(G_1 \times G_2),A)$ onto
$$\{ (\psi_1,\psi_2) \in \textrm{Hom}_{\mathbb{C}-\textrm{alg}}(H(G_1),A) \times \textrm{Hom}_{\mathbb{C}-\textrm{alg}}(H(G_2),A) : \psi_1(f_1), \psi_2(f_2) \textrm{ commute for all } f_i \in H(G_i)\}$$
At first, I thought that I should define $\phi_1$ by
$$\phi_1(f)(g_1,g_2) = f(g_1)$$
which is locally constant, but obviously not of compact support, in general.  Something more clever is required, but I cannot yet see what.  I would appreciate any suggestions or hints.

A: For any t.d. group $G$, $H(G)$ is spanned by the characteristic functions of the (cosets of) compact open subgroups of $G$. So it suffices to define what a map $H(G_1\times G_2)\rightarrow H(G_1)\otimes H(G_2)$ does to each characteristic function. Since we're only working with characteristic functions, we only care about characteristic functions for a basis of the topology on $G_1\times G_2$. So, in particular, we can assume wlog that our function is of the form $\chi_{U\times V}$, where $U\subset G_1$ and $V\subset G_2$ are (cosets of) compact opens. There's an obvious element of $H(G_1)\otimes H(G_2)$ to map this to, namely $\chi_U\otimes\chi_V$. It's not very hard to check that this gives an isomorphism. (What's the inverse?)


text:
Q: Get hash code for an int and a Nullable pair Currently I'm using the following class as my key for a Dictionary collection of objects that are unique by ColumnID and a nullable SubGroupID:
public class ColumnDataKey
{
    public int ColumnID { get; private set; }
    public int? SubGroupID { get; private set; }

    // ...

    public override int GetHashCode()
    {
        var hashKey = this.ColumnID + "_" +
            (this.SubGroupID.HasValue ? this.SubGroupID.Value.ToString() : "NULL");
        return hashKey.GetHashCode();
    }
}

I was thinking of somehow combining this to a 64-bit integer but I'm not sure how to deal with null SubGroupIDs. This is as far as I got, but it isn't valid as SubGroupID can be zero:
var hashKey = (long)this.ColumnID << 32 +
    (this.SubGroupID.HasValue ? this.SubGroupID.Value : 0);
return hashKey.GetHashCode();

Any ideas?

A: Strictly speaking you won't be able to combine these perfectly because logically int? has 33 bits of information (32 bits for the integer and a further bit indicating whether the value is present or not).  Your non-nullable int has a further 32 bits of information making 65 bits in total but a long only has 64 bits.
If you can safely restrict the value range of either of the ints to only 31 bits then you'd be able to pack them roughly as you're already doing.  However, you won't get any advantage over doing it that way - you might as well just calculate the hash code directly like this (with thanks to Resharper's boilerplate code generation):
public override int GetHashCode()
{
    unchecked
    {
        return (ColumnID*397) ^ (SubGroupID.HasValue ? SubGroupID.Value : 0);
    }
}

A: You seem to be thinking of GetHashCode as a unique key. It isn't. HashCodes are 32-bit integers, and are not meant to be unique, only well-distributed across the 32 bit space to minimise the probability of collision. Try this for your GetHashCode method of ColumnDataKey:
ColumnID * 397 ^ (SubGroupID.HasValue ?? SubGroupID.Value : -11111111)

The magic numbers here are 397, a prime number, which for reasons of voodoo magic is a good number to multiply by to mix up your bits (and is the number the ReSharper team picked), and -11111111, a SubGroup ID which I assume is unlikely to arise in practice.


text:
Q: Number of partitions of list If I have my_list = [0, 1, 2]. I want to figure out how many possible list partitions there are for a list of length $n$. For the above example, there would be:
[[0, 1, 2]]
[[0, 1], [2]]
[[0], [1, 2]]
[[0], [1], [2]]

A: If your list has length $n$, there are $n-1$ places to put a divider between elements.  Each choice of a set of dividers makes a different partition.  As each divider can be there or not, there are $2^{n-1}$ ways to partition the list.  In your example $n=3$ and $2^{3-1}=4$, which is the number of partitions you have found.


text:
Q: org.springframework.web.servlet.DispatcherServlet Not Found Okay this has been bugging the hell out of me and I've looked around, and every other thread says go to deployment assembly. Problem is when I go there, theres no 'maven depencies' to click on.
Like in this thread:
     org.springframework.web.servlet.DispatcherServlet not found with VMWare vFabric tc Server and maven     dispatcherservlet-not-found-with-vmware-vfabric
I get to that screen and theres no maven depencies to click.
My web.xml is:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Spring MVC Application</display-name>

<servlet>
  <servlet-name>SpringMVC</servlet-name>
  <servlet-class>
     org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>SpringMVC</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

and the -servlet.xml
   xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
 http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.tutorialspoint" />

<bean     class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
</bean>

</beans>

Any help is appreciated. I'm using STS tools/Eclipse.
heres the pom. all the jars are in the folder java resources/libraries/maven dependecies
     <project xmlns="http://maven.apache.org/POM/4.0.0"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0     http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SpringMVC</groupId>
 <artifactId>SpringMVC</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>SpringMVC</name>

<properties>
    <java.version>1.8</java.version>
</properties>

    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.2.0</version>
    </dependency>
    <dependency>
     <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20090211</version>
   </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.5</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <version>1.3.2.RELEASE</version>
        <scope>test</scope>
    </dependency>
  </dependencies>

 <build>
<sourceDirectory>src</sourceDirectory>
<resources>
  <resource>
    <directory>src</directory>
    <excludes>
      <exclude>**/*.java</exclude>
    </excludes>
  </resource>
</resources>
<plugins>
  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.5.1</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
    </configuration>
    </plugin>
    <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.0.0</version>
    </plugin>
   </plugins>
  </build>
</project>

Exception is:
ava.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:504)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:486)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:113)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1133)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5368)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

EDIT: I got it to compile but now get
WARNING: No mapping found for HTTP request with URI [/HelloWeb/] in DispatcherServlet with name 'HelloWeb

A: Try with this;
Use Servlet API 2.5 and change your web.xml file as below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

and spring-servlet.xml file to:
<?xml version="1.0" encoding="UTF-8"?>
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring-context-3.0.xsd ">

    <context:component-scan base-package="com.tutorialspoint"></context:component-scan>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- Here, the InternalResourceViewResolver class is used for the ViewResolver. -->
        <property name="prefix" value="/WEB-INF/jsp/"></property><!-- prefix can be any thing -->
        <property name="suffix" value=".jsp"></property>
    </bean>

EDIT:
You have to include maven dependency for spring 3.x as below
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>3.1.0.RELEASE</version>
</dependency>
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>3.1.0.RELEASE</version>
</dependency>

As per your query in comments; Here in this case Spring is not creating default constructor so better move on to setter injection or create a default constructor.

A: You can try to add these dependencies in your pom.xml file,Which dependency on what I hava forgotten.
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.2.6.RELEASE</version>
        </dependency>

A: Hope fully this will the best Answer:
i was facing problem i download the eclipse Noen.3 and Dirctly Creating the Maven project. Same Problem was occur that Server not start: DispatcherServlet class not Found Error:

*

*i created the simple Dynamic Web Project and convert the project into Maven project

Steps: Right Click on the project configure->Convert to maven project
For Further Details i followed below the link
http://javawebtutor.com/articles/spring/spring-mvc-hibernate-crud-example.php


text:
Q: Reverse String, Array C# code for reversing a string
I couldn't understand this part
arr[name.Length - i] = name[i - 1];

Let us have a name of 5 characters. so the value of the arr will be 4, right?
Then in the loop, the looping variable is also taking the same length, so its initial value will be 4, too.
In the first iteration, the value of arr[4 - 4] will be arr[0] and name[4 - 1] will be name[3], so the first index of arr is copied with the fourth index of name.
How is the original name stored in reversed order in arr?
static void Main(string[] args)
        {
            Console.Write("What is your name: ");
            var name = Console.ReadLine();

            var arr = new char[name.Length];

            for (var i = name.Length; i > 0; i--)
                arr[name.Length - i] = name[i - 1];

            var reversed = new string(arr);
            Console.WriteLine(reversed);
        }

A: I've reproduced the image of original code here.
using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("What is your name? ");
        string name = Console.ReadLine();
        var arr = new char[name.Length];

        for (var i = name.Length; i > 0; i--){
            arr[name.Length -1] = name[i-1];
        }
        var reversed = new string(arr);
        Console.WriteLine(reversed);

    }
}

It looks like the indexing is just off a little.  You want to take the length of the name that you've entered (the end of it) and take the characters starting from the end back to the beginning of the word.  Below I've changed a few variable names to add a little more meaning to the code.
public static void CorrectedMain()
    {
        Console.WriteLine("What is your name? ");
        string name = Console.ReadLine();

        char[] reversedLetters = new char[name.Length];
        for (var i = name.Length; i > 0; i--){
            reversedLetters[i-1] = name[name.Length -i ];
        }
        var reversed = new string(reversedLetters);
        Console.WriteLine(reversed);
    }

If you enter Thomas in the first block you get back T, if you run the code in the second block you will get back samohT.
Here is a fiddle of it.
https://dotnetfiddle.net/txwyd1

A: In answer to your question: Strings and arrays are zero-indexed. I.e. the first element is at index 0. The last is at Length - 1.
The code in your example is not very well-written. It breaks a couple of basic coding principles.

*

*Iterate forwards, unless there is a very specific need to go backwards. In this case, there is not.

*Use zero-based variables when doing any code involving strings and arrays.

The example breaks both these, and I think that's part of what it makes it hard to read, but let's try.
Looking at the iteration, if Length is 5 as you suggested then i starts at 5 and goes down to 1. When i is 5: (name.Length - i) = 0, and i - 1 = 4, so the array index 0 (the first in the array) gets the character at position 4 (which is the 5th character).
On the next iteration, i is 4: (name.Length - i) = 1, and i - 1 = 3, so the array index 1 (the second in the array) gets the character at position 3 (which is the 4th character).
And so on.
Here's a slightly nicer version of the same algorithm. Hopefully, it is a bit easier to read.
public static void Main()
{
    Console.Write("What is your name: ");
    string name = Console.ReadLine();
    int n = name.Length;
    char[] arr = new char[n];
    for (int i = 0; i < n; i++)
        arr[i] = name[n - 1 - i];
    string reversed = new String(arr);
    Console.WriteLine(reversed);
}


text:
Q: Getting a simple string response ends in a MalformedJsonException I have a simple POST request for registering a location in our backend which should respond a string with the locationId and an unique registration code which gets shown for other stuff. In Postman the request looks like: 120:B6IRDAEDZ82BCDMP9QUK which is fine.
So, I've built a retrofit request which simply does the same:
    @POST("remote_montage/set_credentials/{locationId}")
    suspend fun getRegistrationQrCode(
        @Path("locationId") locationId: Int
    ): Response<String>

Now, if I call it in my repository, it throws me this Error
com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 4 path $
W/System.err:     at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1568)
W/System.err:     at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:590)
W/System.err:     at com.google.gson.stream.JsonReader.peek(JsonReader.java:425)
W/System.err:     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:41)
W/System.err:     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
W/System.err:     at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
W/System.err:     at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
W/System.err:     at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err:     at java.lang.Thread.run(Thread.java:923)

I have no Idea what this means. What Columns? What value? What Line?

A: The GsonConverterFactory you are providing to retrofit is looking at the response and finding that it is invalid JSON.
You should use ScalarsConverterFactory which is designed to convert string responses
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
and add it to your retrofit builder
.addConverterFactory(ScalarsConverterFactory.create())


text:
Q: Update column of blob type_ MySQL I have a database with columns aes_encrypted.
For example, the column email has been aes_encrypted and is of blob type. The issue I am facing is that in this column, there are email addresses that are of upper case.
I want to update all the values in this column and set it to lowercase.
The below is just for testing on a particular record:
update lms_systest_db.member_tb
set email= aes_encrypt(lower(`email`),'$key')
where cast(aes_decrypt(fname,'$key') as char) = "John" ;

When I use the above query, it returns null.

Can anyone help?


text:
Q: CKEditor inherit font style in link tag I need to force CKEditor to apply font styling to a link tag instead of inner span tag. For example, when you write some text, add a link to this text, and change the color of of the link, the source look like this:
Click here...
I need it to be generated like this:
Click here...
Or like this:
Click here...
I can create content filter for this, but i dont want to loose what was might originally been in link tag

A: It looks I solved it...
For me it looks there is no other, but to add htmlFilter rules.
Did it like this:
CKEDITOR.on('instanceReady', function (ev) {
    ev.editor.dataProcessor.htmlFilter.addRules(
                {
                    elements:
                    {
                        $: function (element) {

                            if (element.name == 'a') {
                                if (element.children.length == 1) {
                                    if (element.children[0].name == 'span') {
                                        var innerSpan = element.children[0];
                                        if (innerSpan.attributes.style) {
                                            element.attributes.style = innerSpan.attributes.style;
                                        }
                                    }
                                }
                            }

It checks if link contains only one span children and when just copies everything in style attribute.


text:
Q: Using Jest with Angular 13 + Clarity i am currently attempting to upgrade an existing Angular app which uses VMware Clarity.
I already managed to upgrade from 8.x to 10.x following the Angular update guidelines.
However beyond that the jest configuration breaks, as the newer Clarity versions and Angular 13 use esm.
So i tried to build a minimal working example to investigate the needed configurations.
Starting from the jest-preset-angular example app at https://github.com/thymikee/jest-preset-angular/tree/main/examples/example-app-v13 , i added Clarity as described in https://github.com/vmware-clarity/ng-clarity/blob/main/docs/INSTALLATION.md#installing-clarity-angular-
The example app's test and test-esm run configurations in package.json work without problems.
But as soon as i add ClarityModule to the app.module.ts imports and run the test-esmconfiguration, the test suites for app.component.spec.ts and app.component.router.spec.ts fail with the same error:
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
From src/app/app.component.spec.ts.

          at async Promise.all (index 0)
 FAIL  src/app/app.component.spec.ts
  ● Test suite failed to run

    ENOENT: no such file or directory,
 open 'C:\Users\NAME\IdeaProjects\example-app-13_test\node_modules\@cds\core\index.jsicon\shapes\times.js'

      at Runtime.readFile (node_modules/jest-runtime/build/index.js:2552:21)
          at async Promise.all (index 3)

The error happens immediately after adding ClarityModule to the app.module.ts without adding any Clarity elements to the example app's html.
To me the ENOENT part seems rather weird, as it looks like two paths for legitimate Clarity .js-files were intersected.
I tried various different combinations of adding jest.useFakeTimers, transformIgnorePatterns and other advice i found for similar problems, but these either did nothing or led to more errors. Since i am also quite inexperienced with configuring jest, I might also have used them wrong.
Could you please give me advice what might fix the above error?
The environment i am running this in is:
Angular CLI: 13.3.6
Node: 16.14.0
Package Manager: npm 8.7.0
OS: win32 x64

The versions of the Clarity packages are:
"@cds/core": "^6.0.0",
"@clr/angular": "^13.3.1",
"@clr/ui": "^13.3.1",

A: As it's failing your test and Angular with version 13 has by default  ModuleTeardown options enabled, I assume then disabling the teardown option in your test.ts could help.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting(),
  { teardown: { destroyAfterEach: false } },
);

A: After some more debugging I found out, that Jest seems to have trouble resolving ClarityIcons while processing node_modules\@cds\core\internal-components\close-button\register.js.
So i tried adding various mappings to parts of @cds/core to the moduleNameMapper in jest-esm.config.mjs and finally succeeded in running the tests of the jest-preset-angular example app without errors. After eliminating the paths one by one it seems that adding the following mapping is sufficient for the tests to work:
"@cds/core/icon": '<rootDir>/node_modules/@cds/core/icon/index.js'


text:
Q: Issues building app store ipa w/ xcode4.2/ios5 GM with Three20 after changing settings to build for armv6 and armv7 I originally got this error when attempting to validate my app store .ipa.
iPhone/iPod Touch: application executable is missing a required architecture. At least one of the following architecture(s) must be present: armv6
I changed my build settings to set Architectures to armv6 and armv7
Here are my current build settings.
architectures: armv6; armv7
Base SDK: ios 5.0
Build Active Architecture Only: No
Valid Architectures: armv6; armv7
Deployment Target: ios 4.0
Cleaned all targets, and attempted to rebuild for archiving.  After changing architectures to explicitly add armv6, I got a bunch of the following linking errors w/ Three20.
Undefined symbols for architecture armv6:
  "_OBJC_CLASS_$_TTTableControlItem", referenced from: (35 of these total on different .o files)
I then changed all of the three20 project settings to match the settings above, cleaned all targets, and attempted to rebuild for archive, but got the same error.
I haven't got desperate enough to try reinstalling xcode & sdks
Am I missing something here?  Looked over Three20 commit logs, but I haven't noticed any changes related to ios5. I'm going to try upgrading three20 for giggles now.
Please note that my product owners are not willing to set deployment target to ios 4.3 (which also seems to resolve the issue)

A: I figured it out and wanted to post the solution just in case anyone else comes across this.
Basically, when I modified all of the referenced three20 projects the first time, I only did this for the main target.
I did this again, but this time for all targets (including unit tests), and the issue was resolved.  I was able to build w/out errors, and the outputted .ipa file was validated by iTunes Connect.
Hope this helps.


text:
Q: TextFSM nxos template I have started exploring TextFSM by google, its great for screen scraping. But I'm stuck.
Here is the template for the command: "show ip community-list"
Value TYPE (Standard|Extended)
Value CLNAME (\D+)
Value SEQ (\d+)
Value ACTION (permit|deny)
Value ASNUM (\d+)
Value TAGNUM (\d+)

Start
  ^${TYPE}\s+Community\s+List\s+${CLNAME}\s+ -> Community

Community
  ^\s+${SEQ}\s+${ACTION}\s+${ASNUM}\s+:\s+${TAGNUM}\s+ -> Record Start

Raw output looks like:
Expanded Community List ROUTES_CL1
1 permit "11111:10000"
Standard Community List ROUTES_CL2
    1 permit 11111:10000
    2 permit 22222:10000
    3 permit 33333:10000

somereason doesn't parse into key and values.

A: There are several things which need to be fixed:

*

*Extended (in your template) vs Expanded (in your output)

*CLNAME has digits in it which won't be matched by \D+

*\s+:\s+ requires spaces around the colon which the output doesn't have

*The Community List name needs to be remembered as there may be multiple action lines to which it applies. Use "Filldown".

Using this template:
Value Filldown TYPE (Standard|Extended|Expanded)
Value Filldown CLNAME (\w+)
Value SEQ (\d+)
Value ACTION (permit|deny)
Value ASNUM (\d+)
Value TAGNUM (\d+)

Start
  ^${TYPE}\s+Community\s+List\s+${CLNAME}
  ^\s*${SEQ}\s+${ACTION}\s+"?${ASNUM}:${TAGNUM}"? -> Next.Record

EOF

Will give the parsed output of:
[['Expanded', 'ROUTES_CL1', '1', 'permit', '11111', '10000'],
 ['Standard', 'ROUTES_CL2', '1', 'permit', '11111', '10000'],
 ['Standard', 'ROUTES_CL2', '2', 'permit', '22222', '10000'],
 ['Standard', 'ROUTES_CL2', '3', 'permit', '33333', '10000']]

A similar example with further explanation can be found on the textfsm wiki.


text:
Q: Certain VR games give me a D3D11 access violation error as soon as they launch First, I apologise if this is the wrong place to post this - I don't know where else to put it. If there is a more appropriate forum, I would much appreciate being told about it. I've searched the web for any other error like this, but I can't find a solution that works.
I use a Dell Visor headset on Intel UHD 620 graphics (it runs at a low framerate, but it hasn't caused any issues until now). So far, two games are giving me "d3d11.dll caused an Access Violation (0xc0000005)" at the start of their crash log:

*

*Hot Dogs, Horseshoes and Hand Grenades

*SteamVR Home

Beat Saber crashes in the same way, although I cannot find the crash logs to verify that it is the same error. This issue does not occur with other Unity games such as VRChat or Stick Fight.
As soon as the display goes from the SteamVR loading environment to the game, the HMD rapidly (once every few frames) flickers back and forth between a black screen and the first frame that was displayed by the game. The game itself inevitably crashes between 30 seconds to several minutes later. So far, I have tried these options:

*

*Reinstalling the game, the Mixed Reality Portal and SteamVR.

*Reinstalling my video drivers as well as running the DirectX runtime found on Microsoft's website.

*Fully reinstalling Windows 10.

*Adding a line to Beat Saber's launch options in a (presumably unsuccessful) attempt to force it to use D3D9.

Does anyone know of another solution?
UPDATE: It turns out that VRChat has the same issue, it just doesn't crash until I've played for a minute or two.

A: It looks to be a bug in the game engines rendering pipelines for DirectX11 on your GPU (common issue on a lot of games which are not tested on all the GPU/drivers - a reason to make sure you have the latest version)
You can:

*

*try deleting the as they mentioned in a post for some issues (https://twitter.com/beatsaber/status/998117273675227136?lang=en)

*try force launch it with OpenGL in the editor

*send the crash report to the devs and wait for a new version update (for Beat Saber - "C:\Users\\AppData\LocalLow\Hyperbolic Magnetism\Beat Saber\output_log.txt")

Hope one of this helps. Good luck!


text:
Q: What is happening in this C program with an 'empty' if without curly braces and return after new lines? So I was writing a C function but I had a hard time debugging, and eventually I found the problem was an 'empty' if statement. However, I suspect it isn't empty, as there were no curly braces, and it might just pass newlines until it finds a line of code. If this line is a return, I might think the return is now 'inside' the if. If this is the case, what would happen if the 'if' condition is false? What would the function return? In my original function, it would just return 15 or 16 (when the condition was false) instead of the expected 0 or 1. I leave here a simplified code of what I'm talking about. In this case something stranger happens. It seems it will always return 1 no matter the 'if' condition is satisfied or not. And if we uncomment the 'return 3;' the code works as expected given that the first return would be inside the 'if'. What exactly is happening here?
#include <stdio.h>
int testIf(void){
    if(0)

    return 1;
    //return 3;
}
int main(void){
    printf("%d\n", testIf());
    return 0;
}

A: Note that in the C grammar, a sequence of whitespace, such as several newlines, is equivalent to a single whitespace character.
The code (with the commented return 3) has undefined behaviour because a non-void function does not return a value for all execution paths. (There's an exception for main which you don't want to know about.)
Your compiler should have told you about this. Did you enable all warnings?

A: Then the very next line of code is considered to be its body.
So this:
if(0)

    return 1;

has the same effect with this:
if (0) {
    return 1;
}

Now as for your, method, because the condition of the if statement is hardcoded to 0, it will always evaluate to false, and the return statement will not execute.
return 3; won't execute either, since it's commented. So your method will terminate without executing any return statement, despite the fact that it's defined to return an int.
This code invokes Undefined Behavior (UB), because we cannot tell what value it will return for sure, because it lacks an effective return statement. To you it happened to be 1, today. In my laptop it may be garbage. This code is, therefore, wrong.
I strongly recommend that you enable your compiler warnings, e.g. by passing Wall and/or Wextra flags when compiling with GCC, in order to get warned for such logical errors.
Read more in Function returns value without return statement.


text:
Q: How to get current displayed page object during navigation form one page to other? i have made an application where MainPage is the opening window of my application.
Then i added two pages to the project. One is portrait and other is of landscape mode.
Now there is a controller class which will be controlling the main working of the application. Now i want that when i navigate from main page to portrait or landscape page then i will able to get the object of the current opening page which i require in controller class.
Is there any work around ?

A: There is no way to get the details of the page that was last opened automatically. You will have to do this yourself.
There are 2 common approaches to this:

*

*Use a global variable to store that last viewed page.

*Use a messaging system to inform the MainPage which page was displayed last.