text:
Q: SQLServer how to convert single row values in to multiple rows with each property as separat I have a user defined type which is passed to my sql stored procedure:
CREATE TYPE [dbo].[LearningDelivery] AS TABLE(
    [LearnAimRef]       NVARCHAR(10)    NOT NULL,
    [AimType]           INT             NOT NULL,
    [AimSeqNumber]      INT             NOT NULL,
);

i have a table with structure as below. I want to match join the type name from the above definition into the ElementName column of the FieldDefinitation table and insert separate insert statements. can anyone help me how to achieve this?
CREATE TABLE [dbo].[LearningAimData]
(
    [Id] INT IDENTITY(1, 1) NOT NULL,
    [LearnerId] INT NOT NULL,
    [FieldId] INT NOT NULL,
    [Data] VARCHAR(128) NOT NULL
)

I want to insert each type i.e LearnAimRef , AimType as individual row values in the LearningAimData.
I have a lookup table for [FieldId]
CREATE TABLE [dbo].[FieldDefinition]
(
    [Id] INT IDENTITY(1, 1),
    [FieldId] INT NOT NULL,
    [Name] VARCHAR(50) NOT NULL,
    [ElementName] VARCHAR(50) NOT NULL
)


text:
Q: Read the JSON Objects and Create New JSON File with selected key values I have two different json API responses, which contain the information required for further processing, my requirement is to read these json responses, pull the required information, and create a new single file with the below provided format.
first output:
DETAILS=$(echo $RESPONSE | jq  ".results[] | select( .name | index(\"$CLUSTER\"))" | jq -r '[.name, .regionName, .diskSizeGB, .instanceSizeName]')

echo $DETAILS

[
  "cluster_name",
  "region",
  100,
  "R50"
]

second output:
LATEST_SNAP_ID=$(echo $SNAP_RESPONSE | jq -c ".results[] | select( .createdAt | contains(\"$time_stamp\"))" | jq -r '[.id, .createdAt]')

echo $LATEST_SNAP_ID
[
  "1234567890987654321",
  "2022-12-20T23:01:56Z"
]

I tried various options with jq, but no luck.
expected output would be:
Note: the response contains the values for all the clusters, and we need to pull only the required values for them.
echo $SNAP_RESPONSE | jq '.results[0, 1]'

{
  "cloudProvider": "AWS",
  "copyRegions": [],
  "createdAt": "2022-12-20T23:01:56Z",
  "expiresAt": "2022-12-27T23:03:50Z",
  "frequencyType": "daily",
  "id": "1234567890987654321",
  "links": [
    {
      "href": "url1",
      "rel": "self"
    },
    {
      "href": "url2",
      "rel": "url3"
    }
  ],
  "mongodVersion": "1.1.1",
  "policyItems": [
    "12345465672342"
  ],
  "replicaSetName": "cluster_name_1",
  "snapshotType": "scheduled",
  "status": "completed",
  "storageSizeBytes": 23141234,
  "type": "replicaSet"
}
{
  "cloudProvider": "AWS",
  "copyRegions": [],
  "createdAt": "2022-12-19T23:03:08Z",
  "expiresAt": "2022-12-26T23:05:02Z",
  "frequencyType": "daily",
  "id": "1234567890987654322",
  "links": [
    {
      "href": "url1",
      "rel": "self"
    },
    {
      "href": "url2",
      "rel": "url3"
    }
  ],
  "mongodVersion": "1.1.1",
  "policyItems": [
    "12345465672342"
  ],
  "replicaSetName": "cluster_name_2",
  "snapshotType": "scheduled",
  "status": "completed",
  "storageSizeBytes": 32547137,
  "type": "replicaSet"
}

Since the $RESPONSE is too big to paste here, selected the required keys.
echo $RESPONSE | jq '.results[0, 1]' | jq '[.name, regionName, .diskSizeGB, instanceSizeName]'

[
  "cluster_name_1",
  "region",
  10,
  "M20"
]
[
  "Cluster_name_2",
  "region",
  160,
  "R50"
]

Please assist.

A: Your question only includes information for one cluster, so the following only shows how to handle the data for DETAILS and LATEST_SNAP_ID as provided in the question:
jq -n --argjson r1 "$DETAILS" --argjson r2 "$LATEST_SNAP_ID" '
{
    "cluster_configuration": {
      ($r1[0]): {
        "db_size": $r1[2],
        "size": $r1[3],
        "id": $r2[0],
        "created_at": $r2[1]
      }
   }
}
'

This produces:
{
  "cluster_configuration": {
    "cluster_name": {
      "db_size": 100,
      "size": "R50",
      "id": "1234567890987654321",
      "created_at": "2022-12-20T23:01:56Z"
    }
  }
}

Addendum - Multiple clusters
Assuming r1 is the stream of objects and r2 is the stream of arrays:
you could combine them using:
r2 | jq -n --slurpfile r2 <(r1) '
  def cluster($r1; $r2):
    { ($r1[0]): {
        "db_size": $r1[2],
        "size": $r1[3],
        "id": $r2.id,
        "created_at": $r2.createdAt
      }
   } ;

However, as stated in a comment, it would be better if you combined all the calls to jq into one single call to jq.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multi-tier Application Design Before everyone throws stones at me, I have searched Google / MSDN / StackOver flow for related questions and answers but none of them suited my needs.
I'm working on a rather large application in C# - Windows Forms that is currently divided into the following:

*

*Data-Layer

*Domain-Layer

*UI-Layer

Basically in my current situation the roles of this layers are the following

*

*The Data-Layer's responsability is to communicate with the data-store, basically CRUD operations.

*The Domain-Layer's responsability is to hold the model of our objects, create the objects, apply business-rules etc.

*The UI-Layer, well, basically this is what the user sees and interacts with.

My problem is the following:
From the UI Layer the user has access to fields like: Name, Project Name, Project Number which basically are TextBoxes, Calendars etc - all of them are UI Components.
After the input of the user I call a method named: AddExplorerNode(string name, string projectName, int projectNumber) which resides in the Domain-Layer. This method is responsible based on the passed parameters to create an ExplorerNode Object ( a "special" TreeNode ) which requires the passed parameters to actually be valid.
After the object has been created, sanitized, validated etc - the same method mentioned above passes the created object to the Data-Layer which pushes it to a Cache-Repository and then to persists it to the data-store if everything went OK in the Cache.
So until now, basically everything is separated UI -> Domain -> DataLayer.
My question is, could I replace the signature of the Domain method from
AddExplorerNode(string name, string projectName, int projectNumber) to AddExplorerNode(TreeNode node) and based on the TreeNode object and its properties, construct the actual object I need ? I'm asking this because, if the Domain-Layers knows about the UI ( in this case the TreeNode UI Component ) basically we break the separation.
For example, if next year we swap WindowsForms to a Console Application, then the project is broken due to the fact that a Console Application will not have a TreeNode UI Component.
In this case, is it better to have a domain method which takes for example 5-10 parameters ( int's, strings, etc ) and based on those parameters to create my object or to replaces the parameters with a TreeNode UI Component which ?
Thank you in advance.
@EDIT:
I am asking this question, because a colleague of mine reviewed my code and started to refactor it. By refactoring he was exposing the actual TreeNode UI Component to the Domain-Layer. My approach was AddExplorerNode(string name, string projectName, int projectNumber) etc.

A: You can make your own class that acts in a similar way to TreeNode without actually being a TreeNode.
class TreeNodeModel
{
    public string Name { get; set; }
    public string ProjectName { get; set; }
    public int ProjectNumber { get; set; }
}

Then you can write a method in the UI to map (copy) TreeNodeModel to an actual TreeNode.


text:
Q: Detecting 2 swipes without interrupting touch I am trying to implement game control that will be changes direction of unit
movement. So if i do right swipe it turns to the right, if i do down swipe it turns to the down direction etc.
It's cocos2d game, and i'am using CCNode+SFGestureRecognizers with UISwipeGestureRecognizer.
At now I have next implementation for it
UISwipeGestureRecognizer *rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleRightSwipe:)];
        [self addGestureRecognizer:rightSwipeGestureRecognizer];
        rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
        rightSwipeGestureRecognizer.delegate = self;
        [rightSwipeGestureRecognizer release];

        UISwipeGestureRecognizer *upSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleUpSwipe:)];
        [self addGestureRecognizer:upSwipeGestureRecognizer];
        upSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
        upSwipeGestureRecognizer.delegate = self;
        [upSwipeGestureRecognizer release];

        UISwipeGestureRecognizer *leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleLeftSwipe:)];
        [self addGestureRecognizer:leftSwipeGestureRecognizer];
        leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
        leftSwipeGestureRecognizer.delegate = self;
        [leftSwipeGestureRecognizer release];

        UISwipeGestureRecognizer *downSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleDownSwipe:)];
        [self addGestureRecognizer:downSwipeGestureRecognizer];
        downSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionDown;
        downSwipeGestureRecognizer.delegate = self;
        [downSwipeGestureRecognizer release];

but the problem is that for to recognize the following gesture you need to lift your finger from the screen. if you do not lift a finger after the first swipe, it will recognize only the first swipe.
at now:

How it should be:

What the best way to do that? Thanks!

A: cancelsTouchesInView should help, it prevents the cancellation of touch events when a gesture recognizer has recognized a gesture. This will allow other gesture recognizers to continue checking for their gesture.
  rightSwipeGestureRecognizer.cancelsTouchesInView = NO;
  upSwipeGestureRecognizer.cancelsTouchesInView = NO;
  leftSwipeGestureRecognizer.cancelsTouchesInView = NO;
  downSwipeGestureRecognizer.cancelsTouchesInView = NO;

A: Ok, there is my solution. I dont think that is really good solution, but in my case it works, because i need getting direction at every time interval.
So, in my CCLayer subclass:
#define SWIPE_LENGTH        60
#define SWIPE_TANGENT       2

...

@property(nonatomic, assign) CGPoint latestLocation;

...

-(id) init
{
    if( (self=[super init]) )
        {
            self.isTouchEnabled = YES;
        }
    return self;
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
    self.latestLocation = location;
}

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
    CGPoint delataLocation = CGPointMake(location.x - self.latestLocation.x, location.y - self.latestLocation.y);
    if ( sqrt(pow((delataLocation.x), 2) + pow((delataLocation.y), 2) ) > SWIPE_LENGTH ) {
        if (delataLocation.y > 0 && delataLocation.y > SWIPE_TANGENT * ABS(delataLocation.x))
        {
            [self handleSwipeWithDirestion:SDirectionTypeUp];
        } else if (delataLocation.y < 0 && ABS(delataLocation.y) > SWIPE_TANGENT * ABS(delataLocation.x))
        {
            [self handleSwipeWithDirestion:SDirectionTypeDown];
        } else if (delataLocation.x > 0 && delataLocation.x > SWIPE_TANGENT * ABS(delataLocation.y))
        {
            [self handleSwipeWithDirestion:SDirectionTypeRight];
        } else if (delataLocation.x < 0 && ABS(delataLocation.x) > SWIPE_TANGENT * ABS(delataLocation.y))
        {
            [self handleSwipeWithDirestion:SDirectionTypeLeft];
        }
        self.latestLocation = location;
    }
}


