text:
Q: django select only specific fields from many to many field in serializer My models:
class RequisiteItem(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    enrollable = models.ForeignKey(Enrollable, on_delete=models.CASCADE)
    created_by = models.ForeignKey(ElsUser, on_delete=models.CASCADE)
    completed_within_days = models.IntegerField()
    date_completed_by = models.DateTimeField(default=now, editable=False)

class Requisite(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name =  models.CharField(default=None, blank=True, null=True, max_length=255)
    description = models.CharField(default=None, blank=True, null=True, max_length=255)
    items = models.ManyToManyField(RequisiteItem, blank=True)
    enrolments = models.ManyToManyField(Enrollee, blank=True)
    created_by = models.ForeignKey(ElsUser, on_delete=models.CASCADE, related_name="requisites", default=None)
    timestamp = models.DateTimeField(default=now, editable=False)

    @property
    def created_by_user(self):
        return self.created_by.username

Serializer class:
class RequisiteSerializer(serializers.ModelSerializer):
    created_by = serializers.CharField(source='created_by_user')

    class Meta:
        model = Requisite
        fields = ('id', 'name', 'description', 'items', 'enrolments', 'created_by', 'timestamp')
        read_only_fields = ['id']
        depth = 1

I have enrolments ,created by,requisite items which are foreign keys and manytomany fields etc .In my list API i want only specific fileds from the foreign key to be displayed. For example in the created by field, Elsuser is a custom user inheriting from AbstractUser . I want only the username and email fields from this model and not the entire fields. Similar case for the manyto many fields . How do i implement this?

A: You can create a serializer to get only the required fields. Example:
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('') #the fields you require to display

Then change your serializer as:
class RequisiteSerializer(serializers.ModelSerializer):
    created_by = UserSerializer()

    class Meta:
        model = Requisite
        fields = ('id', 'name', 'description', 'items', 'enrolments', 'created_by', 'timestamp')
        read_only_fields = ['id']
        depth = 1


text:
Q: How to remove/reset a wing of my house without losing my wife? I recently started playing Skyrim again and I am using my save from years ago. Back then my foolish self decided to build some wings on the Falkreath house, Lakeside manor.
From reading other forums I understand I can disable Hearthfire to reset my build. I did this but my concern is that my wife Ysolda also vanished from my Solitude home when I did this.
I used console commands to place and try to marry her again but it didn't work. Is there a way to restart without losing Ysolda?

A: Yes, it is possible. Namely with the (excessive) use of the console. I didn't check whether disabling and re-enabling the DLC removes your wife, but I very much assume so, so you will probably want this approach:
First you need to type
sqv byohhousefalkreath

This should show a lot of variables with IDs and 'enabled'/'disabled'. Those belong to specific rooms and items.
You can then use the command
prid <ID>
enable|disable

depending on whether you want to enable or disable it.
It can be very exhausting to search through the text-dump for the variable you want, but I wouldn't be aware of a proper list, so this will have to do.
In case you are interested: the command prid selects the specified ID and lets you issue commands especially for that ID.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel 8 multi auth using jetstream fortify? what is the solution for multi Auth in Laravel 8 using jetstream and fority and i don't want to use PHP artisan make:auth command.

A: You have to create multiple Guard linked with multiple table;
Default Guard is linked to user table so if you want to make admin you have to create admin guard linked to admin table!


text:
Q: JQGrid Edit form setting focus on an element Hi I have a jqGrid setup and I am trying to set the focus on one of my input boxes after the Edit Form loads. My code is as follows:
ondblClickRow: function (rowid) {
    $(this).jqGrid('editGridRow', rowid, { left: '250', afterShowForm: function (formid) {
          console.log('Bong');
           $('elementID').focus(); }
});

The "Bong" is displayed, the event triggers, but the focus command doesn't seem to work, and my google-fu doesn't seem to be coming up with an answer for why this wouldn't be working.
Thank you in advance.
EDIT:
  My code with a $('#elementID').focus(); still did not work so I implemented Oleg's delay suggestion below and it started to work the way I wanted it to.

A: It seems to me that you have just typing error in your code: you should use
$('#elementID').focus();

instead of
$('elementID').focus();

In some situations it's needed to place the code in setTimeout(function() {/*here*/}, 50); block, but I think it's unneeded in your case.


text:
Q: Django unique_together but only for filtering Is there a way to filter a django model, where two fields are unique together?
For example, I have this model:
class Sequence(models.Model):
    id       = models.CharField(max_length=25, primary_key=True)
    taxonomy = models.CharField(max_length=25)
    sequence = models.TextField()

There can be multiple Sequence objects that have the same the sequence and taxonomy. I want to have a unique subset of Sequence objects where no taxonomy has multiple sequences that are identical, and only pick one object if there are multiple.
So far I have tried iterating over the results:
def unique(query_set):
    used_taxa = {}
    for seq in query_set.all():
        if not seq.sequence in used_taxa:
            used_taxa[seq.sequence] = [seq.taxonomy]
            yield seq
        elif seq.sequence in used_taxa and not seq.taxonomy in used_taxa[seq.sequence]:
            used_taxa[seq.sequence].append(seq.taxonomy)
            yield seq
        else:
            pass

This gets me the correct result, but I need the overall count becuase I am doing pagination later on.
This also gets me closer, but I don't have access to the full Sequence object after values has been called:
result = Sequence.objects.values("sequence", "taxonomy").annotate(id=Max("id"))

If someone can point me in the right direction, I would really appreciate it! Thanks.

A: You've tagged your question with MySQL so I guess you're using that database. Which is unfortunate in this case, as the Django ORM can do what you want but only on PostgreSQL.
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#distinct
On a Postgres db you could do:
Sequence.objects.order_by('taxonomy', 'sequence').distinct('taxonomy', 'sequence')


text:
Q: Robolectric accessing database throws an error I have a test that creates an activity which attempts to get some data from the database. This fails with SQLiteException
17:40:40.528 [DEBUG] [TestEventLogger]     android.database.sqlite.SQLiteException: Cannot open SQLite connection, base error code: 14
17:40:40.528 [DEBUG] [TestEventLogger]      at org.robolectric.shadows.ShadowSQLiteConnection.rethrow(ShadowSQLiteConnection.java:53)
17:40:40.528 [DEBUG] [TestEventLogger]      at org.robolectric.shadows.ShadowSQLiteConnection.access$600(ShadowSQLiteConnection.java:30)
17:40:40.529 [DEBUG] [TestEventLogger]      at org.robolectric.shadows.ShadowSQLiteConnection$Connections.execute(ShadowSQLiteConnection.java:443)
17:40:40.529 [DEBUG] [TestEventLogger]      at org.robolectric.shadows.ShadowSQLiteConnection$Connections.open(ShadowSQLiteConnection.java:345)
17:40:40.529 [DEBUG] [TestEventLogger]      at org.robolectric.shadows.ShadowSQLiteConnection.nativeOpen(ShadowSQLiteConnection.java:58)
17:40:40.529 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteConnection.nativeOpen(SQLiteConnection.java)
17:40:40.529 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
17:40:40.529 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
17:40:40.529 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
17:40:40.530 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
17:40:40.530 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
17:40:40.530 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
17:40:40.530 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
17:40:40.530 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
17:40:40.530 [DEBUG] [TestEventLogger]      at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:1142)
17:40:40.530 [DEBUG] [TestEventLogger]      at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:267)
17:40:40.531 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
17:40:40.531 [DEBUG] [TestEventLogger]      at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)

This used to work fine before I moved my database class to a singleton model. Any suggestions how this should be handled with Robolectric? I couldn't find any documentation or samples on this.
EDIT:
Running Robolectric 3.0 RC-2
Robolectric is driving my activity which attempts to do some work with the database.
In my app DB class, removing the check for instance == null from below 'fixes' the issue (i.e. there's no issue with Robolectric running the test if MySQLiteOpenHelper is recreated every time)
public static synchronized MyDataManager getInstance(Context context){
    if (sInstance == null) {
        sInstance = new MyDataManager(context.getApplicationContext());
    }
    return sInstance;
}

private MyDataManager(Context context) {
    dbHelper = new MySQLiteOpenHelper(context);
}

MySQLiteOpenHelper is a simple extension of SQLiteOpenHelper.
The failure is happening on (again, this is inside by db class):
        database = dbHelper.getWritableDatabase();

Obviously I don't really want to recreate a connection every time in my App - and I think nobody would want that? Which makes me think there should be a way to do this properly in Robolectric and I'm just missing a trick here?
EDIT:
Also, the test runs successfully in isolation, which makes me think it's something to do with Robolectric moving between the test cases and reusing the database connection?
Both tests don't do ANYTHING specific to database or related to any of the DB classes. First test starts a fragment which will access the database to write some data. Second test is failing on attempt to open the db as above.

A: Reset all singleton instances between each test or you will get side effects like yours.
@After
public void finishComponentTesting() {
    resetSingleton(YourSQLiteOpenHelper.class, "sInstance");
}

private void resetSingleton(Class clazz, String fieldName) {
    Field instance;
    try {
        instance = clazz.getDeclaredField(fieldName);
        instance.setAccessible(true);
        instance.set(null, null);
    } catch (Exception e) {
        throw new RuntimeException();
    }
}

A: IMO you have to remove/replace database usage/singlethons with dependency injection and mock them in tests. In this case you don't need to instantiate things that are not used in your code/tests.
Sounds like dummy suggestion and something that requires more effort than "just to fix current state". But my experience it is worth to do and it will lead for clear design and testing for entire application.
As for me it is comparable to (sorry again for obvious examples):

*

*Debug vs Unit testing

*Fixing OEM with preventing memory leaks


text:
Q: Multilayer Perceptron (MLP) Keras tensorflow model I run in to an issue after I fit my model  for training. Below is my code
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn import preprocessing
from tensorflow import keras
from keras.models import Sequential
from tensorflow.keras import layers

bitcoin_data = pd.read_csv("BitcoinHeistData.csv")
#first we'll need to normalize the dataset
normal = bitcoin_data
normalized_bitcoin_data=preprocessing.normalize(normal)

# make it into a dataframe
columns = bitcoin_data.columns
normalized_bitcoin_df = pd.DataFrame(normalized_bitcoin_data, columns=columns)
# start out splitting the data
xtrain = normalized_bitcoin_df
labels = normalized_bitcoin_df.drop('label', axis=1)

x, x_validate, y, y_validate = train_test_split(xtrain, labels, test_size=0.2, train_size=0.8)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.12, train_size=0.88)