text:
Q: Monotonicity of number-of-pages as a function of the number-of-characters I often prepare papers for conferences with an upper limit on the number of pages. I spend a lot of time thinking what words and characters to delete in order to make the paper fit in the page limit.
Recently, I run into an interesting and paradoxical phoenomenon: I remove some words, and the number of pages increases!
As an example: I have a two-column paper. I remove two words from the top of column #2 at page #1. As a result, LaTeX takes the last line from column #1 and puts it on top of column #2. Now, the last line of column #2 is pushed to page #2, and so on, and this leads to page overflow.
It is very difficult to create a minimal working example since this behavior doesn't make much sense to me. So before I spend time to create an MWE, I will be happy to know if this behavior is known.

A: Here is a very simpleminded approach to the problem. (And yes, I also remember that I experienced similar things.) This fragile code marks paragraphs that TeX thinks are "bad".
\documentclass[twocolumn]{article}
\usepackage{lipsum}
\newcounter{Pars}
\let\oldpar\par
\def\par{\stepcounter{Pars}%
\ifnum\badness<5000%
\typeout{paragraph \thePars good}%
\else%
\typeout{paragraph \thePars bad}%
\marginpar{\vspace*{-\baselineskip}$\uparrow$}\relax%\vspace*{-\baselineskip}\makebox[0pt][l]{\color{red}$\uparrow$\color{black}}\relax%
\fi
\oldpar}
\begin{document}
\lipsum[1]

\lipsum[2]

\lipsum[3]

\lipsum[4]

\lipsum[5]

\lipsum[6]

\lipsum[7-20]
\end{document}

Let me stress that I am not an expert and hope not to do any major harm. However, this snippet seems really to identify some "problematic" paragraphs. And of course one can play with the threshold or replace \badness by some other measure. And, as Heiko explained, of course the problematic positions may shift if one makes changes at other places. Nevertheless, my hope is that this code may help you to identify locations worthwhile being modified somewhat more efficiently.

A: For example, there is a paragraph with four lines, two lines are at the bottom of the column A and two lines are at the top of the next column B.
Then, one or more words are removed with the result that TeX breaks the paragraph in three lines instead of four.
The document has set \clubpenalty and \widowpenalty to 10000 to prevent widows and orphans (page break right after the first line or right before the last line of a paragraph). The result is that TeX cannot break the paragraph of three lines.
If there is not enough place in column A (likely), then LaTeX has to move the paragraph to column B. Before the deletion of some words, column B got two lines, now column B takes the whole paragraph with three lines. The extra line can now cause a further page, because at every next page breaks stuff is moved to the next page.


text: Q: How to cycle ncurses form field between a fixed set of string values? I tried having a TYPE_ENUM field but that requires typing some part of one entry (with the field performing autocompletion after that). I then thought about perhaps having a TYPE_ALNUM field that has each of the alternative values set in their respective buffers which I first set with set_field_buffer. But how do you switch between buffers then? Or maybe I should have overlapping fields and switch between them in the app? That seems nasty. Any help?


text:
Q: django concatenate filter model why this is not working? I can't concatenate the filter with another variable?
I have a feeling that I'm being very dumb.
I'm new at django and trying a couple of things with the model.
When I use: birthdate__contains='-03-' works fine, but with the variable, nothing shows up at the url
from django.shortcuts import render
from .models import Employee
from datetime import datetime
# Create your views here.

def index(request):
    currentMonth = datetime.now().month
    mes_atual = '-'+str(currentMonth)+'-'
    employees = Employee.objects.filter(
                                    birthdate__contains=mes_atual
    )
    context = {
        'employees' : employees
    }
    return render(request, 'index.html', context)

thanks in advance

A: The output of datetime.now().month will be 3 not 03
To filter you need the date like 03.
currentMonth = datetime.now()
mes_atual = '-' + str(currentMonth.strftime('%m')) + '-'

Refer this answer for info
Your code will be:
def index(request):
    #currentMonth = datetime.now().month
    #mes_atual = '-'+str(currentMonth)+'-'
    currentMonth = datetime.now()
    mes_atual = '-' + str(currentMonth.strftime('%m')) + '-'

    employees = Employee.objects.filter(
                                    birthdate__contains=mes_atual
    )
    context = {
        'employees' : employees
    }
    return render(request, 'index.html', context)


text:
Q: Liquibase ClassCastException on LiquibaseConfiguration when running update on MongoDB Below jars are present on the classpath

*

*mongo-java-driver-3.12.11.jar

*liquibase-mongodb-4.11.0.jar

*liquibase-core-4.11.0.jar

[2022-06-17 12:54:30] SEVERE [liquibase.integration] Unexpected error running Liquibase: java.lang.ClassCastException: liquibase.configuration.LiquibaseConfiguration cannot be cast to liquibase.SingletonObject
java.lang.ExceptionInInitializerError
        at liquibase.ext.mongodb.database.MongoLiquibaseDatabase.getAdjustTrackingTablesOnStartup(MongoLiquibaseDatabase.java:111)
        at liquibase.ext.mongodb.lockservice.MongoLockService.adjustRepository(MongoLockService.java:97)
        at liquibase.nosql.lockservice.AbstractNoSqlLockService.init(AbstractNoSqlLockService.java:102)
        at liquibase.nosql.lockservice.AbstractNoSqlLockService.acquireLock(AbstractNoSqlLockService.java:155)
        at liquibase.nosql.lockservice.AbstractNoSqlLockService.waitForLock(AbstractNoSqlLockService.java:119)
        at liquibase.Liquibase$1.run(Liquibase.java:188)
        at liquibase.Scope.lambda$child$0(Scope.java:159)
        at liquibase.Scope.child(Scope.java:170)
        at liquibase.Scope.child(Scope.java:158)
        at liquibase.Scope.child(Scope.java:137)
        at liquibase.Liquibase.runInScope(Liquibase.java:1790)
        at liquibase.Liquibase.update(Liquibase.java:183)
        at liquibase.Liquibase.update(Liquibase.java:179)
        at liquibase.integration.commandline.Main.doMigration(Main.java:1543)
        at liquibase.integration.commandline.Main$1.lambda$run$0(Main.java:316)
        at liquibase.Scope.lambda$child$0(Scope.java:159)
        at liquibase.Scope.child(Scope.java:170)
        at liquibase.Scope.child(Scope.java:158)
        at liquibase.Scope.child(Scope.java:137)
        at liquibase.Scope.child(Scope.java:183)
        at liquibase.Scope.child(Scope.java:187)
        at liquibase.integration.commandline.Main$1.run(Main.java:315)
        at liquibase.integration.commandline.Main$1.run(Main.java:166)
        at liquibase.Scope.child(Scope.java:170)
        at liquibase.Scope.child(Scope.java:144)
        at liquibase.integration.commandline.Main.run(Main.java:166)
        at liquibase.integration.commandline.Main.main(Main.java:145)
Caused by: liquibase.exception.UnexpectedLiquibaseException: java.lang.ClassCastException: liquibase.configuration.LiquibaseConfiguration cannot be cast to liquibase.SingletonObject
        at liquibase.Scope.getSingleton(Scope.java:269)
        at liquibase.Scope.getSingleton(Scope.java:252)
        at liquibase.Scope.getSingleton(Scope.java:252)
        at liquibase.Scope.getSingleton(Scope.java:252)
        at liquibase.configuration.ConfigurationDefinition$Building.build(ConfigurationDefinition.java:323)
        at liquibase.ext.mongodb.configuration.MongoConfiguration.<clinit>(MongoConfiguration.java:23)
        ... 27 more
Caused by: java.lang.ClassCastException: liquibase.configuration.LiquibaseConfiguration cannot be cast to liquibase.SingletonObject
        at liquibase.Scope.getSingleton(Scope.java:266)
        ... 32 more

Not sure if this is a dependency/classpath issue. Directions appreciated
Running Liquibase 4.0.0