*#This is my output for my variables so far. Exactly how I want to split it 70% - 20% - 10%
#X HERE SHAPE
#(838860, 10)
#x_test HERE SHAPE
#(100664, 10)
#x_validate HERE SHAPE
#(209715, 10)
#X x_train SHAPE
#(738196, 10)
#y HERE SHAPE
#(838860, 9)
#y_test HERE SHAPE
#(100664, 9)
#X y_validate SHAPE
#(209715, 9)
#X y_train SHAPE
#(738196, 9)*

model = Sequential()
     model.add(layers.Dense(64, activation='relu', kernel_initializer='glorot_normal',
     bias_initializer='zeros', input_shape=(128,)))
     model.add(layers.BatchNormalization())
     model.add(layers.Dense(32, activation='relu', kernel_initializer='glorot_normal',
     bias_initializer='zeros'))
     model.add(layers.BatchNormalization())
     model.add(layers.Dense(32, activation='relu', kernel_initializer='glorot_normal',
     bias_initializer='zeros'))
     model.add(layers.Dense(32, activation='relu', kernel_initializer='glorot_normal',
     bias_initializer='zeros'))
     model.add(layers.Dropout(0.4))
     model.add(layers.Dense(10, activation='softmax'))
     optimizer = keras.optimizers.RMSprop(lr=0.0005, rho=0)
     model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])

     model.fit(x_train, y_train, epochs=20, batch_size=128)

#I get this error ValueError when i run my model.fit for x_train and y_train. I dont understand how
to get around it though. Any help would be apricated
#ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of
input      shape to have value 128 but received input with shape [None, 10]

A: Number of neuron in input layer(input_shape property) must be equal to number of column of x_train data set(x_train.shape[1]). Also number of neuron in output layer must be equal to number of column of y_train(y_train.shape[1]).


text:
Q: I want to close the firefox browser which is opened through backend C# process I want to close the firefox browser which is opened through backend C# process. All other browsers support window.close(); opened through C# process. But firefox does not support. My code in C# Process.Start("firefox", "http://www.google.com"); After opening the browser i am calling this js code. window.close(); all other browsers working perfectly. but FF. if you can help me on this.

A: According to this documentation, script should not be able to close a window that it did not originally open:

The Window.close() method closes the current window, or the window on which it was called.
This method is only allowed to be called for windows that were opened by a script using the window.open() method. If the window was not opened by a script, an error similar to this one appears in the console: Scripts may not close windows that were not opened by script.

So, while it works in IE and Chrome today, don't count on it working forever.
If you want to close the window programmatically, it seems like your best option may be to close the process from your c# code, e.g.
var p = Process.Start("firefox", "http://www.google.com");
System.Threading.Thread.Sleep(10000); //Wait 10 seconds
p.CloseMainWindow();


text:
Q: What would happen if you open a bottle of fizzy drink in a weightless environment? On Earth, pouring a fizzy drink into a glass or opening a bottle, you see the gas start to condense out into bubbles which rise upwards.
You can't pour a Coke into a glass on the ISS but you could (I assume) unscrew a bottle and remove the lid if you're careful.
What would happen in terms of bubbles? And by extension when you see this phenomenon on Earth, why do the bubbles go straight up - due to gravity directly or simply because the lower pressure is (due to gravity) at the top of the bottle?

A: The liquid would float around in globs, and the bubbles would fizz out indiscriminately from all the surfaces of the globs.
Water molecules are attracted to each other, but the carbon dioxide isn't really attracted to the water. The bubbles would therefore escape from the surface by diffusion, so it would take longer than if there were gravity.

A: The volume of the fizzy drink would increase and squirt out the opening of the bottle.
Small pockets of gas would be expanding inside the liquid. Normally they'd expand outward and the liquid would stick together and the bubbles would pop out an edge (probably taking some globs of liquid along). But in the bottle all the expansion will just move a liquid with still expanding gas bubbles out the top.
Initially it may not look all that different than an overflowing pop bottle in gravity.

A: Apparently, according to this guy, the bubbles in the fizzy drink will remain in suspension inside the liquid, as there is no top direction for them to go. Remember in a no gravity environment there is nothing to discriminate between left and right or top and bottom.
Also, NASA has the same thing to say about the matter.


text:
Q: JPA named query gets turned into incorrect SQL I am building a JSF application and want to list some entities on a page. I three entities: Panel, PanelDefinition and Protein. One page is a kind of details page for one Protein entity. One thing I want to do on that details page is to list all Panel entities for that Protein.
To do this I use a method in my PanelController class (JSF managed session scoped bean), which use my PanelService (stateless EJB) to call the named query Panel.byProtein. When I do this I get the error:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.panel_id) AND (t0.target = 5)) AND (t0.panel = t1.panel_id))' at line 1
Error Code: 1064
Call: SELECT t1.panel_id, t1.comment, t1.insert_date, t1.name, t1.panel_version, t1.status, t1.inserted_by, t1.previous_version FROM panel_definition t0, panel t1 WHERE (((t0.panel = t1.panel_id.t1.panel_id) AND (t0.target = ?)) AND (t0.panel = t1.panel_id))
    bind => [1 parameter bound]
Query: ReadAllQuery(name="Panel.byProtein" referenceClass=Panel sql="SELECT t1.panel_id, t1.comment, t1.insert_date, t1.name, t1.panel_version, t1.status, t1.inserted_by, t1.previous_version FROM panel_definition t0, panel t1 WHERE (((t0.panel = t1.panel_id.t1.panel_id) AND (t0.target = ?)) AND (t0.panel = t1.panel_id))")
    at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:679)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
    at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1995)
    at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:570)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:299)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQueryMechanism.java:694)
    at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRowsFromTable(ExpressionQueryMechanism.java:2714)
    at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRows(ExpressionQueryMechanism.java:2667)
    at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:477)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1155)
    at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1114)
    at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:402)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1202)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2894)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1797)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1779)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1744)
    at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)

And t0.panel = t1.panel_id.t1.panel_id does indeed not look proper. How and why do I get incorrect sql?
Here are a simplified version of my entity classes:
@Entity
@NamedQueries({
    @NamedQuery(name = "Panel.findAll", query = "SELECT p FROM Panel p"),
    @NamedQuery(name = "Panel.byProtein", query = "SELECT p FROM Panel p JOIN p.panelDefinition pd WHERE pd.pdId = p.panId AND pd.protein.ID = :pid"),
})
public Class Panel {
    @Id
    private Integer panId;
    @OneToMany(mappedBy = "panel")
    private List<PanelDefinition> panelDefinition;
    //More attributes + getters and setter
}

@Entity
public Class PanelDefinition {
    @Id
    private Integer pdId;
    @JoinColumn(name = "protein", referencedColumnName = "ID")
    @ManyToOne
    private Protein protein;
    @JoinColumn(name = "panel", referencedColumnName = "panId")
    @ManyToOne
    private Panel panel;
    //More attributes + getters and setter
}

@Entity
public Class Protein {
    @Id
    private Integer ID;
    //More attributes + getters and setter
}

A: Apparently I needed another JOIN in the query. This change fixed it:
Original:
SELECT p FROM Panel p JOIN p.panelDefinition pd
WHERE pd.pdId = p.panId AND pd.protein.ID = :pid

Updated query:
SELECT p FROM Panel p JOIN p.panelDefinition pd
JOIN pd.protein t
WHERE p.panId = pd.panel.panId AND t.ID = :id


text:
Q: sqlite, mono, C# cross platform I am using sqlite in my C# project. MoMA complains about the DLLs and i am unsure what to do on the mac/linux side. What are things i generally need to do when porting external DLLs?

A: You might want to look at the C# reimplementation of SQLite on googlecode.  This started life as a line-by-line port of the C++ SQLite but after lots of improvements now outperforms the original for many types of operation.

A: You could use the SQLite assembly that's shipped with Mono - it's derived from the one you are probably using now.
See http://mono-project.com/SQLite for more details

A: PHXSoftware's System.Data.Sqlite runs on Mono.


text:
Q: Transfer data from one workbook to another Im currently working on a code that hopefully does this set of things:

*

*From the database file, ask me to select and open a source file

*Go to Source Sheet, and copy all data on column A, B, D, E, and F from the source file

*Go back to the Database file(Data Sheet) and locate the next empty row on column A, B, D, E, and F.

*Then paste all data column by column

*Close the source file and not save

The current code that I have satisfies requirement 1 & 5 only. Here is my current code:
Option Explicit

    Sub Copy_data()
    Dim databasewkb As Workbook, sourcewkb As Workbook
    Dim Ret1, Ret2
    Dim srcws As Worksheet ' Variable for source workbook worksheets
    Dim databasews As Worksheet ' Variable for portal workbook worksheets
    Dim srcLR As Long ' last row of the source worksheet
    Set databasewkb = ActiveWorkbook

    '~~> Get the first File
    Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
    , "Please select the source file file")
    If Ret1 = False Then
        ' Tell the user why the code has been terminated
        MsgBox ("Sorry, unable to proceed without a file.")
        Exit Sub
    End If

    ' Open the Source file
    Set sourcewkb = Workbooks.Open(Ret1)

    ' Set the source worksheet
    Set srcws = sourcewkb.Sheets("Source Sheet")

    ' Set the first destination worksheet
    Set databasews = databasewkb.Sheets("Data Sheet")

With srcws
    ' Find the last row of data in the Source worksheet
    srcLR = .Cells(Rows.Count, 1).End(xlUp).Row

    'im not sure what to put here

    ' close the source workbook, don't save any changes
    sourcewkb.Close SaveChanges:=False

    ' Clear the objects
    Set srcws = Nothing
    Set sourcewkb = Nothing
    Set databasews = Nothing
    Set databasewkb = Nothing
    End Sub

A:
'im not sure what to put here

    srcLR = .Cells(.Rows.Count, 1).End(xlUp).Row
    ' Beware here, use ".Rows.Count" instead of "Rows.Count", because
    ' I suspect you are opening an old workbook in compatibility mode

    Dim srcRange as Range, destRange as Range

    Set srcRange = .Range("A1:B" & srcLR)
    Set destRange = databasews.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
    srcRange.Copy destRange

    Set srcRange = .Range("D1:F" & srcLR)
    Set destRange = destRange.Offset(0, 3)
    srcRange.Copy destRange

End With


text:
Q: Spark label truncating issue - spark label text becomes truncated if there is plus sign character in it Why does spark label text becomes truncated if there is plus sign in it. Here is the code of a simple app. The issue is reproduced both in Adobe Flex SDK 4.6 and in Apache Flex SDK 4.12:
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
        >
    <s:layout>
        <s:VerticalLayout/>
    </s:layout>

    <s:VGroup width="350">
        <s:Button id="button" width="100%"
                   content="jkqUP+e8Cu62ALgLjkqUPea8Cu62ALgLjkqUPea.aa8Cu62ALgLjkqUPe8Cu62ALgLjkqUPea8C"/>
        <s:Label maxDisplayedLines="1" text="jkqUP+e8Cu62ALgLjkqUPea8Cu62ALgLjkqUPea.aa8Cu62ALgLjkqUPe8Cu62ALgLjkqUPea8C" width="100%" />
    </s:VGroup>
</s:Application>

The label text becomes truncated both in the Button label and in Label after "+" character though there is enough space.

A: Set the style lineBreak="explicit" for spark label which fix the issue. By default it is "toFit". For button add a style tag or set lineBreak in skin if you have one.
<fx:Style>
        @namespace s "library://ns.adobe.com/flex/spark";
        @namespace mx "library://ns.adobe.com/flex/mx";
        s|Button s|Label
        {
            lineBreak:explicit;
        }
    </fx:Style>

<s:Label lineBreak="explicit" />


text:
Q: How to make dynamic scale for bar chart when chart inside a cell. SSRS 2012 The goal was to align Chart with Data Table (Excel Style)
This is my chart in design view:

And this is in Preview mode:

As you can see series perfectly aligned with each month in a table.
But is any way to make a scale on a left side in a left cell? And possible dynamic?
Something like that:

A: Oleg, here is what I would do.
First, insert another column on the left side of the table. Merge this column with the columns containing total month budget and total month actual.
Next, drag out the left chart and place it below the table. Merge the column where the chart was with the column on the left of that chart. Now drag that table back in and add vertical axis values. You can adjust the size of the column on the left of the chart to get the size right. This won't affect your columns below because they are merged in that row.
You will want to set the size of your vertical axis to be consistent so all of the charts right of the left chart will line up with the values in that axis. Should accomplish what you're looking for!


text:
Q: Aria on fixed element I'm trying to make an app that renders in a webkit better to use with screen readers. It's mostly working well the only issue is the menu bar that appears at the bottom of the screen is not working correctly. When the app is scrolled to the top it works fine. BUt when it's scrolled down the box that appears around the button when tapped appears above the button. The box moves more the more the page is scrolled and double tapping does not activate it. Is there a way to tell the screen reader the element is in a fixed position?
Thanks for the help!


text:
Q: Angular services "lifecycle" in lazy loading We know that Angular services do not have lifecycles as components have. My question is about 'destructing' a service when it has done.
In my application, there is a lazy module Module A which provides a service Service A when it is loaded (only Module A needs Service A).
When done, I call another lazy module and Service A is no longer necessary, but it is kept by the Angular injector. Being more specific, Angular injector tree has now a single root injector and a child injector for Module A.
My question: as the service is kept running, should I create a function to destroy it (unsubscribe, clean arrays etc) and call it when Module A is being closed or there is another way to destroy it?
I've searched Angular Injector Class but it doesn't have some delete method to delete specific services.

A: If you register the service in a component, such as the primary component of Module A instead of in Module A directly, then the service will be destroyed when the component is destroyed.


text:
Q: Quotes inside of my PHP variable (wordpress shortcode) aren't returned I have spent hours on this, and I can't seem to find a way to fix my problem so I thought that an outside look would really help.
I have programmed a WordPress shortcode to better manage lazy loaded pictures on my portfolio. I am using a placeholder URL-encoded SVG to prevent content reflow.
The svg is stored in a variable and contains quotes. The SVG is returned with the rest of the shortcode. However, the quotes surrounding the xmlns element of the SVG aren't returned.
Here is my code:

function img_shortcode( $atts , $content = null ) {

    // Attributes
    $atts = shortcode_atts(
        array(
            'caption' => 'no',
            'src' => '',
            'name' => 'media',
            'captionclass' => 'caption',
            'width' => '0',
            'height' => '0',
        ),
        $atts,
        'img'
    );

    $urlsvg = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ". $atts['width'] ." ". $atts['height'] ."'%3E%3C/svg%3E";

    if($atts['caption'] == 'yes')
    {
        return '

'.$content.'

';
    }
    else{
        return '';
    }

}
add_shortcode( 'img', 'img_shortcode' );

And here is what is returned:

Caption text.

I am by no means a php expert, in fact I am certain that I am missing something that will be most obvious to everyone else but I can't seem to be able to see what it is that prevents my quotes from being returned.
I have tried to replace single quotes with double quotes and the outcome was the same.
Thanks,

A: Try to use backslashes around your quotes:
Instead of
$urlsvg = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ". $atts['width'] ." ". $atts['height'] ."'%3E%3C/svg%3E";

Try
$urlsvg = "data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox='0 0 ". $atts['width'] ." ". $atts['height'] ."'%3E%3C/svg%3E";

The backslashes should hopefully escape any -problems.

A: Not sure why your single quotes are not returned in your string for xmlns='..', but then for viewBox='..' they are. Your code seems to be fine.
What you can try is something called escaping, where you use the backslash (\) to remove any special meaning a character has. So for example, in your code you can  write
$urlsvg = "data:image/svg+xml,%3Csvg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 ". $atts['width'] ." ". $atts['height'] ."\"%3E%3C/svg%3E"; which only uses double quotes.
Edit: what caused this problem was the so called 'HTML Minifier', that removed the " or ' characters.


text:
Q: Is there any way to send a message automatically in converse.js Is there any way to send a message automatically, I found a sendMessage trigger but it doesn't work, maybe I am doing wrong something
export const msgUser = (viewerChannelCredentials: any) => {
  const {username, channel} = viewerChannelCredentials;
  window.converse.plugins.add('msg-user', {
    dependencies: [],
    initialize: async function () {
      const _converse = this._converse;

      return _converse.api.trigger('sendMessage', {
        chatbox: _converse.ChatBox | _converse.ChatRoom,
        message: 'abc',
      });
    },
  });
};

Another solution found that also doesn't work, it throws an error which Cannot read properties of undefined (reading '$msg')
export const msgUser = (viewerChannelCredentials: any) => {
  const {username, channel} = viewerChannelCredentials;
  window.converse.plugins.add('msg-user', {
    dependencies: [],
    initialize: async function () {
      const _converse = this._converse;

      var msg = _converse.env.$msg({
        from: 'juliet@example.com/balcony',
        to: 'romeo@example.net',
        type: 'chat',
      });
      _converse.send(msg);
    },
  });
};