text:
Q: Why does named export lead to "Export default was not found"..error I'm trying to add the React useReducer() hook to an existing Redux project, and after a little bit of refactoring I get a compile error:
export 'default' (imported as 'estateAgent') was not found in './estateAgent'
Other questions about this message, such as
Export default was not found
explain how to declare a default export, but that's not what I need.  This is supposed to be a named export, and I don't know why React is expecting a default.
Here are some relevant code snippets.
The line that causes the error is in index.js:
import {EstateAgent}  from '../pages/EstateAgent'
(the curly braces mean that it's a named, not a default, export).  EstateAgent.jsx contains a container function which defines:
const EstateAgent = (props) => {...
(Going by a web example I'm reading, I changed the original container class EstateAgent to a function)
and the connector:
export const connectEstateAgent = connect(
  mapStateToProps,
  mapDispatchToProps
)(EstateAgent)

The lowercase "estateAgent" seems to mean a Redux file estateAgent.js which defines actions and a reducer and is imported by EstateAgent.jsx, but doesn't contain any default keyword or any entity actually named estateAgent, so I don't know how the error line came up with that name.  e.g.:
export const estateAgentReducer = (state = initialState, action) => {...

So, the question:  why is the compiler insisting that I'm trying to import a default export when I don't mean to?

A: The naming syntax I described is completely correct, but I was looking at the wrong import statement in a different index.js file.  The "EstateAgent" name was fine, but estateAgent is the name of a reducer method referenced in the redux subdirectory ./src/redux/index.js .  I had renamed this too out of an overabundance of caution and the error was at first masked by a different compile error.  When I updated the name in that file, it worked:
import {estateAgentReducer} from './estateAgent'
Takeaway:  the error message is pretty accurate, but overlapping file names and reuse of component names with different capitalization can be confusing for those like me who are still learning to navigate React.


text:
Q: Indentation not working for some paragraphs Some paragraphs in my document do not indent, what ever I try. I have solved some of them using the \parindent and \usepackage{indentfirst} but these specific ones do not seem to work. In those specific paragraphs, I include some math environments. Following each paragraph is a math environment on its own line.
Can someone tell me how to fix this?
Here is the code and subsequent pdf view:

The added code at the beginning of the document:


text:
Q: Clear examples for code smells does anybody know how the code smells "rigidity", "fragility", "immobility" and "viscosity" can be explained in short code examples?
I've found a lot of text but never a source code example.
Thanks for your hints.
Are there at least very pratical examples, like the following
- rigidity: "if the access permission is check at 100 code locations with an SQL statement". The resulting software has a high rigidity because the table for user permissions cannot be changed easily.
//UserInterface.java
// Check permission database
stmt.executeQuery("SELECT * FROM permission WHERE user='1')

//AdminInterface.java
// Check permission database
stmt.executeQuery("SELECT * FROM permission WHERE user='1')

A: Rigidity
The characteristic which makes the code difficult to change, where a small change in one part of the code leads to cascading changes in other parts.
There could be no short code example, since rigidity cannot exist in a small piece of code where there is nothing to cascade.
Your practical example with a SQL query repeated one hundred times through the code is not a sign of rigidity. It's simple code duplication, which, while indicative of poorly written code, doesn't make the maintenance overly complicated. Any IDE will let you find-replace text in all files in a folder, making a change in the query extremely simple—the opposite of what you claimed.
Imagine a different example. Originally, the permissions check was done through a query:
SELECT * FROM permission WHERE user='1'

The new requirements is to do it like this:
SELECT * FROM permission WHERE user='1' AND isDisabled=`false`

Exploring the code, it appears that the SQL query is built through a custom-made builder which supports the notion of user ID, but was never designed to handle isDisabled. You start by changing this, and discover that the builder uses a type conversion utility which handles strings and numbers, but not booleans. You add such support, but running the unit tests indicate that you've broken some other part of the code. You fix it, get back to the original assignment, and discover that in order to make it work, you need to change three other classes (and their respective tests), and now that the signature of one of the methods have changed, it requires you to modify ten more classes. Because of the rigidity, instead of doing one change in code and one change in tests, you affected half of the code base.
Fragility
class Probe
{
    static bool finished;

    public void Process()
    {
        while (true)
        {
            var measurement = this.ReadNext();
            if (measurement == null)
            {
                Probe.finished = true;
                break;
            }

            var results = this.Analyze(measurement);
            if (results.Relevant)
            {
                this.S3File.Append(results);
            }
        }
    }
}

// Somewhere else in the code, `Process` is called asynchronously.
// In parallel, the following code is executed every two seconds:
if (Probe.finished)
{
    // Alert the user that the probe finished sending the data.
}

Aside from the improper use of a static field, the major problem is that the field was made public and is accessed from the outside. Checking that the probe finished its measurements in this way makes the code particularly fragile; a change in the internals of the Probe class may break the code.
It would be much better to make the field private (and non-static) and let the caller of Process call this method synchronously and handle the termination of the method accordingly.
Immobility
While the previous piece of code may look like an example of immobility, the smell rather applies to larger blocks of code, and so, there could be no short code example for it.
You recognize it when you ask developers "could we add this simple feature to our booking system?" and they start avoiding eye contact and the most courageous of them scream "Not the booking system! Please, let us avoid what happened two years ago! I can't work once more sixteen hours per day for three weeks to restore all our business critical systems!"
Viscosity
// It would be too complex to use our Dependency Injection framework here, so
// let's create new instances directly for now. It makes it impossible to run unit
// tests for this class, so beware of regressions.
// TODO: Use Dependency Injection and add unit tests.
...


text:
Q: error: failed to initialize database, got error dial tcp :0: connectex: The requested address is not valid in its context I am trying to create an API in go language, but I get an error. How can this be resolved? I will post the error text.
error: failed to initialize database, got error dial tcp :0: connectex: The requested address is not valid in its context
failed to initialize database, got error dial tcp :0: connectex: The requested address is not valid in its context.
panic: DB Error: dial tcp :0: connectex: The requested address is not valid in its context.

goroutine 1 [running]:
ToDoList-Server/model.DBConnection()
        C:/Users/81804/enviroment/todo/ToDoList-Server/model/db.go:21 +0x225
main.main()
        C:/Users/81804/enviroment/todo/ToDoList-Server/main.go:10 +0x2a

package model

import (
    "database/sql"
    "fmt"
    "os"

    _ "github.com/go-sql-driver/mysql"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

var db *gorm.DB

// DB接続とテーブルを作成する
func DBConnection() *sql.DB {
    dsn := GetDBConfig()
    var err error
    db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        panic(fmt.Errorf("DB Error: %w", err))
    }
    CreateTable(db)
    sqlDB, err := db.DB()
    if err != nil {
        panic(fmt.Errorf("DB Error: %w", err))
    }
    return sqlDB
}

// DBのdsnを取得する
func GetDBConfig() string {
    user := os.Getenv("DB_USERNAME")
    password := os.Getenv("DB_PASSWORD")
    hostname := os.Getenv("DB_HOSTNAME")
    port := os.Getenv("DB_PORT")
    dbname := os.Getenv("DB_DBNAME")

    dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, password, hostname, port, dbname) + "?charset=utf8mb4&parseTime=True&loc=Local"
    return dsn
}

// Task型のテーブルを作成する
func CreateTable(db *gorm.DB) {
    db.AutoMigrate(&Task{})
}

A: try to format your dsn string as follows:
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s post=%s", hostname, user, password, dbname, port)


text:
Q: jquery-ajax-c# success function is executed but no response The post is fired and I can see the below in firebug
POST http://localhost:1148/WebSite2/frmMain.aspx/webDelete 200 OK 15ms

jQuery code is:
$.ajax({
   url: "frmMain.aspx/webDelete",
   type: "POST",
   dataType: "text",
   contentType:"text/plain",
   data: {id:"abc"},
   success: function(data){alert("success");alert(data)},
   error: function(){alert("failed");}
});

Then two alerts in the success function are fired but the second alert is empty
Server side coding:
[WebMethod][ScriptMethod]
public static string webDelete(string id)
{
    HttpContext context = HttpContext.Current;
    context.Response.ContentType = "text/plain";

    return id;
}

currently trying without the involvements of param, the error function is triggeres, no success
jquery code
$.ajax({

        url: "frmMain.aspx/webDelete",
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        async: true,
        success: function(data){alert("success");alert(data.d) },
        error: function(){alert("failed"); }

    } );

server code
[WebMethod][ScriptMethod]
public static string webDelete()
{
   return "hello";
}

firebug info:
Response Headers
Cache-Control   private
Connection          Close
Content-Length  11732
Content-Type    text/html; charset=utf-8
Date            Thu, 18 Jul 2013 09:47:34 GMT
Server          ASP.NET Development Server/8.0.0.0
X-AspNet-Version    2.0.50727

Request Headers
Accept          application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length  2
Content-Type    application/json; charset=utf-8
Host            localhost:1148
Referer         http://localhost:1148/WebSite2/frmMain.aspx
User-Agent          Mozilla/5.0 (Windows NT 5.2; rv:22.0) Gecko/20100101 Firefox/22.0
X-Requested-With    XMLHttpRequest

A: In order to see what's wrong.

*

*Debug webDelete() to see that id is actually 'abc'!
might be problem in parsing the form data...

*check the actual response using FireBug or Chrome F12

Try navigating to :
http://localhost:1148/WebSite2/frmMain.aspx/webDelete?id=myNeetID

*

*does this fire up the WebMethod?

*does this return myNeetID or a blank?

notice: you might need to Enable GET method.

A: If you use [WebMethod][ScriptMethod] in combination, you need to make some changes to your ajax call.
$.ajax({
   url: "frmMain.aspx/webDelete",
   type: "POST",
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   data: JSON.stringify({id:"abc"}),
   success: function(data){alert("success");alert(data.d)},
   error: function(){alert("failed");}
});

See:
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

A: Thank you all for your help ^_^
Was able to find an answer through this wonderful post!
jquery ajax with asp.net not working
Note: This isuue was caused by the .NET version problem


text:
Q: Basic Modal Logic question #1 Its about two weeks I have started Cresswell's "A New Introduction To modal Logic".
Now I've got a few questions on the text and I would deeply thank you if you help me clarify on them.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
The first among them will be as follows:
To prove $K$-Validity of the system $K$ (i.e. that every theorem of the system $K$ is $K$-Valid; or in other words, is valid in every frame $(W,R)$ ), the book is using induction on the set of theorems. So:
(a) It first tries to prove it for all valid formulas of Propositional Calculus (i.e. Tautologies of PC), plus the axiom $K$, are $K$-Valid; And
(b) it shows that the Transformation rules of the system $K$, preserve $K$-validity.

Now in part (a), to prove that every tautology of PC is $K$-Valid, the author argues in the following way:

In any model, a PC wff is evaluated in any world without reference to
  any other world. Therefore, since a valid wff has the value $1$ for
  every value-assignment to the variables, it has the value $1$ in every
  world in every model, i.e. it is valid on every frame.

But the author has defined validity of a formula in world, recursively, such that its base is such that if $V$ is a Value-assignmet, then "For any atomic formula $a$ , and any world $w$ ,either $V(a,w)=1$ or $V(a,w)=0$"
[And then he continues to define valuation of other formulas, recursively; that we don't care here]
So,the way the book shows is that: Value-assignmet are functions of form  $V: PROP\times W \longrightarrow  \{0,1\}$   that as we saw, are not dependent to any kind of valuation of propositions in PC.
So why the author argues as above, while there is no connection between valuations of formulas in PC and valuations of them (in worlds) in the system $K$?

A: The recursive definition of valuation of other formulas is the key. In particular, the valuation of formulas constructed using non-modal connectives only uses the valuation of the component formulas in the current world.
More precisely, for every modal valuation $V$ and every world $w$, you can define a PC-valuation $V_w$ by $V_w(a)=V(a,w)$, and then you can show by induction on the complexity of $\phi$ that if $\phi$ is a PC-formula, then $V(\phi,w)=V_w(\phi)$ (or, $w\models_V\phi\iff\models_{V_w}\phi$, or whatever notation Hughes and Cresswell use for valuation of compound formulas). If $\phi$ is a PC-valid, then $V_w(\phi)=1$, thus $V(\phi,w)=1$. Since $V$ and $w$ were arbitrary, $\phi$ is $K$-valid.

A: Well, i think the unclarity is more a matter of philosophy than math.
You said we can define the valuation of formulas in PC by combining it with the world conception.And
Then it results that a formula in PC is valid iff it is valid in every world.
Now the ambiguity arises here for me: When i am in the context of PC, i understand truth of an atomic proposition independent from
anything else[and then other formulas, recursively on them, by their definition of truth]. No tool in mathematical logic is to check the truth of an atomic proposition;
It's a matter of philosophy and theories of truth; and for example if we accept the Correspondence approach to truth, it's somehow a matter of corresponding to the
real world(take intuitively the "world" as what we are living in- or the state of affairs).
Now the question is that when we define the truth of PC formulas by the modal concept 'world'(Or as you said, a member of the arbitrarily chosen set W in a model)
and we say that for example v(a,w)=1 and v(a,w')=0 for an atomic formula a , what is the meaning of such assertions? What is the meaning of truth in a world here? I don't understand it neither mathematically nor non-mathematically!
Tell me if i am still unclear with the question.


text:
Q: Extracting .mat files with structs into Python I am new to python and am facing difficulty in extracting file data. So I have a .mat file which has the following output in Matlab:
d= open('tesla.mat')

d =
struct with fields:
diga: [1×1 struct]

d.diga.daten

ans =
struct with fields:
       Programmdauer: [1×78 double]
              SOCVec: [1×78 double]
            Spannung: [1×78 double]
         SpannungVec: [1×78 double]
               Strom: [1×78 double]
            StromVec: [1×78 double]
       TemperaturVec: [1×78 double]
   ThermischLeistung: [1×78 double]
ThermischLeistungVec: [1×78 double]

d.diga.daten.Spannung

ans =
Columns 1 through 20
4.0544    4.2100    4.2133    4.2149    4.2159    4.2168    4.2175    4.2181    4.2186    4.2191    4.0332    4.0265    4.0247    4.0235    4.0227    4.0223    4.0219    4.0217    4.0215    4.0213

Columns 21 through 40
4.0211    4.0210    4.0208    4.0552    4.0559    4.0561    4.0563    4.0564    4.0564    4.0564    4.0564    4.0564    4.0564    4.0564    4.0563    4.0563    4.0563    4.0563    4.0563    4.0563

Columns 41 through 60
4.0562    4.0562    4.0562    4.0562    4.0562    4.0562    4.0561    4.0561    4.0561    4.0561    4.0561    4.0561    4.0561    4.0561    4.0561    4.0560    4.0560    4.0560    4.0560    4.0560

Columns 61 through 78
4.0560    4.0560    4.0560    4.0560    4.0560    4.0560    4.0559    4.0559    4.0559    4.0559    4.0559    4.0559    4.0559    4.0559    4.0559    4.0559    4.0559    4.0559

I want to parse this data in python and extract this specific variable e.g Spannung data . The output in python is as follows :
{'__header__': b'MATLAB 5.0 MAT-file, Platform: x86_64-pc-linux-gnu, Created by: libmatio v1.5.9 on Mon Jul  6 20:29:51 2020', '__version__': '1.0', '__globals__': [], 'diga': array([[(array([[(array([[0.        , 0.10464944, 0.21018082, 0.31937647, 0.42176473,
    0.53570583, 0.6428233 , 0.74994078, 0.85705826, 0.96417574,
    1.0681423 , 1.17389392, 1.28139943, 1.40048611, 1.52559419,
    1.64743952, 1.76928485, 1.89113018, 2.        , 2.12290829,
    2.24581658, 2.36872488, 2.49163317, 2.59454399, 2.69687044,
    2.81347033, 2.93308651, 3.05714129, 3.17464839, 3.3055228 ,
    3.45267061, 3.58849168, 3.77533445, 3.88176795, 3.998157  ,
    4.19674602, 4.34787781, 4.5       , 4.69631901, 4.83781901,
    4.99708256, 5.20507697, 5.37073747, 5.5       , 5.6080527 ,
    5.78533992, 5.95166902, 6.09878942, 6.28218433, 6.4540618 ,
    6.59066557, 6.69357254, 6.8539116 , 6.95566133, 7.08274939,
    7.19399435, 7.3374617 , 7.44876399, 7.58496883, 7.70381522,
    7.83578215, 7.94780886, 8.08803463, 8.19780798, 8.34935696,
    8.45694731, 8.58460976, 8.69666891, 8.83509531, 8.94704739,
    9.08658847, 9.20783487, 9.33469661, 9.44355668, 9.59016133,
    9.6962619 , 9.85349258, 9.95928693]]), array([[88.3       , 88.30430713, 88.30865056, 88.3131448 , 88.31735886,
    88.32204841, 88.32645712, 88.33086583, 88.33527453, 88.33968324,
    88.34053444, 88.33956722, 88.33858396, 88.33749478, 88.33635052,
    88.3352361 , 88.33412169, 88.33300727, 88.33201153, 88.33088739,
    88.32976326, 88.32863912, 88.32751498, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846, 88.32743846, 88.32743846,
    88.32743846, 88.32743846, 88.32743846]]), array([[4.05436068, 4.21002405, 4.21327229, 4.21486158, 4.21591229,
    4.2168056 , 4.21748722, 4.21807606, 4.21860772, 4.21910362,
    4.03324528, 4.0265357 , 4.02467542, 4.02350034, 4.02273807,
    4.02225604, 4.02191832, 4.02166347, 4.02147603, 4.02129491,
    4.02113115, 4.020979  , 4.02083454, 4.05516985, 4.05587307,
    4.05613862, 4.05627884, 4.05635271, 4.05638517, 4.0563976 ,
    4.0563957 , 4.05638637, 4.05636811, 4.05635644, 4.05634327,
    4.05632056, 4.05630343, 4.05628649, 4.05626516, 4.05625018,
    4.05623371, 4.05621284, 4.0561967 , 4.05618439, 4.0561743 ,
    4.05615809, 4.05614328, 4.05613048, 4.0561149 , 4.05610068,
    4.05608961, 4.05608141, 4.05606887, 4.05606105, 4.05605142,
    4.05604313, 4.05603261, 4.05602458, 4.05601491, 4.0560066 ,
    4.05599751, 4.05598991, 4.05598053, 4.0559733 , 4.05596346,
    4.05595658, 4.05594852, 4.05594153, 4.05593303, 4.05592624,
    4.05591789, 4.05591073, 4.05590333, 4.05589706, 4.05588872,
    4.05588277, 4.05587405, 4.05586825]]), array([[4.05436068, 4.21002405, 4.21327229, 4.21486158, 4.21591229,
    4.2168056 , 4.21748722, 4.21807606, 4.21860772, 4.21910362,
    4.03324528, 4.0265357 , 4.02467542, 4.02350034, 4.02273807,
    4.02225604, 4.02191832, 4.02166347, 4.02147603, 4.02129491,
    4.02113115, 4.020979  , 4.02083454, 4.05516985, 4.05587307,
    4.05613862, 4.05627884, 4.05635271, 4.05638517, 4.0563976 ,
    4.0563957 , 4.05638637, 4.05636811, 4.05635644, 4.05634327,
    4.05632056, 4.05630343, 4.05628649, 4.05626516, 4.05625018,
    4.05623371, 4.05621284, 4.0561967 , 4.05618439, 4.0561743 ,
    4.05615809, 4.05614328, 4.05613048, 4.0561149 , 4.05610068,
    4.05608961, 4.05608141, 4.05606887, 4.05606105, 4.05605142,
    4.05604313, 4.05603261, 4.05602458, 4.05601491, 4.0560066 ,
    4.05599751, 4.05598991, 4.05598053, 4.0559733 , 4.05596346,
    4.05595658, 4.05594852, 4.05594153, 4.05593303, 4.05592624,
    4.05591789, 4.05591073, 4.05590333, 4.05589706, 4.05588872,
    4.05588277, 4.05587405, 4.05586825]]), array([[ 0. ,  4.5,  4.5,  4.5,  4.5,  4.5,  4.5,  4.5,  4.5,  4.5, -1. ,
    -1. , -1. , -1. , -1. , -1. , -1. , -1. , -1. , -1. , -1. , -1. ,
    -1. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
     0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
     0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
     0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
     0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
     0. ]]), array([[ 0. ,  4.5,  4.5,  4.5,  4.5,  4.5,  4.5,  4.5,  4.5,  4.5, -1. ,
    -1. , -1. , -1. , -1. , -1. , -1. , -1. , -1. , -1. , -1. , -1. ,
    -1. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
     0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
     0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
     0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
     0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,
     0. ]]), array([[25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25.,
    25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25.,
    25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25.,
    25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25.,
    25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25.,
    25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25., 25.]]), array([[0.00000000e+00, 6.85992309e-01, 7.03449743e-01, 7.10867829e-01,
    7.15615588e-01, 7.19174707e-01, 7.21389575e-01, 7.22912024e-01,
    7.24007563e-01, 7.24847258e-01, 4.45033989e-02, 3.85461248e-02,
    3.58360767e-02, 3.53935152e-02, 3.56460808e-02, 3.59131697e-02,
    3.60769536e-02, 3.61500744e-02, 3.61654153e-02, 3.61491829e-02,
    3.61153062e-02, 3.60739446e-02, 3.60309650e-02, 9.69429070e-04,
    5.35032457e-04, 3.58732548e-04, 2.92579042e-04, 2.64021521e-04,
    2.49466440e-04, 2.38203495e-04, 2.27951943e-04, 2.19594624e-04,
    2.09204995e-04, 2.03745280e-04, 1.98105959e-04, 1.89197221e-04,
    1.82955847e-04, 1.77092643e-04, 1.70083570e-04, 1.65383061e-04,
    1.60410350e-04, 1.54374091e-04, 1.49900760e-04, 1.46597195e-04,
    1.43952210e-04, 1.39825410e-04, 1.36175399e-04, 1.33110819e-04,
    1.29488217e-04, 1.26275854e-04, 1.23838901e-04, 1.22066587e-04,
    1.19407152e-04, 1.17780340e-04, 1.15810875e-04, 1.14141001e-04,
    1.12057839e-04, 1.10493479e-04, 1.08637272e-04, 1.07067274e-04,
    1.05375319e-04, 1.03979386e-04, 1.02281688e-04, 1.00989373e-04,
    9.92555314e-05, 9.80583899e-05, 9.66725802e-05, 9.54858692e-05,
    9.40565860e-05, 9.29290483e-05, 9.15576202e-05, 9.03953350e-05,
    8.92071874e-05, 8.82095618e-05, 8.68967397e-05, 8.59677815e-05,
    8.46224613e-05, 8.37375088e-05]]), array([[0.00000000e+00, 6.85992309e-01, 7.03449743e-01, 7.10867829e-01,
    7.15615588e-01, 7.19174707e-01, 7.21389575e-01, 7.22912024e-01,
    7.24007563e-01, 7.24847258e-01, 4.45033989e-02, 3.85461248e-02,
    3.58360767e-02, 3.53935152e-02, 3.56460808e-02, 3.59131697e-02,
    3.60769536e-02, 3.61500744e-02, 3.61654153e-02, 3.61491829e-02,
    3.61153062e-02, 3.60739446e-02, 3.60309650e-02, 9.69429070e-04,
    5.35032457e-04, 3.58732548e-04, 2.92579042e-04, 2.64021521e-04,
    2.49466440e-04, 2.38203495e-04, 2.27951943e-04, 2.19594624e-04,
    2.09204995e-04, 2.03745280e-04, 1.98105959e-04, 1.89197221e-04,
    1.82955847e-04, 1.77092643e-04, 1.70083570e-04, 1.65383061e-04,
    1.60410350e-04, 1.54374091e-04, 1.49900760e-04, 1.46597195e-04,
    1.43952210e-04, 1.39825410e-04, 1.36175399e-04, 1.33110819e-04,
    1.29488217e-04, 1.26275854e-04, 1.23838901e-04, 1.22066587e-04,
    1.19407152e-04, 1.17780340e-04, 1.15810875e-04, 1.14141001e-04,
    1.12057839e-04, 1.10493479e-04, 1.08637272e-04, 1.07067274e-04,
    1.05375319e-04, 1.03979386e-04, 1.02281688e-04, 1.00989373e-04,
    9.92555314e-05, 9.80583899e-05, 9.66725802e-05, 9.54858692e-05,
    9.40565860e-05, 9.29290483e-05, 9.15576202e-05, 9.03953350e-05,
    8.92071874e-05, 8.82095618e-05, 8.68967397e-05, 8.59677815e-05,
    8.46224613e-05, 8.37375088e-05]]))]],
  dtype=[('Programmdauer', 'O'), ('SOCVec', 'O'), ('Spannung', 'O'), ('SpannungVec', 'O'), ('Strom', 'O'), ('StromVec', 'O'), ('TemperaturVec', 'O'), ('ThermischLeistung', 'O'), ('ThermischLeistungVec', 'O')]),)]],
  dtype=[('daten', 'O')])}

what would be the code to write in python to extract specific array data .

A: OK I'm adding a second answer with a generalized little function that can extract data mat files with any type of fields inside, for people who may need it in the future (and even for myself, I am dealing with this question often and each time I build an ad-hoc solution...).
This function should be able to take in any mat file with structs and nested structs inside, and return a dictionary:
import scipy.io as sio

def load_from_mat(filename=None, data={}, loaded=None):
    if filename:
        vrs = sio.whosmat(filename)
        name = vrs[0][0]
        loaded = sio.loadmat(filename,struct_as_record=True)
        loaded = loaded[name]
    whats_inside = loaded.dtype.fields
    fields = list(whats_inside.keys())
    for field in fields:
        if len(loaded[0,0][field].dtype) > 0: # it's a struct
            data[field] = {}
            data[field] = load_from_mat(data=data[field], loaded=loaded[0,0][field])
        else: # it's a variable
            data[field] = loaded[0,0][field]
    return data

# and then just call the function
my_file = r"C:\Users\.......\data.mat"
data = load_from_mat(filename=my_file) # Don't worry about the other input vars (data, loaded), there are used in the recursion.

A: Loading matlab structs into python is a bit of a mess but the scipy.io.loadmat method can do it with a bit of exploration.
See help for scipy.io.loadmat. They explain how it works.
Start by loading the file:
import scipy.io as sio
my_struct = sio.loadmat(file_name)

Then, get the data from the dict:
my_struct.keys() # this will show you the var name of your data, in your case diga (if I understand correctly)
data = my_struct["diga"]

Now, for each level of nested structs you can use .dtype to see the next structs inside and then pull the data:
data.dtype
data[0,0]["daten"]

And then:
data[0,0,]["daten"][0,0]["Spannung"]

** I might have missed a level in your struct, play with it to see if it's not exactly fitting your struct.


text:
Q: Keep Masterlist of Objects in Array, check array if it exists before adding a new object The code below doesn't work as intended to. It never checks for the server in the master list. Am I doing something wrong?
var servers = [];
$.serverlist.addServers = function(jsonData) {
for (var server in servers) {
    if (server["ID"] == jsonData["ID"]) {
        // server exists, dont add, just update
    } else {
        //server doesnt exist, just add it
    }
}

The jsonData I'm receiving is formatted like so:
{ "ID": 1, "something else": "Value", "another key": "Key Val" }

So when it goes into the array, the array states (if there were multiple added)
[
 0:
   {
    "ID":1,
    "something else": "Value",
    "another key": "Key Val"
   }
  1:
   {
    "ID":2,etc...
   }
]

A: Try testing the array length.
if( servers.length > 0 ){
    // Server exist!
    console.log("Append!");
}else{
    // Doesn't...
    console.log("Create the array.");
}

EDIT
For a specific object, this should do:
if( servers.indexOf(jsonData["ID"]) != -1 ){
    // Data is in array
    console.log("It's there.");
}else{
    // Doesn't...
    console.log("It's not there.");
}

2nd EDIT
I made a CodePen of what it should look like.
But I'm not sure about your data... It looks like DOM object format when you console log it.
I think it's different than a json or an object...
I made my example based on an array of objects.
Look at CodePen console.
var servers = [
  {
    "ID":1,
    "something else": "Value",
    "another key": "Key Val"
   },
  {
    "ID":2,
    "something else": "another Value",
    "another key": "another Key Val"
   },
  {
    "ID":3,
    "something else": "Boring Value",
    "another key": "Interesting!"
   },
  {
    "ID":4,
    "something else": "arrggg.",
    "another key": "Yeah!"
   }
];

for(i=0;i<servers.length;i++){
  var temp = servers[i];
  if (temp.ID== 3){
    console.log("Found!");
    break;                  // Exits the loop when found ID = 3
  }else{
    console.log("NOT fount yet... Still checking.");
  }
}


text:
Q: startActivity(intent) not working when used along with data binding I have used data binding in my code. On using data binding startActivity(intent) is not taking me to the SecondActivity
MainActivity.java -
public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private Data data = new Data();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        binding.setData(data);
        binding.invalidateAll();

        data.setClickMe("Click Me");

        binding.button.setOnClickListener(view -> {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        });
    }
}

SeondActivity.java -
public class SecondActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private Data data = new Data();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_second);
        binding.setData(data);
        binding.invalidateAll();
        data.setHelloThere("Hello there");
    }
}

A: Apparently, I have made a silly mistake here
In SecondActivity.java -
on second line it should be -
private ActivitySecondBinding binding
rather than
private ActivityMainBinding binding


text:
Q: In prepared statement after SQLException on SQL Width in JAVA I have a problem with prepared statements in JDBC against an OpenEdge database, when we get the following exception:

java.sql.SQLException: [DataDirect][OpenEdge JDBC Driver][OpenEdge] Column Namn in table PUB.Brevlada has value exceeding its max length or precision.

I'm well aware of the fix for this with DBTool but I have another question. When we have used the prepared statement and got this Exception it can't be used again to fetch other entries in the table that hasn't got the width problem. We then get a slightly different exception:

java.sql.SQLException: [DataDirect][OpenEdge JDBC Driver][OpenEdge] Column %s in table %s has value exceeding its max length or precision (7864)

Is this a problem with the SQL Statement Cache on the server, and is there any workaround for this except for re-initialization of the JDBC connection to the database?


text:
Q: 301 / plus others , but not all urls We want to redirect most , but not all, of a website wit a 301 redirect.
Will this work or is the first line to much ?
redirect 301 / http://designers-floor.nl/
redirect 301 /index.php http://designers-floor.nl/
redirect 301 /index.php/woonbeton http://designers-floor.nl/inspiratie/

A: The Redirect directive will redirect any url starting with the first fragment to the second fragment. The first directive will thus redirect the entire site. (docs)
I recommend testing with temporary redirects until you have accomplished what you want, because testing with permanent redirects will cause those redirects to be cached. Once everything works as expected you can make the redirects permanent. Make sure that the most specific url is always listed first, so that it is matched first.
If you cannot accomplish your goal with just the Redirect directives, you can either use RedirectMatch (docs) or the RewriteEngine of mod_rewrite (docs).


text:
Q: Angularjs Hide error on page load I'm creating a form with numeric textbox that allows numbers between 12 to 30. In case, user types value other than this it should prompt an error. The following code works just like that. But I don't need this error when the page is loaded. How could I achieve it?
Code

    <title>Custom Form Validation</title>

<form name="myForm" >
    How old are you
        <input type="number"
               class="agee"
               required="required"
               min="12"  max="30"
               name="age"
               ng-model="user.age">

Age must lie between 12 to 30

<input type="submit" name="submit" value="Submit" ng-disabled="myForm.$invalid">
</form>

A: You have misspelled age by agee in
Age must lie between 12 to 30

         angular.module('formMod',[])
                .controller('formCont',[ function(){
                          this.valueContainer = 'Ms.';

                          this.shouldIshow = function(age){
                               return {
                                 castAway : (age >= 12) || (age <= 30),
                                 castIn : (age == null)
                               };
                          };
                }]);

    <title>Custom Form Validation</title>

<form name="myForm" >
    How old are you
        <input type="number"
               class="agee"
               required="required"
               min="12"  max="30"
               name="age"
               ng-model="user.age">

Age must lie between 12 to 30

<input type="submit" name="submit" value="Submit" ng-disabled="myForm.$invalid">
</form>

A: Figured it out.
ng-hide="myForm.agee.$pristine"

should be:
ng-hide="myForm.age.$pristine"

because age represents the element and agee represents the class in code.

A:
When you use form, you could try with input tag name[Here it is age.]
You should give a combination try. It should not be
  interacted[pristine] and not touched.

 Age must lie between 12 to 30


text:
Q: How can I display a web page as my Gnome screensaver? We'd like to change our screensavers to show the current status of our service at a glance. We already have a page that shows uptime, build status, and more as large red and green squares, and that page refreshes automatically.
We're all running Gnome. How can we make that page our screensaver?

A: try cutycap, a webkit based 'www-snapshoter':

CutyCapt is a small cross-platform command-line utility to capture WebKit's rendering of a web page into a variety of vector and bitmap formats, including SVG, PDF, PS, PNG, JPEG, TIFF, GIF, and BMP. See IECapt for a similar tool based on Internet Explorer.

then setup your screensaver application to pick up the snapshotted website pictures.

A: hmm ... maybe try the merger of what you both said ...
cron as "nobody" (or equivalent) every minute to run cutycapt into imagedir/date +nagios-%y-%m-%d_%T.jpg with auto-cleanup =
... * * * * * dir="/usr/share/admin/ScreenSaverDir" && a=date +$dir/nagios-%y-%m-%d_%T.png && CutyCapt --url=http://nagios.MyDomain.com/ --out=$a && && b=ls -1tr $dir | tail -1 && rm ls -1  $dir | egrep -v $b
so the most recent image is going to be the only thing in that directory but it will have a unique-to-the-second filename, guaranteeing that it will not be cached by the screensaver


text:
Q: What is the best way to handle empty [input type=date] cross-browser? I'm working on a web app at the moment which uses the HTML5 [input type=date] form element. As far as I know it's only supported in a few browsers at the moment: Chrome, Safari and Opera.
I'm focussing on support for Chrome and Safari primarily. I'm trying to detect whether a date has been entered or not but Chrome and Safari both treat blank dates differently. To Chrome, an empty date field's value is an empty string, but to Safari an empty date field's value is '0000-00-00'.
Is there any standard for detecting blank dates or am I just going to have to test as many different 'blank' formats as I can? I'd rather not since going forward I'd hate to have to keep adding formats to the list once other browsers like IE and Firefox support [input type=date] and go with their own blank format again....


text:
Q: javac reports "package does not exist" even though classpath is set I have a file Test.java (stripped down for debugging):
import com.github.tkutche1.jgrade.Grade;

I try compiling it with this command line and get an error:
# javac -cp lib/com/github/tkutche1/jgrade/Grade.class:. Test.java
Test.java:1: error: package com.github.tkutche1.jgrade does not exist
import com.github.tkutche1.jgrade.Grade;
                                 ^
1 error

The package does exist, as shown:
# javap lib/com/github/tkutche1/jgrade/Grade.class

Compiled from "Grade.java"
public interface com.github.tkutche1.jgrade.Grade extends java.lang.annotation.Annotation {
}

Here's what happens with the verbose command line option [with added line breaks]:
# javac -verbose -cp lib/com/github/tkutche1/jgrade/Grade.class:. Test.java
[parsing started RegularFileObject[Test.java]]
[parsing completed 15ms]
[search path for source files: lib/com/github/tkutche1/jgrade/Grade.class,.]
[search path for class files: /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/resources.jar,
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/rt.jar,/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/sunrsasign.jar,/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jsse.jar,/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jce.jar,
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/charsets.jar, /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfr.jar,/usr/lib/jvm/java-8-openjdk-amd64/jre/classes,/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/nashorn.jar,
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jaccess.jar,/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/sunpkcs11.jar,/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/sunjce_provider.jar,
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/localedata.jar,/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/icedtea-sound.jar,/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/dnsns.jar,
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/java-atk-wrapper.jar,/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/zipfs.jar,/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/cldrdata.jar, /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/sunec.jar,
lib/com/github/tkutche1/jgrade/Grade.class,.]
Test.java:2: error: package com.github.tkutche1.jgrade does not exist
import com.github.tkutche1.jgrade.Grade;
                                 ^
[total 111ms]
1 error

I am using javac 1.8.0_352 on Ubuntu. (I am trying to create a Gradescope autograder.)
I have read the answers to many similar questions, which say to include the .class file (or .jar file) in the classpath, which I have done. None of the questions have the output of javap showing that the package exists in the specified class.
What am I doing wrong?

A: The valid entries on the Java classpath are:

*

*Directories containing compiled package trees ... whose names match the package name structure

*Individual JAR files

*JAR file wildcards

Entries that are none of the above will be silently ignored.
You have put an individual .class file on the classpath.  It will be ignored.
Assuming that "lib" is a directory that contains "com/github/tkutche1/jgrade/Grade.class", your classpath should be:
$ javac -cp lib:. ....


text:
Q: enabling Spanning-Tree or not do you think is wise or stupid keeping the rapid spanning tree enabled for just two switches in this image? https://imgur.com/a/XI1NI
 As you can see the switches are not redundant each other but are connected simply because one has finished the ports avaible.
Two swithes can't generate a loop isn't it?
Thanks for any help.

A: You should only disable spanning tree if you do not use Layer2.
If all ports on your switch are Layer3 interfaces, you cannot have a loop and your endpoints are routed, each with a private subnet. Otherwise keep it on!
Update
There is a difference between OFF and not configured, with 2 switches I would leave them unconfigured, in most switches disabling RSTP may be possible, but STP will still be enabled.

A: You can disable STP but you shouldn't.
Why? When someone connects two switch ports together your network will go down without STP. Leaving it on doesn't hurt a bit.

A: As you have just 2 switches, connected with single cable, you can disable STP.
However the STP can prevent your environment from accidential loop caused by inserting another cable to both switches making additional path. The overhead of STP is really low these days. If you're sure that such a possibility won't happen or is very very unlikely, disable STP. Otherwise leave it running.

A: So what happens if someone inadvertently makes another connection between the switches? What happens when you add a third switch and forget that STP is disabled on the first two?
There's no good reason to disable STP.


text:
Q: Prevent django send_mail timimg attack I have different REST-API views where I either send a mail (if an account exists) or do not send a mail.
For example, the user can input the email in the forgot-password form and a mail is sent if the account exists.
I am using from django.core.mail import send_mail to send the mail.
The problem is, that this takes some time, and so requests for valid emails are generally longer than requests for non-exiting emails.
This allows an attacker to compare the request times to find out if an account exists or not.
Is there any way that I can call send_mail() without sending the mail?
Or what would be the fix to make request times equally long for both cases?
Note: I could check how long send_mail() needs on average and wait this time if I do not send the mail. As the app runs on different servers with different configs, this can not be generally done in my case. I would rather not store the average execution time per server in a database to solve this.

A: It's a common practice to use celery for tasks that require some time to be finished. Celery will run a task in a separate thread and a user doesn't need to wait while it is finished. In your specific case what will happen if you use celery:

*

*You send a task send_mail to celery and immediately return a successful response to a user.

*Celery receives a task and runs it in a separate thread.

In this way, the response time for both cases will be the same.

A: So this is something similar to an issue I had, and my solution was actually to always send the email, but the email reads something like You tried to reset your password, but this email isn't registered to an account with us. if they don't have an account.
From a user's perspective, it can be annoying to have to wait for an email that may or may not arrive, and spend time checking spam/junk etc. Telling them they don't have an account with that email address is quicker and cleaner for them.
We saw a big drop in users enquiring with us about why they hadn't received a PW reset email.
(Sorry for not actually answering the question, I dislike it when people do this on SO but since I experienced the same issue, I thought I'd weigh in.)


text:
Q: How to unit test a function that executes SQL without affecting the db in Python? I am struggling to unittest a function that doesn't return anything and executes delete operation. The function is as follows:
    def removeReportParseData(self, report_id, conn=None):
        table_id = dbFind(
            "select table_id from table_table where report_id=%s", (report_id), conn
        )
        for t in table_id:
            self.removeTableParseData(int(t["table_id"]), conn)
            dbUpdate("delete from table_table where table_id=%s", t["table_id"], conn)

I want to make sure that the commands were executed but don't want to affect the actual db. My current code is:
    def test_remove_report_parse_data(self):
        with patch("com.pdfgather.GlobalHelper.dbFind") as mocked_find:
            mocked_find.return_value = [123, 232, 431]
            mocked_find.assert_called_once()

Thank you in advance for any support.

A: I don't believe it is possible to execute SQL without executing it, so to speak, however if you are on MySQL you might be able to get fairly close to what you want by wrapping your queries in START TRANSACTION; and ROLLBACK;
i.e. you might replace your queries with:
START TRANSACTION;
YOUR QUERY HERE;
ROLLBACK

This will prove that your function works without actually changing the contents of the database.
However, if it is sufficient to simply test that these functions would execute ANY query, you could alternatively opt to test them with empty queries, and simply assert that your dbFind and dbUpdate methods were called as many times as you would expect.
Again, though, as I alluded to in my comment, I would strongly suggest NOT having your test suite interact with even your development database.
While there is certainly some configuration involved in setting up another database for your tests, you should be able to find some boilerplate code to do this quite easily as it is very common practice.


text:
Q: Javascript - Populando um campo com parágrafo Estou elaborando um javascript para popular uma caixa de texto, porém me deparei com uma situação que está me gerando dificuldade. Preciso popular com essa mensagem por exemplo:
TESTE
TESTE
TESTE
Porém não estou conseguindo trazer as quebras de linha quando populo o campo, tentei com /n,
,
, vbCrLf, porém não obtive êxito. Alguém poderia me ajudar.
Ressaltando que minha caixa de texto em html está assim:

            <textarea id="teste" class="CaixaTexto" runat="server" style="width: 600px;
                height: 90px;" cols="97" rows="5"></textarea>

Att,

A: Usa .replace(/\r?\n/g, '
'), exemplo:

  var txtBox = $('textarea');
txtBox.keydown(function(e){
    var that = this;
    setTimeout(function(){
        var html = that.value.replace(/\n/g,"
");
        $("div").html(html);
    },10);
});

<textarea></textarea>

A: Você disse que testou /n, quando na verdade deveria ser \n ou \n\r.


text:
Q: Open Source XSS Prevention Script I am looking for damn good open source XSS prevention script to implement in my php mvc framework.
Any ideas?

A: Its not quite what you are asking for, but check out: http://code.google.com/p/owasp-esapi-php/

A: You might check out the AntiSamy project, managed by the Open Web Application Security Project (OWASP).
It's named AntiSamy after Samy Kamkar, creator of the MySpace worm.
http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project

A: Although this is not for PHP it could at least give you some ideas for writing your own code. I suppose PHP has the same built in functions to validate/parse URL, encode HTML, etc ...
See if that helps you at all ....


text:
Q: HTML Anochor tag breaks into new line When I add HTML Anchor tag on any word in my web page, it breaks into new line.
The paragraph
A Web Page is a Hypertext Document
becomes like this
A Web Page is a
Hypertext
Document

When link is set to Hypertext with the following code
What is Web Page?

This is my HTML Code

A Web Page is a Hypertext Document written in    any Markup Language . HTML is a  Markup Language  which is mostly used in Web Page designing.

This is my CSS Code
body{background-color:rgba(196,213,220,0.05)}#body{min-height:90vh}a{text-decoration:none!important;outline:none!important;display:block}.flex-center{align-items:center;display:flex;justify-content:center}a.link{color:#636b6f;padding:0 25px;font-size:12px;font-weight:600;letter-spacing:.1rem;text-decoration:none;text-transform:uppercase;font-family:'Raleway',sans-serif}.padding-top-bottom-thirty{padding-top:10px;padding-bottom:15px}.mainhead{border-bottom:1px solid rgba(224,98,47,0.39);
What is the Problem?

A: display:block in your CSS is causing your problem. Just remove it:
a {
  text-decoration: none!important;
  outline: none!important;
}

body {
  background-color: rgba(196, 213, 220, 0.05)
}
#body {
  min-height: 90vh
}
a {
  text-decoration: none!important;
  outline: none!important;
}
.flex-center {
  align-items: center;
  display: flex;
  justify-content: center
}
a.link {
  color: #636b6f;
  padding: 0 25px;
  font-size: 12px;
  font-weight: 600;
  letter-spacing: .1rem;
  text-decoration: none;
  text-transform: uppercase;
  font-family: 'Raleway', sans-serif
}
.padding-top-bottom-thirty {
  padding-top: 10px;
  padding-bottom: 15px
}
.mainhead {
  border-bottom: 1px solid rgba(224, 98, 47, 0.39);

A Web Page is a Hypertext Document written in any Markup Language . HTML is a  Markup Language  which is mostly used in Web Page designing.


text:
Q: Is a regression more accurate using age/sex/race normalized scores or raw scores, but controlling for age/sex/race? I am having trouble conceptualizing normalizing versus controlling for variables and would appreciate some education on the matter.
For example, you want to do a regression with two variables:

*

*Hunger, which is how long you have gone without food.

*Working Memory, which is your score on a test of working memory.

You hypothesize that the amount of time you have gone without food will result in worse working memory, thus a negative relationship will be created: The more more hungry you are, the worse your working memory will be.
So, say you have reason to believe that Age, Sex, and Race all could be influencing both your working memory score and how hungry your participants are. You also have access to a database that can norm your working memory score, based on a large sample of healthy controls. What would you say are the correct methods for further analysis?

*

*You run a regression on the raw WM scores and the raw Hunger scores, but you control for Age, Race, Sex.

*You run a regression with age/sex/race normalized WM scores and the raw hunger scores, but do not control for any variables.

*You run a regression with age/sex/race normalized WM scores and the raw hunger scores, but you still control for age, sex, and race.
I would greatly appreciate the community's wisdom on this matter and references where you can supply them, so I can better understand what is going on.

A: If by "controlling" you mean put them in one multiple regression, and by "normalized WM scores" you mean WM scores that have, in some way, been adjusted for the effect other predictors, I would say 1) is clearly the best. Reason: you state you include the other predictors because they may be confounding = correlated with hunger. But this also means that, when trying to normalize the response without considering hunger, you also have a confounding problem, i.e. you could take out the effect of hunger through the normalization.


text:
Q: Javascript function not getting called when ' (single quote)is present I am calling javascript function through:
    <a href='javascript:void(0)' onclick='javascript:onEditRevPrepare("<%#
Convert.ToString(Eval("ReviewTitle")))%>")'>

When single quot (') is present in  Eval("ReviewTitle") its not calling the function.
I tried with:
Convert.ToString(Eval("ReviewTitle"))).Replace("'","\")

But this does not worked.
Also tried with:
 <a href='javascript:void(0)' onclick='javascript:onEditRevPrepare(""<%#
    Convert.ToString(Eval("ReviewTitle")))%>"")'>

But this also not worked.
EDIT
As and when i add ' or / in replace i stops getting line of javascript , which indicates function calling is not correct:

Please look at the broken line after replace

A: At it's simplest, you could
//Convert.ToString(Eval("ReviewTitle"))).Replace("'","\") //broken
  Convert.ToString(Eval("ReviewTitle"))).Replace("'","\\'").Replace("\"","\\\"")

However, you really should look at javascript encoding for a more robust solution.


text:
Q: Github migrate repo to organization and keep branch personal I have a public personal repository on Github. It has the following branches:
master
2.x
3.x

The master branch is currently the release branch and it is based of the 2.x branch.
I am building new features in the 3.x branch with breaking changes - however it is not ready to be public as yet (again due to things breaking).
I want to transfer this repository to an organization and work separately on the 3.x branch privately in my account.
What would be a good strategy to separate them? Any help is appreciated. If this post belongs elsewhere - please direct me and I will post it there.


text:
Q: a struct with a flexible array member in another struct Is something like the code below valid?
struct foo {
    int a;
    int b[];
};

struct bar {
    int c;
    struct foo d;
};

struct bar *x = malloc(sizeof(struct bar) + sizeof(int [128]));

It seems ok to me, but I am a bit skeptical because compiler does not complain if I do:
struct bar {
    struct foo d;
    int c;
};

A: It's not okay. Section 6.7.2.1 (in n1570), point 3 says

3 A structure or union shall not contain a member with incomplete or function type (hence,
  a structure shall not contain an instance of itself, but may contain a pointer to an instance
  of itself), except that the last member of a structure with more than one named member
  may have incomplete array type; such a structure (and any union containing, possibly
  recursively, a member that is such a structure) shall not be a member of a structure or an
  element of an array.

So a struct with a flexible array member may not be part of another struct.
(It may well work as the last member of a struct, though, if the compiler accepts it.)


text:
Q: How to use regex to split set-cookie header How would I use regex to split the set-cookie header into name and value:
Eg. test_cookie=Cookie+check; path=/; domain=.Site.com
name: test_cooke
value: Cookie+check; path=/; domain=Site.com

A: This would have the name in the first group, and value in the second
Dim r as Regex = new Regex("(.+?)=(.+)")
Dim cookie as string = "test_cookie=blah;bleh"
Dim name as string = r.Match(cookie).Groups(1).ToString()
Dim value as string = r.Match(cookie).Groups(2).ToString()


text:
Q: How to parse INI file? I have ini files that contains data from server.
Map.ini
[MAP_1]
MapType = 1
MapWar = 1
Position = 42.03,738.2,737.3

[MAP_2]
MapType = 1
MapWar = 1
Position = 42.03,738.2,737.3

How to read map.ini that contains this kind of files and save it in Dictionary or List.

A: Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            List<Map> maps = new List<Map>();
            Map map = null;
            StreamReader reader = new StreamReader(FILENAME);
            string line = "";
            while ((line = reader.ReadLine()) != null)
            {
                line.Trim();
                if (line.Length > 0)
                {
                    if(line.StartsWith("["))
                    {
                        string name = line.Trim(new char[] { '[', ']' });
                        map = new Map();
                        maps.Add(map);
                        map.name = name;
                    }
                    else
                    {
                        string[] data = line.Split(new char[] { '=' });
                        switch (data[0].Trim())
                        {
                            case "MapType" :
                                map.mapType = int.Parse(data[1]);
                                break;
                            case "MapWar":
                                map.mapWar = int.Parse(data[1]);
                                break;
                            case "Position":
                                string[] numbers = data[1].Split(new char[] { ',' });
                                map.x = decimal.Parse(numbers[0]);
                                map.y = decimal.Parse(numbers[1]);
                                map.z = decimal.Parse(numbers[2]);
                                break;
                            default :
                                break;
                        }
                    }
                }
            }
            Dictionary<string, Map> dict = maps
                .GroupBy(x => x.name, y => y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
    public class Map
    {
        public string name { get; set; }
        public int mapType { get; set; }
        public int mapWar { get; set; }
        public decimal x { get; set; }
        public decimal y { get; set; }
        public decimal z { get; set; }
    }
}


text:
Q: Magento-2 How to exclude category products from catalog search results I need to change catalog search product results collection, exclude some categories from catalog search results.
Anyone know how to apply category filters in search results.
Thanks


text:
Q: Why does std::vector::get_allocator() return by-value? To my surprise, I got an error when trying to use std::vector::get_allocator() with an non-copyable allocator. Why does std::vector::get_allocator() return by-value and not by-reference?
template<typename T>
class nc_allocator {
public:
    using value_type = T;

    nc_allocator(nc_allocator const&) = delete;
    nc_allocator& operator=(nc_allocator const&) = delete;

    // Other required members.
};

std::vector<int, nc_allocator<int>> v;
// boom: use of deleted function
//           'nc_allocator<T>::nc_allocator(const nc_allocator<T>&) [with T = int]'
v.get_allocator();

A:
I got an error when trying to use std::vector::get_allocator() with an non-copyable allocator.

The standard forbids you to do so.  The allocator requirements in 17.6.3.5 state that an allocator shall be copyable.
X a1(a);         Shall not exit via an exception.
                 post: a1 == a
X a1(move(a));   Shall not exit via an exception.
                 post: a1 equals the prior value
                 of a.

So return by value is a correct way of returning an allocator, concerning the allocator requirements defined by the standard.
I'm not sure why this is a requirement but if noncopyable allocators would have been allowed, the empty base optimization would no more work.

A: The standard simply dictates so:

[C++11: 23.2.1/7]: [..] In all container types defined in this Clause, the
  member get_allocator() returns a copy of the allocator used to construct the container or, if that allocator has been replaced, a copy of the most recent replacement [..]

I suspect @Vaughn's correct in his hypothesis that allocators are meant to be used as "handles".
By very loose analogy, would you ever write a non-copyable functor for use with standard algorithms?


text:
Q: Соотнесение столбцов dataframe pandas Всем привет! Есть два датафрейма с разной структурой:
df_old = pd.DataFrame(columns=['id','old_col1','old_col2', 'old_col3', 'old_col4'])
df = pd.DataFrame(columns=['id','col1','col2'])

Требуется перенести данные из df_old в df через append по такой логике:
df['id'] = df_old['id']
df['col1'] = df_old['old_col2']
df['col2'] = df_old['old_col3']

Нужно как то записать эту логику в вызове append, но не понимаю как.
Вариант перестроить df_old не сработает в данной ситуации, так как данные переносятся из df_old в df по определенной логике с использованием append для каждой строки фрейма.
Вызываю данную логику через apply:
def makeList(x, course_name):
  if (x['old_col4'] == 1):
    df.append(x) # тут нужно средактировать append так, чтобы df['col1'] соотностился с df_old['old_col2]
  else:
    if (len(df[df['id'] == x['id']]) != 0):
      if (x['old_col2'] == course_name):
        df_result[df_result['id'] == x['id']]['col2'] = x['old_col2']
      else:
        df_result[df_result['id'] == x['id']]['col2'] = x['old_col3']
    else:
      if (x['old_col2'] == course_name):
        df_result.append(x) # тут нужно средактировать append так, чтобы df['col1'] соотностился с df_old['old_col2]
      else:
        df_result.append(x) # тут нужно средактировать append так, чтобы df['col1'] соотностился с df_old['old_col3]
  return x


text:
Q: My calendar won't work on my iPhone 4 since upgrading to iOS8. I am unable to save events All my history and future events (except birthdays attached to my contacts) are gone and I can't save new events.  When I view my calendar in iCloud from my computer they are all there.  They're just not syncing with my phone!  I don't have my calendar in my phone synced to any other calendar either. How can I resolve this?

A: I struggled with this for quite a while. Out of nowhere, I could not add any events or reminders to my calendar, and the (+) in the corner of my calendar was grey. Super frustrating!
Go under settings. Select Mail, Contacts, Calendars.  You must click on individual accounts, and move the slider for calendar to the "on" position. For instance, I have an iCloud account, and multiple gmail accounts listed. I clicked on each account, and turned on all of the calendar sliders.
This fixed the problem, and I am now able to add events, and view birthdays and events.

A: To save new events to your Calendar go to Settings > Mail, Contacts, Calendars.
I clicked on Hotmail and then turned on Calendars. After that the gray + went red and I can now save events again.


text:
Q: How to create Layout Topside ribbon on android app I want to create a layout with ribbon for my android app layout but the ribbon goes behind the image immediately it fetches data / image from server. this is my layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/spacing_medium"
    android:clipToPadding="false"
    app:cardBackgroundColor="@android:color/white"
    app:cardCornerRadius="@dimen/card_radius"
    app:cardElevation="@dimen/card_elevation"
    app:cardUseCompatPadding="false">

    <com.balysv.materialripple.MaterialRippleLayout
        android:id="@+id/lyt_parent"
        style="@style/RippleStyleBlack"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/grey_40">

                <ImageView
                    android:layout_width="@dimen/product_item_img"
                    android:layout_height="@dimen/product_item_img"
                    android:src="@drawable/loading_placeholder"
                    android:tint="@color/grey_60" />

                <ImageView
                    android:text="RED"
                    android:id="@+id/down_ribbon"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_gravity="right|top"
                    android:src="@drawable/ic_top_ad_right"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentRight="true"
                    />

                <ImageView
                    android:id="@+id/image"
                    android:layout_width="match_parent"
                    android:layout_centerInParent="true"
                    android:layout_height="150dp"
                    android:scaleType="centerCrop" />

            </RelativeLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="2px"
                android:background="@color/grey_5" />

        </LinearLayout>

    </com.balysv.materialripple.MaterialRippleLayout>

</android.support.v7.widget.CardView>

The first imageView above is the background The second Imageview is the ribbon and the third imageView is for the image gotten from the server.
My Question is how will i make image Ribbon come in front of the image after and before it fetches it from the server. Thanks

A: THe problem is that the ribbon imageView should come last since all of them are at the same RelativeLayout see the correct code below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/spacing_medium"
    android:clipToPadding="false"
    app:cardBackgroundColor="@android:color/white"
    app:cardCornerRadius="@dimen/card_radius"
    app:cardElevation="@dimen/card_elevation"
    app:cardUseCompatPadding="false">

    <com.balysv.materialripple.MaterialRippleLayout
        android:id="@+id/lyt_parent"
        style="@style/RippleStyleBlack"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/grey_40">

                <ImageView
                    android:layout_width="@dimen/product_item_img"
                    android:layout_height="@dimen/product_item_img"
                    android:src="@drawable/loading_placeholder"
                    android:tint="@color/grey_60" />

                <ImageView
                    android:id="@+id/image"
                    android:layout_width="match_parent"
                    android:layout_centerInParent="true"
                    android:layout_height="150dp"
                    android:scaleType="centerCrop" />

                <ImageView
                    android:text="RED"
                    android:id="@+id/down_ribbon"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_gravity="right|top"
                    android:src="@drawable/ic_top_ad_right"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentRight="true"
                    />

            </RelativeLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="2px"
                android:background="@color/grey_5" />

        </LinearLayout>

    </com.balysv.materialripple.MaterialRippleLayout>

</android.support.v7.widget.CardView>


text:
Q: Setting Vim whitespace preferences by filetype At my work, I am required to follow the house style for indentation, which goes as follows:

*

*2 spaces when coding html and ruby

*tabs when coding javascript, with tabwidth=4 recommended

What is the best way to specify different whitespace preferences per filetype?

A: Peter's answer is straightforward enough, but unfortunately the options aren't right. You need to use the following options instead:
autocmd Filetype html setlocal ts=2 sw=2 expandtab
autocmd Filetype ruby setlocal ts=2 sw=2 expandtab
autocmd Filetype javascript setlocal ts=4 sw=4 sts=0 noexpandtab

Also note:

*

*You can make vim show tab characters by using :set list.

*Once you have the tab/space options set correctly, you can make vim repair the file (replace spaces with tabs or vice versa) using the :retab! command.

A: +1 to Peter's answer, but Vim provides another solution as well. If you want to do something more complicated than a single setlocal, like setting up a whole bunch of options, commands, and mappings at once, then vim's filetype plugin feature comes to the rescue.
You need to have filetype plugin on or filetype plugin indent on in your .vimrc, and then to create a plugin for e.g. ruby you can create ~/.vim/ftplugin/ruby.vim. Technically you can use any commands you like in here, to be run when a Ruby file is loaded, but the recommended ones include setlocal, map <buffer>, command -buffer, and defining functions. Lots more information is in the User Guide; if you're pretty familiar with scripting vim then jump to :help 41.11, otherwise read :help usr_40 and :help usr_41.

A: there are many ways, but here's a simple, easy to understand way. add these lines to your ~/.vimrc:
autocmd FileType html setlocal ts=2 sts=2 sw=2
autocmd FileType ruby setlocal ts=2 sts=2 sw=2
autocmd FileType javascript setlocal ts=4 sts=4 sw=4

A: There's also a nice vim script: DetectIndent which tries to detect the indentation of a file that you open.
It's very handy if you work with many files with different coding style.
I use an autocommand in my .vimrc:
:autocmd BufReadPost * :DetectIndent

A: To insert space characters whenever the tab key is pressed, set the 'expandtab' option:
:set expandtab

Next step is to control the number of space characters that will be inserted when the tab key is pressed, set the 'tabstop' option. For example, to insert 2 space for a tab, use:
:set tabstop=2

ref: http://vim.wikia.com/wiki/Converting_tabs_to_spaces


text:
Q: How to get browser to ignore one row when computing table width Say I have a table with one column per row, where the cells contain text.  One of the rows has much longer text than the others.  I'd like to display a table where that row is not taken into consideration when the table width is computed; that is, the width would be the same as if that long row were removed.  The long text would then be wrapped over several lines.
Example:

      <title>tabtest</title>

Veni, vidi, vici

All's well that ends well

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Let them eat cake

This makes the table width the entire width of the browser window (with the really long text wrapping over 3 lines).  This isn't what I want.  I'm trying to get it displayed so that the table width is based on the second row (the longest of the remaining three rows).  The third row would then wrap over many lines (which is ugly, but it won't be so bad in the real-life example I'm working on).
I've tried various combinations of width: inherit, width: 100%, word-wrap: break-word, either in the  for the long row or in singly- or doubly-nested
 elements inside that cell, but I haven't gotten anything to do what I want.


text:
Q: update_meta_user difference in i:1 and b:1, how to write b:1 This code leads to wp_cababilities being written to the database but with an i:1 in front.
if( $new_roles === 'administrator' ) {
    $capabilities = array ("administrator",'activate_plugins','delete_others_pages','delete_others_posts','delete_pages','delete_plugins','delete_posts','delete_private_pages','delete_private_posts','delete_published_pages','delete_published_posts','edit_dashboard','edit_files','edit_others_pages','edit_others_posts','edit_pages','edit_posts','edit_private_pages','edit_private_posts','edit_published_pages','edit_published_posts','edit_theme_options','export','import','list_users','manage_categories','manage_links','manage_options','moderate_comments','promote_users','publish_pages','publish_posts','read_private_pages','read_private_posts','read','remove_users','switch_themes','upload_files','create_product');
    $user->set_role('administrator');
    update_user_meta( $user_id, 'wp_capabilities', $capabilities );
    update_user_meta( $user_id, 'wp_user_level', 10 );
}

This is what is placed in the database:
a:39:i:0;s:13:"administrator";i:1;s:16:"activate_plugins";i:2;s:19:"delete_others_pages";i:3;s:19:"delete_others_posts";i:4;s:12:"delete_pages";i:5;s:14:"delete_plugins";i:6;s:12:"delete_posts";i:7;s:20:"delete_private_pages";i:8;s:20:"delete_private_posts";i:9;s:22:"delete_published_pages";i:10;s:22:"delete_published_posts";i:11;s:14:"edit_dashboard";i:12;s:10:"edit_files";i:13;s:17:"edit_others_pages";i:14;s:17:"edit_others_posts";i:15;s:10:"edit_pages";i:16;s:10:"edit_posts";i:17;s:18:"edit_private_pages";i:18;s:18:"edit_private_posts";i:19;s:20:"edit_published_pages";i:20;s:20:"edit_published_posts";i:21;s:18:"edit_theme_options";i:22;s:6:"export";i:23;s:6:"import";i:24;s:10:"list_users";i:25;s:17:"manage_categories";i:26;s:12:"manage_links";i:27;s:14:"manage_options";i:28;s:17:"moderate_comments";i:29;s:13:"promote_users";i:30;s:13:"publish_pages";i:31;s:13:"publish_posts";i:32;s:18:"read_private_pages";i:33;s:18:"read_private_posts";i:34;s:4:"read";i:35;s:12:"remove_users";i:36;s:13:"switch_themes";i:37;s:12:"upload_files";i:38;s:14:"create_product";}

These capabilities do not work for that user.
A simple copy/paste of the following into the database gives the user the capabilities
a:27:{s:13:"administrator";b:1;s:12:"delete_posts";b:1;s:22:"delete_published_posts";b:1;s:10:"edit_posts";b:1;s:20:"edit_published_posts";b:1;s:13:"publish_posts";b:1;s:4:"read";b:1;s:12:"upload_files";b:1;s:19:"delete_others_pages";b:1;s:19:"delete_others_posts";b:1;s:12:"delete_pages";b:1;s:11:"delete_post";b:1;s:20:"delete_private_pages";b:1;s:20:"delete_private_posts";b:1;s:22:"delete_published_pages";b:1;s:17:"edit_others_pages";b:1;s:17:"edit_others_posts";b:1;s:10:"edit_pages";b:1;s:18:"edit_private_pages";b:1;s:18:"edit_private_posts";b:1;s:20:"edit_published_pages";b:1;s:17:"manage_categories";b:1;s:12:"manage_links";b:1;s:17:"moderate_comments";b:1;s:13:"publish_pages";b:1;s:18:"read_private_pages";b:1;s:18:"read_private_posts";b:1;}

What is the difference between the i:1 and b:1 ? How can I get the update_meta_user to add the b:1?
I cannot find a document but curious if this is i for integer and b for boolean. In which case, how can I get this code to update the wp_cabailities database field?

A: Your first serialized string is broken. I can't spot why but you should not be trying to manipulate capabilities manually. You already have a user object. Use it.
if( $new_roles === 'administrator' ) {
  $capabilities = array ("administrator",'activate_plugins','delete_others_pages','delete_others_posts','delete_pages','delete_plugins','delete_posts','delete_private_pages','delete_private_posts','delete_published_pages','delete_published_posts','edit_dashboard','edit_files','edit_others_pages','edit_others_posts','edit_pages','edit_posts','edit_private_pages','edit_private_posts','edit_published_pages','edit_published_posts','edit_theme_options','export','import','list_users','manage_categories','manage_links','manage_options','moderate_comments','promote_users','publish_pages','publish_posts','read_private_pages','read_private_posts','read','remove_users','switch_themes','upload_files','create_product');
  $user->set_role('administrator');
  foreach ($capabilities as $cap) {
    $user->add_cap($cap);
  }
}

Untested but that should work. However, you should only need to explicitly add the capabilities not already implied by the role. You could make that capability array significantly shorter.