A: Calling api.trigger('sendMessage' only fires an event with the name "sendMessage", it doesn't actually send a message.
To send a message, you can call the sendMessage method on a ChatBox.
For example:
const chat = await api.chats.get(jid)
chat.sendMessage({ body: 'Hello world' });


text:
Q: Bigquery year-over-year join I built a query with a join to layer on yoy data. As soon as I add more dimensions the yoy total doesn't match anymore. Am I applying the using function properly?
When I added browser or device the total is different
   (SELECT

 date,
 py_date,
 browser,
 device,
 sum(ga_sessions) as visit,

 FROM (SELECT

 device.browser as browser,
 device.deviceCategory as device,
 PARSE_DATE("%Y%m%d", date) as date,
 DATE_SUB(PARSE_DATE("%Y%m%d", date), INTERVAL 364 DAY) as py_date,
 totals.visits as ga_sessions,

 FROM `xx.ga_sessions_20210824`
GROUP BY date, py_date, browser, device
),

 PREV_YEAR as (SELECT

 py_date,
 browser,
 device,
 sum(py_ga_sessions) as py_visit,

 FROM ( SELECT
 PARSE_DATE("%Y%m%d", date) as py_date,
 totals.visits as py_ga_sessions,
 device.browser as browser,
 device.deviceCategory as device

 FROM `xx.ga_sessions_20200824`
 GROUP BY py_date, browser, device
),

DATAPULL as (SELECT *
FROM CURRENT_PERIOD LEFT OUTER JOIN PREV_YEAR USING(py_date, browser, device) ORDER BY date DESC
)

SELECT * FROM DATAPULL```


text:
Q: Cannot understand this JAVA statement in AOSP IPackageManager.java While tracing the install procedure on AOSP I came across these lines and I am unable to understand what they do. (I am not a complete novice in java programming, neither am I a fully professional java developer)
@Override public void installPackage(java.lang.String originPath, android.content.pm.IPackageInstallObserver2 observer, int flags, java.lang.String installerPackageName, android.content.pm.VerificationParams verificationParams, java.lang.String packageAbiOverride) throws     android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(originPath);
_data.writeStrongBinder((((observer!=null))?(observer.asBinder()):(null)));
_data.writeInt(flags);
_data.writeString(installerPackageName);
if ((verificationParams!=null)) {
_data.writeInt(1);
verificationParams.writeToParcel(_data, 0);
}
else {
_data.writeInt(0);
}
_data.writeString(packageAbiOverride);
mRemote.transact(Stub.TRANSACTION_installPackage, _data, _reply, 0);
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}

In this code above what do the lines inside the try block work? Especially what does the line _data.writeStrongBinder... do? Any pointers to help understand this code is appreciated!

A: _data is an Parcel object. You can look at the API documentation here
ps.: You could install Codota. I actually can click at your code and see the documentation. So you kinda answered your own question already ;)


text:
Q: How to update in BD only the fields filled in my struct? I have a struct to get the data from the user and update the info in the database. However, if the user lets a field in a blank, the correspondent field into DB will be blank. I don't want that, I would like to edit only the fields that the user informed.
My model:
type Business struct {
    Id           uint64 `json:"id,omitempty"`
    Company_name string `json:"company_name,omitempty"`
    Trading_name string `json:"trading_name,omitempty"`
    Facebook     string `json:"facebook,omitempty"`
    Instagram    string `json:"instagram,omitempty"`
    Tel          string `json:"tel,omitempty"`
    User_id      uint64 `json:"user_id,omitempty"`
}

My controller:
func EditBusinessInfo(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    businessIDParams, err := strconv.ParseUint(params["businessID"], 10, 64)
    if err != nil {
        returns.ERROR(w, http.StatusBadRequest, err)
        return
    }

    userIDInToken, err := auth.ExtractUserID(r)
    if err != nil {
        returns.ERROR(w, http.StatusInternalServerError, err)
        return
    }

    db, err := db.ConnectToDB()
    if err != nil {
        returns.ERROR(w, http.StatusInternalServerError, err)
        return
    }
    defer db.Close()

    repository := repositories.NewUsersRepository(db)
    businessInBD, err := repository.GetBusiness(businessIDParams)
    if err != nil {
        returns.ERROR(w, http.StatusInternalServerError, err)
        return
    }

    if userIDInToken != businessInBD.User_id {
        returns.ERROR(w, http.StatusUnauthorized, errors.New("você não pode editar a empresa de outra pessoa"))
        return
    }

    if businessIDParams != businessInBD.Id {
        returns.ERROR(w, http.StatusForbidden, errors.New("essa empresa não peertence a você"))
        return
    }

    bodyRequest, err := ioutil.ReadAll(r.Body)
    if err != nil {
        returns.ERROR(w, http.StatusBadRequest, err)
        return
    }

    var business models.Business

    if err := json.Unmarshal(bodyRequest, &business); err != nil {
        returns.ERROR(w, http.StatusUnprocessableEntity, err)
        return
    }

    if err := repository.EditBusinessInfo(userIDInToken, business); err != nil {
        returns.ERROR(w, http.StatusInternalServerError, err)
        return
    }

    returns.JSON_RESPONSE(w, http.StatusOK, nil)

}

A: An int and string both have default values, so if you don't assign a value to them they will be populated with their default value (0 or ""). Since they will always have a value assigned, the omitempty tag will never come into play.
A common solution to this issue is to make your struct fields be pointers, if a pointer isn't set then it is nil. the nil value will then trigger the json marshaler to recognize the omitempty tag. And when you insert to you DB those values will be null/nil as well.
You should evaluate which fields need a value and which can be allowed to be empty in case your DB has integrity constraints. You will also have to add nil checks in your code when working with data.


text:
Q: python - returning nan when trying to predict with Keras For a school project, I'm trying to predict data using the keras framework, but it's returning 'nan' loss and values when I try to get predicted data.
Source code :
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=5)

# create model
model = Sequential()
model.add(Dense(950, input_shape=(425,), activation='relu'))
model.add(Dense(425, activation='relu'))
model.add(Dense(200, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# Compile model
sgd = optimizers.SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer='sgd')

# Fit the model
model.fit(X_train, y_train, epochs=20, batch_size=1, verbose=1)

#evaluate the model
y_pred = model.predict(X_test)

score = model.evaluate(X_test, y_test,verbose=1)
print(score)

# calculate predictions
predictions = model.predict(X_pred)

Data :
X_train and X_test are (panda)dataframes of 5000 rows(nber of samples) * 425 columns (number of dimensions).
y_train and y_test look like :
array([ 1.17899644,  1.46080518,  0.9662137 , ...,  2.40157461,
        0.53870386,  1.3192718 ])

Can you help me with that ?
Thank you for you help!

A: Usually, this means that something converges to infinity. As @desertnaut pointed out in the comment, reducing the learning rate might help.
But the root of the issue is your input data. What do these 425 data points mean? Are they from different sources, different features, different parameters? Finding outliners or normalizing the data, could help.
Your code looks fine otherwise.

A: *

*Make sure your target output is in range (0, 1) as you have sigmoid in the last layer.

*sigmoid has an output between zero and one so if the target output is not in this range then (a) change the activation function or (b) normalize outputs in the required range.

*Make sure the purpose of this model is the regression.

*After considering the above three points, play around with learning rate (decrease) and the optimiser (replace with any other).

A: Try changing your optimizer to 'Adam' instead of SGD

A: You initialized your SGD optimizer in variable sgd but you're not using it in compile


text:
Q: PyInstaller "failed to execute script" Error I'm trying to make an exe file with PyInstaller however I'm unable to do so. The file is built and deposited in the dist folder, however when I try to run it, the the error "Failed to execute script {name}" pops up.
Here is the .spec file that I'm using:
# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(['simulator.pyw'],
             pathex=['C:\\Simulator'],
             binaries=[],
             datas=[('bin/**/*.kv', './bin/ui'), ('bin/**/*.xml', './bin/ui')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=True,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='simulator',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=False , icon='bin\\ui\\icon.ico')
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               upx_exclude=[],
               name='simulator')

and this is the output from the console:
LOG
What could be the problem?

A: You can check the full traceback by starting the script via command prompt.
This can be done by pressing WIN + R and writting cmd then changing the directory with cd command until you reach the folder, and then use .\<softwarename>.exe to run.
For example:
> cd C:\softwares\test
> pwd
C:\softwares\test
> .\test.exe

From experience, this probably is caused by a ModuleNotFoundError. If that's the problem you can add the module name to the hiddenimports list at the spec.
i.e.: hiddenimports=['pyodbc'],

A: So you are using Kivy and it logs several errors:
picamera - ImportError: No module named picamera
  File "c:\python27\lib\site-packages\kivy\core\__init__.py", line 63, in core_select_lib
    fromlist=[modulename], level=0)
  File "c:\python27\lib\site-packages\kivy\core\camera\camera_picamera.py", line 18, in <module>
    from picamera import PiCamera

gi - ImportError: No module named gi.repository
  File "c:\python27\lib\site-packages\kivy\core\__init__.py", line 63, in core_select_lib
    fromlist=[modulename], level=0)
  File "c:\python27\lib\site-packages\kivy\core\camera\camera_gi.py", line 10, in <module>
    from gi.repository import Gst

opencv - ImportError: No module named cv2
  File "c:\python27\lib\site-packages\kivy\core\__init__.py", line 63, in core_select_lib
    fromlist=[modulename], level=0)
  File "c:\python27\lib\site-packages\kivy\core\camera\camera_opencv.py", line 48, in <module>
    import cv2

Did you declare kivy in a requirements.txt file ?
There is also
15333 INFO: Processing pre-safe import module hook   win32com
Traceback (most recent call last):
  File "<string>", line 2, in <module>
ImportError: No module named win32com
15411 INFO: Processing pre-safe import module hook   win32com
Traceback (most recent call last):
  File "<string>", line 2, in <module>
ImportError: No module named win32com

which says a library is missing (see ImportError: No module named win32com.client).
So, how did you declare the dependencies ? We'd need to see your project structure.

A: The problems seemed to be indeed in Kivy (https://kivy.org/doc/stable/guide/packaging-windows.html#alternate-installations). I modified the .spec file and the application was built successfully.
# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(['simulator.pyw'],
             pathex=['C:\\Python27\\Scripts\\Simulator'],
             binaries=[],
             datas=[('./bin/ui/dynamic_classes.kv', './bin/ui/'), ('./bin/ui/main_layout.kv', './bin/ui/'), ('./bin/ui/text.xml', './bin/ui/'), ('./bin/ui/treatment_adaptive.kv', './bin/ui/'), ('./bin/ui/treatment_classic.kv', './bin/ui/'), ('./bin/ui/treatment_user.kv', './bin/ui/'), ('./bin/ui/icon.ico', './bin/ui/')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=True,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='simulator',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          clean=True,
          console=False, icon='bin\\ui\\icon.ico')
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               Tree('C:\\Python27\\share\\sdl2\\bin'),
               Tree('C:\\Python27\\share\\glew\\bin'),
               strip=False,
               upx=True,
               upx_exclude=[],
               name='simulator')


text:
Q: How to tell IntelliJ not to warn me about request attributes can not be being resolved in jsp files? This is what I am talking about:

Well IntelliJ is complaining that it can not resolve username or email. Is there anyway to tell IntelliJ not to make this inspection for variables that will be in request attributes?

A: I will answer my own question:
Forcing
requestScope.username

avoids this warning..


text:
Q: Sort table id's cut by a hyphen (PHP/MySQL) I have a MySQL table that I would like to display in a decreasing way. The problem is that the ID is broken by a dash ... So MySQL does not understand my request.
SELECT * FROM table WHERE id ORDER BY id DESC

results
20633-18489
184945-190028
183661-188782
1575-1610

but I want this order
184945-190028
183661-188782
20633-18489
1575-1610

What is the solution in php?

A: What you are looking for is the REPLACE() FUNCTION
so your query would look like:
SELECT *,  REPLACE(id, '-' , '') AS sortable_id  WHERE id ORDER BY sortable_id DESC

A: In the SQL statement, we could do this:
 ORDER BY id + 0 DESC

or this:
 ORDER BY SUBSTRING_INDEX(id,'-',1) + 0 DESC

The "+ 0" is going to cause the string before it to be evaluated in a numeric context. That will return a number. And then the ordering will be by the numeric value.

As a demonstration
SELECT t.id
     , t.id + 0 AS id0
     , SUBSTRING_INDEX(t.id,'-',1)+0 AS id1
  FROM ( SELECT '184945-190028' AS id
         UNION ALL SELECT '183661-188782'
         UNION ALL SELECT '20633-18489'
         UNION ALL SELECT '1575-1610'
       ) t
 ORDER BY t.id + 0  DESC

returns
id                id0     id1
-------------  ------  ------
184945-190028  184945  184945
183661-188782  183661  183661
20633-18489     20633   20633
1575-1610        1575    1575

Note: this is ordering only on the part of the id before the dash. This doesn't specify what order id values that "match" on the leading portion will be returned in. MySQL would be free to return these two in any order.
456-42
456-321

We can add more expressions to the ORDER BY clause to make the order of these deterministic.


text:
Q: Navigation Bar issue on html page When I am going to the another html page navigating from home page, then the navigation bar (three line) is not opening in android devices. while running go to the inspect and change the view to android to see the problem). Then please help me to solve the issue
Download the zip file from the github link ,extract and run.Project
*Please don't close the question. I have verified the link as public.


text:
Q: Send some arguments to a PHP using the iPhone I need to send some arguments from the iPhone to a php in the server
PHP:
$text = $_GET['text']);
$mail = $_GET['mail']);
$phone = $_GET['phone']);

iPhone SDK
NSString *text = [[NSString alloc] initWithString:@""]; //very long text
NSString *mail = [[NSString alloc] initWithString:@"any@any.com"];
NSString *phone = [[NSString alloc] initWithString:@"456233876"];

How can I send this strings to the PHP?

A: Here's how you'd create an HTTP POST request with NSURLConnection to post the fields "text", "mail", and "phone":
NSURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.myserver.com/page.php"]];
NSMutableString *postBody = [NSMutableString stringWithFormat:@"text=%@", [@"very long text" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[postBody appendFormat:@"&mail=%@", [@"any@any.com" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[postBody appendFormat:@"&phone=%@", [@"1231231234" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[req setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPMethod:@"POST"];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];

// Now, implement NSURLConnection delegate methods such as connectionDidFinishLoading: and connection:didFailWithError: to do something with the response from the server.

A: Just use GET or POST data, as normal. It's very simple. Then use an NSURLConnection to send the data, and change the method to POST. Or you can use GET, and just send a URL like http://www.mysite.com/mypage.php?var1=abc&var2=def etc.
See
Using NSURLConnection


text:
Q: Distinguish between multiple arguments and array argument in Java method I have a method which accepts multiple arguments: void doodle(Object o, Object... objects).
Is there any way to distinguish if objects is a real array or just one built from multiple arguments?
Overloading the method like void doodle(Object o, Object[] objects) is not allowed in Java.

A: There is no way to distinguish, because there is no real difference.
Object... is nothing more than syntactic sugar, under the hood, the real method signature has Object[], that's why you can't overload it, it's basically the same.
For your particular use case, you can test if the method has varargs and create the visualization accordingly, see if this helps:
http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#isVarArgs%28%29


text:
Q: Eclipse Workspace Path Error I download SDK 4.5 on Samsung webpage. After i add a samsung's example codo. Everything is successfully. But when i execute it being follow Error:
Eclipse Workspace Path Error
- Please don't use spaces.
- Please change Eclipse workspace path
please help me about this.
thanks so much.

A: Don't use spaces on your workspace path.
If it's on "c:\My long folder with spaces\Name\Workspace for code\Shapur Mohit Magwar\workspace" it won't work.
Try c:\Coding\eclipse_workspace instead.


text:
Q: Mvvmcross tombstoning - always return null values I tried two approaches:
1.
    public class SavedState
    {
        public string Data1 { get; set; }
        public string Data2 { get; set; }
    }

    public void ReloadState(SavedState state)
    {
        //Data1 and Data2 always have null values.
    }

    public SavedState SaveState() {
        return new SavedState
        {
            Data1 = "AAAA",
            Data2 = "BBBB"
        };
    }

2.
    protected override void ReloadFromBundle(IMvxBundle state)
    {
        base.ReloadFromBundle(state);

        //state.Data has 0 elements.
    }

    protected override void SaveStateToBundle(IMvxBundle bundle)
    {
        bundle.Data["Data1"] = "AAAA";
        bundle.Data["Data2"] = "BBBB";

        base.SaveStateToBundle(bundle);
    }

What am I doing wrong? The ReloadStateand ReloadFromBundle methods are called but with null parameters.
I have only Windows Store target, with custom presenter which shows view this way:
_rootFrame.Navigate(GetViewType(request), request);

A: Yesterday I had similar issue.
I used this code to show ViewModel with parameter:
ShowViewModel<UserAccountViewModel>(new UserAccountViewModelParams{ FromLogin = true });

and tombstoning behaved exactly like in your case.
When I changed it to:
ShowViewModel<UserAccountViewModel>();

it worked.
I guess it's MVX error.


text:
Q: Not able to get camera running status To check whether camera is running or not i am writing these code
ActivityManager actvityManager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
    String packageName = actvityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
    if(packageName.equals("android.hardware.camera")||packageName.equals("com.android.camera")){
        Camera_status = "STATUS_ON";
        System.out.println("===on===");
    }else{
        Camera_status = "STATUS_OFF";
        System.out.println("====off====");
    }

By using this, i am able to get correct result in android emulator but while testing In real device i an not able to get the correct result.As per the answer posted here by CommonsWare,i think he is correct.So friends may i know how to get the camera on/off status programmatically.

A: Try This its working!!!
Camera _camera;
    boolean qOpened = false;
    try {
        _camera=Camera.open();
        qOpened=(_camera!=null);
        if(qOpened){
            Camera_status = "STATUS_OFF";
        }else{
            System.out.println("==nothing to do====");
        }

    } catch (Exception e) {
        Camera_status = "STATUS_ON";
        System.out.println("=====Camera running=====");
    }


text:
Q: Basic authentication doesn't work for SOAP Web Service with Active Directory LDAP in Spring Boot The HTTP Basic Authentication is failing while testing the SOAP Request from SOAP UI but working when trying to access the wsdl from Web Browser.
I have added the Authentication details in SOAP UI also under Authentication tab with details as shown below:

*

*Authorization Type  : Global HTTP Basic

*Username : ****

*Password : ****

*Domain: test.com //here the domain given which has configured in LDAP Config

Getting below error logs on consoile while testing from SOAP UI:
Getting " ExceptionTranslationFilter - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
"
[DEBUG] 2018-08-28 12:08:33.070 [http-nio-36454-exec-3] AndRequestMatcher - Trying to match using Ant [pattern='/**', GET]
[DEBUG] 2018-08-28 12:08:33.070 [http-nio-36454-exec-3] AntPathRequestMatcher - Request 'POST /error' doesn't match 'GET /**
[DEBUG] 2018-08-28 12:08:33.070 [http-nio-36454-exec-3] AndRequestMatcher - Did not match
[DEBUG] 2018-08-28 12:08:33.070 [http-nio-36454-exec-3] HttpSessionRequestCache - Request not saved as configured RequestMatcher did not

 Config() as shown below:
@Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().anyRequest().fullyAuthenticated().and().httpBasic().authenticationEntryPoint(authEntryPoint);

        http.exceptionHandling().authenticationEntryPoint(authEntryPoint);

    }

Anything need to be add in WsConfigurerAdapter class  apart from defaultWsdl11Definition for SOAP Web service call to Authenticate in Spring Boot?
and also added the below code in SOAPWebServiceConfig.java:
@Bean
    public XwsSecurityInterceptor securityInterceptor(){
        XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
        //Callback Handler -> SimplePasswordValidationCallbackHandler
        securityInterceptor.setCallbackHandler(callbackHandler());
        //Security Policy -> securityPolicy.xml
        securityInterceptor.setPolicyConfiguration(new ClassPathResource("securityPolicy.xml"));
        return securityInterceptor;
    }

    @Bean
    public SimplePasswordValidationCallbackHandler callbackHandler() {
        SimplePasswordValidationCallbackHandler handler = new SimplePasswordValidationCallbackHandler();
        handler.setUsersMap(Collections.singletonMap("user", "password"));
        return handler;
    }

    //Interceptors.add -> XwsSecurityInterceptor
    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) {
        interceptors.add(securityInterceptor());
    }

Can anyone please help on this.

A: Try using this in config():
@Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().anyRequest().fullyAuthenticated().and().csrf().disable().httpBasic();
    }

And when you said Basic Authentication, select "Basic" in SOAP UI Authorization.


text:
Q: Pipe ssh's output (stderr and stdout) to different commands I'm a writing script for some kind of backup involving ssh and rsync. Every time that script runs I redirect all output to a log file. To standardize the log-entries I wrote a log-function that adds a timestamp and log-level. My idea was to also read the stdout and stderr of each command line by line and call that log-function. Therefor I followed the answers from https://serverfault.com/questions/526592/pipe-stderr-and-stdout-to-different-commands-not-just-to-files.
My script looks like this (it's reduced, assume all used vars are set properly):
#!/bin/bash

# function: print a formatted log message including timestamp with given level and message to stdout
# arguments: <LEVEL> <MESSAGE>
log()
{
    timestamp=$(date +"%F %T.%3N")
    level=$1
    message=$2
    echo $timestamp $level: $message
}

# function: read command output from stdin and log it with given level
# arguments: <LEVEL>
logoutput()
{
    sed 1d | \
    while read i
    do
        log "$1" "$i"
    done
}

log INFO "START ssh"
(ssh $connection mkdir -p $destStaticDirectory | logoutput INFO) 3>&1 1>&2 2>&3 | logoutput ERROR

log INFO "START rsync"
(rsync $rsyncArguments $linkDest $fromDirectory $connection:$destStaticDirectory | logoutput INFO) 3>&1 1>&2 2>&3 | logoutput ERROR

The function log() is used to echo a log entry and the function logoutput() is used to read stdout line by line and log each.
Now the thing is everything works as expectet for the rsync-command. But not for the ssh-command. I know there is no output to stdout when calling ssh $connection mkdir -p $destStaticDirectory correctly. So I tested it by letting ssh connect to an an unkown host which results in ssh: Could not resolve hostname XXX: Name or service not known. But again nothing. I also added the same ssh-command "unwrapped" to the script which prints all output as expected. Finally I switched on ssh's verbose mode which resulted in error-log-entries. But that's not an option as I dont't want ssh's bebug messages in my log.
Am I missing something? Is there same strange stdout,err handling ssh is doing I'm not aware of?
I hope I made myself clear what I'm trying to do.

A: Your problem is most likely in the logoutput function where "sed 1d" removes the output you are looking for. Try to remove the line "sed 1d" and see if your script behaves as expected.

A: Have you considerd using logger(1) to do the logging for you and add timestamps etc.
Then something like
{ ssh ... | logger ...; }  2>&1 | logger ...

should to what you want as the first part sends stdout to a log file via logger and the second part send stderr to a log file. You can use the logger command line options to select which log facility or file etc.

There is a neater way of doing this too. Use Process Substitution e.g.
ssh ... > >(logger ...) 2> >(logger ...)

This saves having to messa around with all the file descriptors.


text:
Q: For dependency Injection to work, what is the prerequisite Although I have worked in Spring framework for a while, I believe I still don't fully understand it. I want to know how and where dependency injection works.
To reinforce the concepts, I created a standalone Java program, and wanted to see how to inject the implementation using Spring framework.
Here is the snippet of spring bean file:
<beans .....>

    <bean id="CommomImpl" class="com.example.common.impl.CommomImpl">
    </bean>

    <bean id="SimpleImpl" class="com.example.simple.impl.SimpleImpl">
    </bean>
</beans>

Now, the below is the standalone Java program where I wanted to see how DI works.
public class MainApp {

    Resource(name = "SimpleImpl")    -------------------> (1)
    static SimpleTasks simpleTasks1;

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("spring-bean-config.xml");

        SimpleTasks simpleTasks = null;
        CommonTasks commonTasks = null;

        simpleTasks = (SimpleTasks) context.getBean("SimpleImpl"); ----->(2)
        simpleTasks.print("USER");

        commonTasks = (CommonTasks) context.getBean("CommomImpl"); ----->(3)
        commonTasks.add(3,3);

        simpleTasks1.print("USER"); ---------(4)
    }
}

With regards to above program, I have following questions:
Q1: The code at (1) doesn't provide any injection, that is simpleTasks1 is null. What this is so? How come in web-applications, we can inject implementation using similar fashion?
Q2: Are (2) and (3) dependency injection?
Q3: The code at (4) gives null pointer exception, because (1) doesn't inject the implementation. It is this which is confusing me. Under what situations does DI work?  When we create the web-application, we deploy the .war inside a web-container and NOT in Spring container, then how come @Resouce(name = "xyz") works, when the spring framework jars itself are provided as dependency to the application.
Any detailed explanation would be of great help to clear these doubts.

A: Dependency injection works by having a way (configuration) to provide dependencies in your classes. Instead of having the class create its dependencies, you pass the required objects from outside. This makes your code testable and you can take advantage of object reusability.
Dependency injection in Spring works in a similar way with other DI frameworks.
You can either inject a dependency of a class through its constructor, or through a member field (private fields also work in Spring).
What you're doing is calling the spring context to locate the dependency. Once you do this, Spring will try to locate a bean (provider) for the dependency you want. Once it finds it, it will create the object (by resolving its own dependencies as well) or use an existing instance of it and it will return the instance to you.
Spring provides the @Autowired annotation, as a replacement of using the context, which you can use to inject dependencies in your classes and it makes your code cleaner and safer since you don't use the bean name to inject you dependency.
You could also have a look at Java based configurations for spring to avoid configuring your beans in XML files and use the @Bean annotation.
I would strongly suggest to have a look at the guides in the Spring website, especially the ones that use Spring Boot since they are giving you all the info you need to setup a basic example using Java annotations.


text:
Q: I created a hash to replace words from one .po to another file but I don't know how to write the end file I have 2 files, origin.txt and end.txt
Origin.txt have text like this:
msgid "Page not found"
msgstr "Page not found translation"
msgid "Latest Listings"
msgstr "Latest Listings translation"

end.txt hasn't translations
msgid "Page not found"
msgstr ""
msgid "Latest Listings"
msgstr ""

I want to copy the translated words from origin.txt to end.txt. I decided to create a hash in ruby with all the words from origin.txt and then replace the translation between the "" in the line msgstr "".
This is my current code:
tr = {}
msgidline = ""
msgstrline = ""

f = File.open("origin.txt", "r")

target = open("end.txt", 'r+')

# Create a dictionary
f.each_line do |line|
    if line.start_with?("msgid", "msgstr") && line.start_with?(%Q(msgid "")) == false && line.start_with?(%Q(msgstr "")) == false
        if line.start_with?("msgid") == true
            msgidline = line.scan(/"([^"]*)"/).join()
        elsif line.start_with?("msgstr") == true
            msgstrline = line.scan(/"([^"]*)"/).join()
        end
    end
    tr[msgidline] = msgstrline
end

msgidlineReference = ""

target.each_line do |line|
    if line.start_with?("msgid", "msgstr") && line.start_with?(%Q(msgid "")) == false
        if line.start_with?("msgid") == true
            msgidReference = line.scan(/"([^"]*)"/).join()
        elsif line.start_with?("msgstr") == true
            msgstrtext = line.scan(/"([^"]*)"/).join()
            line.gsub(msgstrtext, tr[msgidReference])
        end
    end
end

target.close
f.close

I am getting a nil error:
translate.rb:29:in `gsub': no implicit conversion of nil into String (TypeError)

I don't know hot to make work the sub or gsub commands and replace the words in end.txt. This is the way to go? or do you think there is a better way to do it?
Edit update: I added ".join() at the end of scan. Now the nil error is gone. Thanks rantingsonrails.
Now I need to write or replace in the file because it is not changing. Do you have any ideas?

A: Rewrote for more Rubyishness.
tr = {}
msgid = nil
File.readlines("origin.txt").each do |line|
  if (match = line[/^\s*msgid\s*"(.*)"\s*$/, 1])
    msgid = match
  elsif (match = line[/^\s*msgstr\s*"(.*)"\s*$/, 1])
    tr[msgid] = match
  end
end

lines = File.readlines("end.txt").map do |line|
  if (match = line[/^\s*msgid\s*"(.*)"\s*$/, 1])
    msgid = match
  elsif (match = line[/^\s*msgstr\s*"(.*)"\s*$/, 1])
    line[Regexp.last_match.begin(1), match.length] = tr[msgid]
  end
  line
end

File.write("end.txt", lines.join)

Note that you need to remember only the ID; then when you encounter the STR, you use both. In original code, you would end up with wrong tr because you put stuff into tr after each line - specifically after ID changes (but the associated STR hasn't been read yet). They need to be processed in pairs.
scan is an overkill, because it looks for multiple occurrences. There is only one occurrence we're interested in, per line; and String#[] is just so handy with Regexp.
It is typical in Ruby to use a block with open, so that we can guarantee the file handle is closed after it is not needed. Sure, f and target will be closed when the script exits, but it is not very elegant. However, we want lines, and there happens to exist a method that opens a file, gets all the lines and closes it - perfect tool for the job.
While we could open the file for reading and writing, read it then truncate it and write new contents, just opening it once for reading and once for writing is easier on the programmer.
As for lines, they could contain whitespace, or comments, or whatever that we're not interested; so each line that doesn't contain ID or STR is still kept, without change, while STR lines are transformed using String#[]= operator, to seamlessly slot in the new content exactly where we found the old.

A: The method scan returns an array, not a string, and gsub requires a string as a parameter.
For example
If line = %q[msgid "Page not found"]
line.scan(/"([^"]*)"/) will return [["Page not found"]]
So something like the following would at least get rid of that error.
msgstrtext = line.scan(/"([^"]*)"/)
unless msgstrtext.empty?
  line.gsub(msgstrtext.first.first, tr[msgidReference].to_s)
end

Full code including file writing and reading
tr = {}
msgidline = ""
msgstrline = ""

f = File.open("origin.txt", "r")

# Create a dictionary
f.each_line do |line|
    if line.start_with?("msgid", "msgstr") && line.start_with?(%Q(msgid "")) == false && line.start_with?(%Q(msgstr "")) == false
        if line.start_with?("msgid") == true
            msgidline = line.scan(/"([^"]*)"/).join()
        elsif line.start_with?("msgstr") == true
            msgstrline = line.scan(/"([^"]*)"/).join()
        end
    end
    tr[msgidline] = msgstrline
end

@msgidlineReference = ""

new_lines = File.readlines("end.txt").map do |line|
    if line.start_with?("msgid") == true
      @msgidReference = line.scan(/"([^"]*)"/).join
      @new_line = line
    elsif line.start_with?("msgstr") == true
      msgstrtext = line.scan(/"([^"]*)"/).join
      @new_line = %Q[msgstr "#{tr[@msgidReference].to_s}"\n]
    end
    @new_line
end

File.write("end.txt", new_lines.join)


text:
Q: Search substring in a list and give all the matching results comma separated I have a list of items
My uncle eats a banana
My uncle eats a pear
My father eats an apple
My father eats a pear

If i enter the substring "uncle" i want to see "My uncle eats a banana,My uncle eats a pear"
If enter "pear" I want to see "My uncle eats a pear,My father eats a pear"
The tricky thing is that it cannot be a macro
Any ideas how I can get that to work?
I found on
https://www.xelplus.com/return-multiple-match-values-in-excel/
This formula:
=TEXTJOIN(",",TRUE,IF(A5:A14=G4,B5:B14,""))
which works only for exact matches, not substrings

A: You could use:

Formula in C1:
=TEXTJOIN(", ",,FILTER(A$1:A$4,ISNUMBER(FIND(" "&B1&" "," "&A$1:A$4&" "))))

Or:
=TEXTJOIN(", ",,IF(ISNUMBER(FIND(" "&B1&" "," "&A$1:A$4&" ")),A$1:A$4,""))

The 2nd option is to be CSE-entered in Excel-2019.

A: As I'm using Excel 2016 (without TEXTJOIN function), My method while trying not to use VBA was like this excel file:
https://www.dropbox.com/s/7c09ykr4redog4k/Concat%20without%20VBA.xlsx?dl=1
Hope helps you


text:
Q: QML MediaPlayer with GStreamer Backend on Windows I am designing a video streaming application where host (sender) is on Ubuntu and client (reciever) is on Windows (msvc2015 compiler). My main focus is sending and showing the most recent frame as fast as possible on screen. Both computers have QT 5.15.2
I am utilizing GStreamer with JPEG encryption for sending the frames with the below pipeline. (A little bit modified version of the pipeline from QMediaPlayer documentation https://doc.qt.io/qt-5/qmediaplayer.html)

gst-pipeline: appsrc ! video/x-raw, format=BGRx, framerate=0/1 !
videoconvert ! video/xraw, format=I420 ! jpegenc ! rtpjpegpay ! udpsink
host=127.0.0.1 port=5000

I can decode and show this stream with QML MediaPlayer on Linux and the performance is quite good.
MediaPlayer {
        id: mediaPlayer
        source: "gst-pipeline: udpsrc port=5000 caps = \"application/x-rtp, media=video, clock-rate=90000, encoding-name=JPEG, payload=26\" ! rtpjpegdepay ! jpegdec ! videoconvert ! qtvideosink sync=false"
        autoPlay: true
    }

However, my target is to show this stream on Windows machine and I am having difficulties with GStreamer backend. Same url results in the error below. I think it indicates QT is not linked to gstreamer backend and passes the given argument to DirectShow.

DirectShowPlayerService::doSetUrlSource: Unresolved error code
0x800c000d (The specified protocol is unknown.)

Stream plays well with gst-launch command given below, it seems only problem is qt is not able to use gstreamer. In this case, I could not find a way to link GStreamer with QT on windows.

.\gst-launch-1.0.exe udpsrc port=5000 caps = "application/x-rtp,
media=video, clock-rate=90000, encoding-name=JPEG, payload=26" !
rtpjpegdepay ! jpegdec ! videoconvert ! autovideosink sync=false

I can also show the video with K-Lite codec using QML MediaPlayer again but the video has a delay around 1-2 seconds which is not desired for my design. The code snippet is given below:
MediaPlayer {
        id: mediaPlayer
        source: "rtp://127.0.0.1:5000"
        autoPlay: true
    }

My question is can I integrate gstreamer to QT somehow? If I can not how can I remove the delay that occurs with K-Lite? I would like to obtain the performance I see with gst-launch command.


text:
Q: Invoke-sqlcmd on remote machine I am using following code to execute a query on a remote machine.
Invoke-Sqlcmd -ServerInstance $serverInstance -Database $dbName -InputFile $filePath -U "test" -P "testpwd"

But getting an error like
Invoke-Sqlcmd : Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.

My database server and my machine are in same domain but both are different machnies.
Please help.

A: Make sure you have Windows Authentication and SQL Authentication switched on on the database server you are trying to access.!

A: First of all, I am assuming that your $serverInstance variable is an object, instantiated in the following way:
$serverInstance = New-Object Microsoft.SqlServer.Management.Smo.Server($SQLInstanceName)
I believe that by the time you were having this issue you were using IntegratedSecurity = true (the default value). You can set this to false with the following assignment:
$serverInstance.ConnectionContext.LoginSecure=$false;
An explanation on how this solves the error you were having can be found in this answer:

If your SQL Server is on one domain controller and you are trying to
  connect to it from another domain controller then you will get this
  error when
IntegratedSecurity = true;

This will happen even if you include a valid SQL Server username and
  password in your connection string as they will automatically be
  over-written with your windows login and password. Integrated security
  means simply - use your windows credentials for login verification to
  SQL Server. So, if you are logged in to a different domain controller
  then it will fail. In the case where you are on two different domain
  controllers then you have no choice but to use
IntegratedSecurity = false;

Now, when Integrated security is false SQL Server will use the SQL
  Server login and password provided in your connection string. For this
  to work, the SQL Server instance has to have its authentication mode
  configured to mixed mode, being, SQL Server and Windows Authentication
  mode.
To verify or change this setting in SQL Server you can open the SQL
  Server Management Studio and right-click on your server name and then
  select Properties. On the pop-up that appears select Security and you
  will see where to alter this setting if you need to.


text:
Q: Regex which blacklist special characters but allow all world wide languages characters How to allow spaces between string in this regex
^((?![\s!@#$%[^&*+}/,{"?><.|]\|=:;]).){1,150}.(jpeg|jpg|png|pdf|docx|doc|txt|xls|xlsx)$
currently I am building this one but how to allow spaces in between string


text:
Q: Why did C.S. Lewis use Turkish Delight as temptation for Edmund? As today's xkcd so neatly puts it, The Chronicles of Narnia gives a really unrealistic impression of how good Turkish Delight tastes:

Have some Turkish delight. If you betray your family, there's more where that came from.
Wow. This is... not great.
The Narnia books gave me a really unrealistic impression of how good Turkish delight tastes.

While he was eating the Queen kept asking him questions. At first Edmund tried to remember that it is rude to speak with one's mouth full, but soon he forgot about this and thought only of trying to shovel down as much Turkish Delight as he could, and the more he ate the more he wanted to eat,
The Lion, the Witch, and the Wardrobe - Chapter 4: Turkish Delight

Having tasted Turkish Delight IRL, its really not that great. So what was Lewis' fascination with it, and why did he present it as if it was the end-all-be-all of candy?

A: Beside the delightfullness of some brands of Turkish Delight according to some of those who have answered here, there is also the Turkishness of Turkish Delight to considered.
If Communist Cookies, or Nazi Nougat, or Stalinist Sweets, or Enemy Eclairs, or Anarchist Apple Fritters, had been a popular band of candy or sweets when Lewis was writing, he might have chosen them for Jadis to tempt Edmund with, for the sake of their sinister sounding names.
But if Lewis was limited to using a real and familiar type of sweets, I guess that the name of Turkish Delights might have had the most sinister and hostile connotations of any real type.  Various Turkish realms had been feared threats to various Christian and/or European societies for six hundred years up to the Great Turkish War of 1683 to 1699 when their conquests in Europe began to be reversed.

A: It should be remembered that until Edmund asked for Turkish delight, Jadis had very likely never heard of it at all, and so the enchantments she used to create it were running on his ideas about it.
It was already Edmund's favorite candy (or he would have asked for whatever his favorite candy was and we would be talking about that), and he could have been envisioning it as more enjoyable than his actual experience warranted.
And since the whole point of offering it to him was to hook him into her schemes, she amped up the pleasure of eating it.

A: It's helpful to consider in context of the time. Rationings were in effect in WWII England, and Turkish Delights were a particular delicacy that was popular at the time and hard to come by. Also consider that food in general was less sugar packed than many of the options we have today, so many foods at the time that we might consider "disappointing" would have had a much different impression of the people of their time. From an article a couple years ago regarding this exact question:

The question of Turkish Delight often becomes still more perplexing when a young Narnia fan actually eats the stuff, and finds that it does not live up to Edmund's rapturous praises. As with so many things in pop culture, the answer lies in the context, and since we're living in a beautiful future, an academic article has stepped in to tell us all about the importance of Delight.
According to food critic Cara Strickland, the Turkish sweet cast an intoxicating spell over late-Victorian England. Made from a confection of rose oil and sugar, the candy is simple on paper, but proves extremely difficult to make – no matter how Western Europeans tried, they never quite replicated it. Thus, if you wanted real Delight, you had to import it from Turkey, which got expensive fast, so that it became a marker of either status or indulgence in much the way the way coffee had a century earlier.
Of course just as costs had gone down, the outbreak of World War II and its subsequent rationing meant that the candy was harder than ever to come by. Perhaps this is why it became so significant to Lewis? As he welcomed refugee children into his Oxford neighborhood, he thought back on the candies and holidays that had marked his own childhood.

It makes sense that Turkish delight would have been on Lewis's brain as he crafted a book where Christmas features as a main theme. In Narnia, it is "always winter and never Christmas," a product of the White Witch's evil magic. It makes sense to draw a parallel between this dismal fantasy and the stark realities of wartime. Rationing extended to timber, which made Christmas trees harder to come by, and confectionery rationing didn't end until February of 1953—still well before the end of sugar rationing later that year. When the White Witch asks Edmund what he'd like best to eat, it's entirely possible that Lewis was answering for him: the candy that would be most difficult and expensive to obtain. Edmund isn't just asking the witch for candy, he's essentially asking her for Christmas, too.

Why Was Turkish Delight the Ultimate Temptation in C.S. Lewis' Narnia? - Leah Schnelbach
The article I've referenced summarizes and cites from an article written by Cara Strickland. She goes far more in depth into the matter, including pointing out Lewis' fascination with Turkish culture (Aslan is apparently the Turkish word for Lion, for example). It's far too long and detailed to include though, so I recommend checking it out directly if you want to go deeper.
So it was essentially both a cultural delicacy at the time, and as the article speculates, likely something of specific connection to Lewis himself.

A: The only reason that he could not stop eating it is because it was enchanted.
As I recall (having read the book recently, though I don't have it at hand now) there's a point where Edmund is looking longingly at the empty box, and the witch is not surprised, since the treats were enchanted.

A: The reason Edmund forgets his manners (and everything but stuffing as much candy in his mouth as fast as humanly possible) is not the fact that Turkish Delight is the greatest confection in existence, but the White Witch's magic:

At last the Turkish Delight was all finished and Edmund was looking very hard at the empty box and wishing she would ask him whether he would like some more. Probably the Queen knew quite well what he was thinking; for she knew, though Edmund did not, that this was enchanted Turkish Delight and that anyone who had once tasted it would want more and more of it, and would even, if they were allowed, go on eating it till they killed themselves.

This is apparently something she's done before, probably with other foods, as Beaver specifically calls out her food in connection with treachery.

"He had the look of one who has been with the Witch and eaten her food. You can always tell them if you've lived long enough in Narnia; something about their eyes."

So while you can look to the other answers for the reason Lewis picked Turkish Delight over say, toffee, keep in mind that this was never supposed to be a realistic impression of how good Turkish Delight tastes.

A: Possibly due to how the writing works as Turkish delight is a very specific food for a westerner to imagine.
If I say chocolate you are imagining a vague concept of twenty plus types but you have probably only had Turkish delight a few times and it makes the reader imagine the food with much more clarity.

A: While I support the answer of Mwr247 for important context (even if it largely lifts from another source that lacks a clear CC license), I came across an interesting answer for this question years ago at a diverse table of people from many countries.
The Turkish representative had brought a box of Turkish delight, imported from Turkey, and thus labeled in its original Turkish language ("Lokum").  This was touted as the real thing; I'd finally get to learn after years of waiting just what Edmund (Lewis) was referring to.
The Danish representative, arriving a few moments later, laughed and commented that in his language, the word means "toilet."
So even linguistically, we were set up for the experience of the dessert being a welcome treat but not nearly as amazing as Edmund described it, in comparison and context with a modern peacetime of relative abundance where a wide variety of sweets and rich foods are relatively easy to come by.
If Lewis knew this, this particular choice of treat could have been a hidden reference to something which seems quite attractive on its surface but has a much dirtier true meaning underneath.  With evacuated Danish children in wartime England, real Turkish delight something that would have to be imported (according to Leah Schnelbach's article quoted by Mwr247), and the higher average number of languages Europeans are familiar with (compared to residents of other English-dominant countries), it would not necessarily be that unusual for Lewis or at least some of his readers to pick up on this connection.
His writing style puts meaning on so many different levels and layers, that I would not be entirely surprised if this was intentional.  Also, he could not have conveyed that meaning with any other choice of treat, so it lends a bit more weight to the possibility that the extra layer of meaning may have been intended.
In a later reading of the particular section quoted in the question, I also interpreted "Turkish Delight" as a code for addictive drugs (e.g. opiods) that also make one forget one's manners, think only of trying to shovel down as much as one can, where the more one consumes the more one wants to consume.  Lewis's goal of embedding morals and lessons important for young people to learn would likely have included strong cautions against this sort of substance, even if is something that sounds exotic and tempting, because such drugs lead to one's downfall and hurt one's family.


text:
Q: Find the sides of the triangle given its area and the sides of the similiar triangle The triangle $\triangle ABC$ is similar to the triangle $\triangle A'B'C'$. The sides of the triangle $\triangle ABC$ are $a$, $b$ and $c$ and the sides of the triangle $\triangle A'B'C$ are $a'$, $b'$ and $c'$. The area of the triangle $\triangle ABC$ is $A=63$. The sides of the triangle $\triangle A'B'C'$ are $a'=45,b'=40,c'=13$. How can we find the sides $a,b,c$?
Unfortunately, I couldn't crack this problem altough I did try out a few approaches (all of them eventually led me to a dead end). But, if someone of you needs the area of the triangle $\triangle A'B'C'$ it is $A'=18\sqrt{861}$ (well, at least I think so).

A: Hint:
If $w$ is the scale factor of the corresponding sides, then $w^2$ is the scale factor for the areas.

Since you know one of the two areas, and can find the other (Heron's formula),
you can find $w^2$, hence you can find $w$.
By the way, for the other triangle, check your area calculation (I get $252$).

A: If the areas of two similar triangles have ratio X then corresponding side lengths will have ratio Sqrt(X). So if you are correct in your calculation of the area of triangle A'B'C', you should now have a solution for the side lengths of triangle ABC.

A: 1) How to find the area of a triangle from its sides:
Hurons' formula:
If a triangle has sides $a,b,c$ then perimeter is $a + b + c$ and the semi-perimeter is $p = \frac {a+b+c}2$ then the area of the triangle is $\sqrt{p(p-a)(p-b)(p-c)}$.
So... $ a′=45,b′=40,c′=13$ so $p = \frac {45 + 40 + 13}2 = 49$.
So Area $\triangle A'B'C' = \sqrt{49(49-45)(49-40)(49-13)} =\sqrt{49*4*9*36} = 7*2*3*6=252$.
2) Areas are proportion to the squares of the proportions of the sides.
If $\frac a{a'} = \frac b{b'} = c{c'} = k$ then $\frac {Area \triangle ABC}{Area \triangle A'B'C' }= k^2$
So  $\frac {Area \triangle ABC}{Area \triangle A'B'C' }= \frac {63}{252} = \frac {7*9}{7*2*3*6}= \frac 1{4}$.
So $k = \frac 12$
So $a = ka'=\frac 1245=\frac {45}2 ; b = kb'=\frac 1240=20; c = kc'=\frac 1213=\frac {13}2$

A: Your area calculation is wrong. Try it again with Heron's formula. Cross-check by plugging your values here. I get 252. Thus, $\triangle A'B'C'$ is 4 times the size of $\triangle ABC$. Thus, $a, b, c$ are half of $a', b', c'$.


text:
Q: Type Error Converting circular structure to JSON starting at object with constructor 'Object' the problem I have is that I want a Medico from the collection to be updated in the collection and I managed to unstructure the data of the Medico name and email
and I managed to get the ID of the assigned hospital
and when I modify them I can't get it to send them to me in the correct format. I attach the code that I have
  cargarMedico(id: string) {
    if (id === 'nuevo') {
      return;
    } else {

      this.medicoService.obtenerMedicoPorId(id)
        .subscribe(medico => {

          //Regla de validacion
          if (!medico) {
            this.router.navigateByUrl(`/dashboard/medicos/`)
          }

          console.log(medico)
          const hospital = medico.hospital?._id;
          console.log(hospital)

          const { nombre, email } = medico;
          console.log(nombre, email, hospital)
          this.medicoSeleccionado = medico;
          this.medicoForm.setValue({ nombre, email, hospital });
        });
    }
  }

Here I perform the destructuring to get the necessary data
guardarMedico() {

    const { nombre } = this.medicoForm.value

    if (this.medicoSeleccionado) {
      //actualizar
      const data = {
        ...this.medicoForm,
        _id: this.medicoSeleccionado.hospital
      }
      this.medicoService.actualizarMedico(data)
        .subscribe(resp => {
          console.log(resp);
          Swal.fire('Actualizado', `${nombre} actualizado correctamente`, 'success');

        })

    } else {
      //crear
      const { nombre } = this.medicoForm.value
      console.log(this.medicoForm.value)
      this.medicoService.crearMedico(this.medicoForm.value)
        .subscribe((resp: any) => {
          console.log(resp);
          Swal.fire('Creado', `${nombre} registrado correctamente`, 'success');
          this.router.navigateByUrl(`/dashboard/medico/${resp.medico._id}`)
        })
    }

  }

This is where I save for recording in the collection
  public medicoSeleccionado: Medico | any;

export class Medico {

    constructor(
        public nombre: string,
        public img: string,
        public email: string,
        public _id: string,
        public usuario?: _MedicoUser,
        public hospital?: Hospital

    ) { }
}

this is the Model of Medico
And this is the bug
enter image description here
If you need more part of the code to help me solve the problem, ask for it
I had problems destructuring the hospital since I tried to do it directly but it gave me an error and of course I necessarily need that ID to update the Medico
const { nombre, email, hospital{ _id} } = medico;

A: Okay, first of all your destructuring is wrong, you should do something like this:
const { nombre, email, hospital } = medico;
const { _id } = hospital;

and maybe put an alias to the _id but that's up to you.
now your save method should take the value of form not the instance which is what you do by just doing ...this.form, it should be ...this.form.value
guardarMedico() {

    const { nombre } = this.medicoForm.value

    if (this.medicoSeleccionado) {
      //actualizar
      const data = {
        ...this.medicoForm.value,
        _id: this.medicoSeleccionado.hospital._id
      }
      this.medicoService.actualizarMedico(data)
        .subscribe(resp => {
          console.log(resp);
          Swal.fire('Actualizado', `${nombre} actualizado correctamente`, 'success');

        })

    } else {
      //crear
      const { nombre } = this.medicoForm.value
      console.log(this.medicoForm.value)
      this.medicoService.crearMedico(this.medicoForm.value)
        .subscribe((resp: any) => {
          console.log(resp);
          Swal.fire('Creado', `${nombre} registrado correctamente`, 'success');
          this.router.navigateByUrl(`/dashboard/medico/${resp.medico._id}`)
        })
    }

  }


text:
Q: Best way to repackage ripped DVD to mpg I have a bunch of DVDs that I've already ripped into a VIDEO_TS directory containing .IFO and .VOB files.
I have a cheap primitive video player that will accept .mpg files.
I've tried two different solutions for converting formats, but neither give totally acceptable results. The first is Handbrake. It has a magical ability to zero in on the content I want, but it insists on re-encoding everything it touches. This makes it take forever to create a file, and the result is noticeably inferior to the original.
The second is ffmpeg. It can quickly convert the format with no loss whatsoever, but it can't process multiple input files and thus requires you to manually concatenate the .VOB files before you start. It also doesn't know when to stop - I have one example where the last VOB consists of 2/3 of the end of the movie and 1/3 of the start of a making of documentary. I'd like to lose the documentary. The command line I use is:
ffmpeg -i temp.vob -target film-dvd -vcodec copy -acodec copy "movie.mpg"

I'd like something that combines the convenience of Handbrake with the lossless quality and speed of ffmpeg, preferably free or with a trial at a minimum.
Edit: I'd also be happy with finding the options for Handbrake or ffmpeg that would allow them to do what I want. At the moment it looks like I'll need to use another utility to find the length of the segment that I want to keep, then pass that parameter to ffmpeg - hardly a streamlined operation.

A: Based on the information you've provided in the comments; I would suggest that you try the following Handbrake settings:
Container: MP4 File (Leave all three boxed unticked)
Leave everything on the Video Filters, Chapter, Subtitles, Advanced tabs blank
Video Tab - Video Codec: MPEG-2 (FFMpeg), leave quality factor as it is, default is fine
Audio Tab - Leave it as the default to begin with, if that doesn't work try changing the audio codec to MP3 (lame)
Based on what I can tell, those settings should work with the player in question - maybe a little of trial and error with the audio codec, but MP3 is pretty universally supported.

A: Your best bet is to strip out the extraneous data of the VOB -- after all, it's already in MPG format. You can use Project X for this. It does many other things, but will strip the audio/video out into MPG, with the added benefit of not transcoding -- this way you'll have video and audio that's identical to the original (no loss due to additional compression). Not to mention it's dramatically faster to strip out the unnecessary data than to re-encode.


text:
Q: iPhone: round double value I have a few double values..35.44, 35.66 . I need to round them, and the result should be as NSNumber. The result should be 35.4 , 35.7. So how to do that ? Once again, the result should be as NSNumber, not NSString !

A: You could print it to a string and use the format string to clip it to one decimal point.
NSString *stringRepresentation = [NSString stringWithFormat:@"%.1f", myDouble];
NSNumber *number = [NSNumber numberWithDouble:[stringRepresentation doubleValue]];

A: Multiply by 10, use a rounding function to strip the decimal, then divide by 10.

A: NSNumber *myNumber = [NSNumber numberWithInt:myDouble];

or
NSNumber *myNumber = [NSNumber numberWithInt:(int)myDouble];

EDIT:
I misread the original question and thought you wanted to store a double as an integer value in an nsnumber.
So to answer the correct question, another option is an interim int:
double myDouble = 1.23;
int myInt = myDouble * 10;
myDouble = (double)myInt ;
myDouble /= 10;
NSNumber *myNumber = [NSNumber numberWithDouble:myDouble];

You might be better just storing the double in the NSNumber though and rounding it when you retrieve it later.
EDIT 2:
a more streamlined version would be:
double myDouble = 1.23;
myDouble = (int)(myDouble * 10);
NSNumber *myNumber = [NSNumber numberWithDouble:myDouble/10];

it's probably better to not have to create an interim nsstring... imho


text:
Q: Python eval does not use locals() where called from nor locals() passed to eval for func def one():
    var1 = 1

    def sub():
        nonlocal var1
        var1 += 1
        return var1

    return sub

def two():
    var1 = 5
    sub1 = one()
    return eval('sub1()', globals(), locals())

if __name__ == "__main__":
    print(two())

I was expecting the above code to print 6 but it prints 2. The Python 3.6.1 docs state: "The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. "
Do the global and local namespaces only apply to what can be parsed in eval? The function call sub1() is evaluated in the namespace of the sub1() function regardless of global or local being passed to eval?

A: Yes, the global and local namespaces pretty much only apply to those that can be parsed in eval. Function objects are statically bound to their global object (the module!) and when a function is entered, a new local namespace is created.

A: nonlocal refers to a parent scope of the function's definition, not the call site. When you pass locals into eval, you're not changing the local variables inside of functions you call — you're setting up local variables for the code snippet you're evaluating. So writing eval('sub1()', globals(), locals() is equivalent to just writing sub1(), because the same local variables are in scope either way — and you wouldn't expect sub1 to return 6 if you wrote that, would you?