text:
Q: SQL Server: Find All Columns Across Multiple Databases Where a Substring Is Present I am working with a SQL Server that has multiple databases in its schema (let's call them alpha, beta, gamma, etc.).
I'm looking to go through each of these databases and find which columns have at least one value containing a certain substring (let's say it is "dog").
I know that if I want to check if a certain column (COLUMN_NAME) contains this substring I could use
WHERE COLUMN_NAME LIKE '%dog%'

and if the table that is returned is not empty, that column had the sub string and if the table is empty, there was no substring "dog."
For a more concrete example, let's say I have the table:

Person
Pet
Favorite Animal

Jack
Cat
Dog

James
Dog
Lion

I would want the result of my query to be (in some format) "Pet" and "Favorite Animal."
What I don't know is how to iterate over all of the columns (check if any values of each column has "dog"), let alone all of the columns of all of the databases.
How would I do this? Is this beyond the scope of a SQL query (in other words, should this be done in something like Python)?
(Edited for clarity of question.)

A: This is one way to do it with pure t-sql. It involves cursors and dynamic sql wich is best avoided if possible. First loop through all databases and get the columns of type varchar/nvarchar (you can add other types if you want like text/ntext). Then loop through all columns using dynamic sql to count rows that have a match.
Warning: Do not run this query on a big production environment as it can have serious impact on performance.
--Set the search query
DECLARE @search_query NVARCHAR(200) = '%dog%';

--Create temp output table
DROP TABLE IF EXISTS #columns;
CREATE TABLE #columns (
    _database_name NVARCHAR(4000),
    _schema_name NVARCHAR(4000),
    _table_name NVARCHAR(4000),
    _column_name NVARCHAR(4000),
    _count INT
);

/*
    1. Loop through all databases on server
    and get columns of type nvarchar och varchar
*/

DECLARE @database_name NVARCHAR(250);
DECLARE @sql NVARCHAR(MAX);

-- Create a cursor for database names except
DECLARE database_cursor CURSOR FOR
SELECT
    [name]
FROM sys.databases
WHERE
    --Modify this to exclude other databases
    name NOT IN ('SSISDB','master','tempdb','model','msdb');

OPEN database_cursor;

FETCH NEXT FROM database_cursor INTO @database_name;

-- Loop through the databases and insert columns in temp-table
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = CONCAT(
        '
        INSERT INTO #columns (_database_name,_schema_name,_table_name,_column_name)
        SELECT ''',
            @database_name,''' database_name,
            s.name schema_name,
            t.name table_name,
            c.name column_name
        FROM [',@database_name,'].sys.all_objects t
        JOIN [',@database_name,'].sys.schemas s
        ON t.schema_id = s.schema_id
        JOIN [',@database_name,'].sys.all_columns c
        ON t.object_id = c.object_id
        JOIN [',@database_name,'].sys.types ty
        ON c.user_type_id = ty.user_type_id
        WHERE
            ty.name IN (''nvarchar'',''varchar'') AND
            is_ms_shipped = 0 AND
            t.type = ''U''');

    EXEC (@sql);

    FETCH NEXT FROM database_cursor INTO @database_name;
END

CLOSE database_cursor;
DEALLOCATE database_cursor;

/*
    Step 2: Loop through the columns of all
    databases, count ocurrences of the query
    and add to temp table
*/
DECLARE @column_name NVARCHAR(4000),@table_name NVARCHAR(4000);
DECLARE column_cursor CURSOR FOR
SELECT
CONCAT('[',_column_name,']'),
CONCAT('[',_database_name,'].[',_schema_name,'].[',_table_name,']')
FROM #columns

OPEN column_cursor;
FETCH NEXT FROM column_cursor INTO @column_name, @table_name;
WHILE @@FETCH_STATUS = 0
BEGIN

    SET @sql = CONCAT('UPDATE columns
    SET _count = row_search._count
    FROM #columns columns
    JOIN (
    SELECT
    COUNT(*) _count
    FROM ',@table_name,'
    WHERE ',@column_name,' LIKE ''',@search_query,'''
    ) row_search ON 1=1
    WHERE
        CONCAT(''['',_database_name,''].['',_schema_name,''].['',_table_name,'']'') = ''',@table_name,''' AND
        CONCAT(''['',_column_name,'']'') = ''',@column_name,''''
    )
    ;
    EXEC (@sql);
FETCH NEXT FROM column_cursor INTO @column_name,@table_name;
END

CLOSE column_cursor;
DEALLOCATE column_cursor;

;
--Final output
SELECT
    _database_name [Database],
    _schema_name [Schema],
    _table_name [Table],
    _column_name [Column],
    _count [Count]
FROM #columns


text:
Q: CheckAccessCore not being called in custom ServiceAuthorizationManager I am working on a WCF REST service that will be hosted within Azure and want to check the user id. To this end I have created a custom ServiceAuthorizationManager.
namespace SecureService
{
    public class AccessControlServiceAuthorizationManager : ServiceAuthorizationManager
    {
        String serviceNamespace      = String.Empty;
        String acsHostname           = String.Empty;
        String trustedTokenPolicyKey = String.Empty;
        String trustedAudience       = String.Empty;

        public AccessControlServiceAuthorizationManager()
        {
            try
            {
                serviceNamespace      = RoleEnvironment.GetConfigurationSettingValue("serviceNamespace");
                acsHostname           = RoleEnvironment.GetConfigurationSettingValue("acsHostname");
                trustedTokenPolicyKey = RoleEnvironment.GetConfigurationSettingValue("trustedTokenPolicyKey");
                trustedAudience       = RoleEnvironment.GetConfigurationSettingValue("trustedAudience");
            }
            catch
            {
                GenerateErrorResponse();
            }
            finally
            {

            }
        }                                   // end AccessControlServiceAuthorizationManager() Constructor

        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            String headerValue = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Authorization];
            String token = String.Empty;
            string[] nameValuePair = null;
            TokenValidator validator = null;

            if (String.IsNullOrEmpty(headerValue))
            {
                GenerateErrorResponse();
                return false;
            }

            if (!headerValue.StartsWith("WRAP "))
            {
                GenerateErrorResponse();
                return false;
            }

            nameValuePair = headerValue.Substring("WRAP ".Length).Split(new char[] { '=' }, 2);

            if (nameValuePair.Length != 2 ||
                nameValuePair[0] != "access_token" ||
                !nameValuePair[1].StartsWith("\"") ||
                !nameValuePair[1].EndsWith("\""))
            {
                GenerateErrorResponse();
                return false;
            }

            token     = nameValuePair[1].Substring(1, nameValuePair[1].Length - 2);
            validator = new TokenValidator(acsHostname, serviceNamespace, trustedAudience, trustedTokenPolicyKey);

            if (!validator.Validate(token))
            {
                GenerateErrorResponse();
                return false;
            }

            return true;
        }

        public void GenerateErrorResponse()
        {

        }
    }
}

My Web.config is as follows;

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <behaviors>
        <serviceBehaviors>
            <behavior name="Secure">
                <serviceAuthorization serviceAuthorizationManagerType="SecureService.AccessControlServiceAuthorizationManager" />
            </behavior>
        </serviceBehaviors>
        <endpointBehaviors>
            <behavior name="webBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <services>
        <service name="SecureService.Demo">
            <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" bindingConfiguration="" contract="SecureService.IDemo" />
            <endpoint address="rest" behaviorConfiguration="webBehavior" binding="webHttpBinding" bindingConfiguration="" contract="SecureService.IDemo" />
        </service>
    </services>
</system.serviceModel>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
        <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
</system.webServer>

However the CheckAccessCore() method does not seem to be called when I call the service via IE. So the question is how can I ensure it is called and therefore ensure that my users are validated.
I have put a break point in the CheckAccessCore and it never seems to get hit.
And just to make things really interesting - I will need to call this webservice from within Silverlight.
Thanks in advance

A: Following the configuration pasted above, I see that service behavior "Secure" is missed to apply on Service. Please check it, if it's not a typo...

A: Ignore your 'services' section in config. Try:
<standardEndpoints>
  <webHttpEndpoint>
    <standardEndpoint crossDomainScriptAccessEnabled="True" automaticFormatSelectionEnabled="true" helpEnabled="True"/>
  </webHttpEndpoint>
</standardEndpoints>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Elements not recognized by get_attribute('class') name In the following loop, im simply traversing a page;
element by element, and stopping to retrieve the URL of a button type only.
However my script was stopping on elements not true of the get_attribute('role') == 'button' check, which was quite frustrating.
As such I realized the class name for all of the buttons i needed as best shown here highlighted, were the same. Which would be insanely convenient to check for, however its not working at all.
What am i doing wrong?
if starting_element.get_attribute('role') == "button" and starting_element.get_attribute('class') == "x1i10hfl xjqpnuy xa49m3k xqeqjp1 x2hbi6w x972fbf xcfux6l x1qhh985 xm0m39n x9f619 x1ypdohk xe8uvvx xdj266r x11i5rnm xat24cr x1mh8g0r x2lwn1j xeuugli x16tdsg8 xggy1nq x1ja2u2z x1t137rt x6s0dn4 x1ejq31n xd10rxx x1sy0etr x17r0tee xdl72j9 x1q0g3np x193iq5w x1n2onr6 x1hl2dhg x87ps6o xxymvpz xlh3980 xvmahel x1lku1pv xhk9q7s x1otrzb0 x1i1ezom x1o6z2jb xo1l8bm x108nfp6 xas4zb2 x1y1aw1k xwib8y2 x1swvt13 x1pi30zi x78zum5 x1iyjqo2 xs83m0k":
                button_text = starting_element.text
                if button_text in meta_cta_buttons:
                    parent_element = starting_element.find_element(By.XPATH, "..")
                    while (True):
                        if parent_element.tag_name != 'a':
                            # moves up element ancestry chain
                            parent_element = parent_element.find_element(By.XPATH, "..")
                        else:
                            cta_url = parent_element.get_attribute('href')
                            # store links in a set
                            unique_store_urls.add(cta_url)
                            break
                else:
                    continue
            else:
                continue

Can provide more of the outer loop if needed, but it is not relevant to the questions concern.

A: Here's a quick way to get the hrefs of the Call-to-Action "Learn More" buttons using SeleniumBase:
from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)

class MyTestClass(BaseCase):
    def test_base(self):
        self.open("https://www.facebook.com/ads/library/?active_status=all&ad_type=all&country=ALL&q=hearthstone&search_type=keyword_unordered&media_type=all")
        self.wait_for_element_visible('a:contains("Learn More")')
        elements = self.find_elements('a:contains("Learn More")')
        for element in elements:
            print(element.get_dom_attribute("href"))

Run with python or pytest.


text:
Q: Why Can't I store XML in ASP.NET ListBox Value? Why does this work:
ListItem item = new ListItem();
string value = lstAvailExtPropsToFilter.SelectedItem.Text +" = "+ txtExtPropToFilter.Text;
string text = lstAvailExtPropsToFilter.SelectedItem.Text + " = " + txtExtPropToFilter.Text;
item.Text = text;
item.Value = value;
lstExtPropsToFilter.Items.Add(item);

But not this:
ListItem item = new ListItem();
string value = string.Format("<key>{0}</key><value>{1}</value>", lstAvailExtPropsToFilter.SelectedItem.Text, txtExtPropToFilter.Text);
string text = lstAvailExtPropsToFilter.SelectedItem.Text + " = " + txtExtPropToFilter.Text;
item.Text = text;
item.Value = value;
lstExtPropsToFilter.Items.Add(item);

A: You would have to escape the string so it works in HTML.  Try Server.HTMLEncode.
Server.HTMLEncode("<key>{0}</key><value>{1}</value>")

Then when you need to pull the value you, use Server.HTMLDecode.


text:
Q: Room how to type convert a really complex data class? I want to use Room database to store data about my Itineraries, but the problem is that my Itinerary data class is really complex due to the large amount of data from API call. What is an optimal way of writing type converter for these types of classes?
Main class stored in Room
data class ItineraryModel(
    @PrimaryKey(autoGenerate = true)
    val itineraryId: Int = 0,

    @ColumnInfo(name = "price_details")
    @TypeConverters(PriceDetailsModelConverter::class)
    val priceDetails: PriceDetailsModel? = null,

    @ColumnInfo(name = "slice_data")
    @TypeConverters(SliceDataModelConverter::class)
    val sliceData: SliceDataModel? = null
)

SliceDataModel
data class SliceDataModel(
    val slice: SliceModel
)

SliceModel
data class SliceModel(
    val info: InfoSliceModel,
    val airline: AirlineModel,
    val arrival: ArrivalModel,
    val departure: DepartureModel,
    val flightData: FlightDataModel
)

InfoSliceModel
data class InfoSliceModel(
    val connectionCount: Int,
    val duration: String,
    val id: Int,
    val stopCount: Int
)

AirlineModel
data class AirlineModel(
    val logo: String,
    val name: String
)

Arrival/Departure Models (the same)
data class ArrivalModel(
    val airport: AirportModel,
    val datetime: DatetimeModel
)

AirportModel
data class AirportModel(
    val city: String,
    val code: String,
    val country: String,
    val name: String,
)

DatetimeModel
data class DatetimeModel(
    val date: String,
    val dateDisplay: String,
    val time24h: String,
)

FlightDataModel
data class FlightDataModel(
    val flights: List<FlightModel>
)

FlightModel
data class FlightModel(
    val arrival: ArrivalModel,
    val departure: DepartureModel,
    val info: InfoModel
)

InfoModel
data class InfoModel(
    val aircraft: String,
    val aircraftType: String,
    val cabinClass: String,
    val cabinName: String,
    val duration: String,
    val stopCount: Int
)

As you can see, there's a lot of data. How can I convert it optimally?

A: One easy solution to this is to use a serialization library, which allows converting big and complex objects into a String JSON, so you can store them in your Room database easily. I recommend using Kotlinx.serialization library, you can follow this link to setup with Gradle.
After installing the library, annotate all your data class with @Serializable. For example:
@Serializable
@Entity
data class ItineraryModel(
    @PrimaryKey(autoGenerate = true)
    val itineraryId: Int = 0,

    @ColumnInfo(name = "price_details")
    @TypeConverters(PriceDetailsModelConverter::class)
    val priceDetails: PriceDetailsModel? = null,

    @ColumnInfo(name = "slice_data")
    @TypeConverters(SliceDataModelConverter::class)
    val sliceData: SliceDataModel? = null
)

Do the same thing with all other data classes that are involved in your model. After doing this, go to your type converters:
PriceDetailsModelConverter:
class PriceDetailsModelConverter {

    @TypeConverter
    fun convertToJsonString(priceDetails: PriceDetailsModel?): String {
         return Json.encodeToString(priceDetails)
    }

    @TypeConverter
    fun convertToObject(json: String): PriceDetailsModel? {
         return Json.decodeFromString(json)
    }

}

SliceDataModelConverter:
class SliceDataModelConverter {

    @TypeConverter
    fun convertToJsonString(sliceDetails: SliceDataModel?): String {
         return Json.encodeToString(sliceDetails)
    }

    @TypeConverter
    fun convertToObject(json: String): SliceDataModel? {
         return Json.decodeFromString(json)
    }

}

And everything is OK, when store the big model object, priceDetails and sliceDetails will be stored in the form of String JSON, when you query the database, you will receive them as model objects.
Later on, if you want to select rows based on a price condition for example, you have to use LIKE sql operator since the priceDetails is stored as String, this maybe the only drawback of this approach.


text:
Q: New or Existing cell when using dequeueReusableCellWithIdentifier:forIndexPath:? Having a UITableViewControllerand using:
  override func tableView(tableView: UITableView, cellForRowAtIndexPath
          indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
    return cell
 }

Using dequeueReusableCellWithIdentifier:forIndexPath:'' instead ofdequeueReusableCellWithIdentifier`` how can I determine if a cell is a new one or a reused one?

A: Create your own custom cell class to use for the reuse identifier. Then, inside that cell, implement awakeFromNib and make your changes to the cell. This will only be called once when your cell is loaded from its NIB file.
Any other changes that need to be made when the cell is reused can be made in prepareForReuse.


text:
Q: Internal hom: products and coproducts It seems to me that

Assuming the all smalllimits and colimits exist:
  Internal hom for a closed symmetric monoidal category satisfies:
  $$[\bigsqcup C_i, X] \cong \prod_i [C_i, X] $$
  where $(-)\otimes X: V \rightarrow V $, have right adjoint $[X,-]:V \rightarrow V$.

My proof is by showing that they represent the same object in $V$. Is this isomorphism true?

A: You should show us your proof, but the standard proof carries out essentially like the proof that left adjoints preserve colimits and right adjoints preserve limits. $[\_, X]$ actually turns all colimits into limits, not just coproducts into products ($[\_, X]: V^{op} \to V$ preserves limits).
For objects $X$ and $Y$ in $V$ and a diagram $F: J \to V$,
$$
\begin{aligned}
C(X, [ \mathrm{colim}_{j \in J} F(j), Y ] ) & \simeq C(X \otimes \mathrm{colim}_{j \in J} F(j), Y ) \\
& \simeq C(\mathrm{colim}_{j \in J} F(j) \otimes X, Y ) \\
& \simeq C(\mathrm{colim}_{j \in J} F(j), [X, Y] ) \\
& \simeq \lim_{j \in J} C(F(j), [X, Y] ) \\
& \simeq \lim_{j \in J} C(F(j) \otimes X, Y ) \\
& \simeq \lim_{j \in J} C(X \otimes F(j), Y ) \\
& \simeq \lim_{j \in J} C(X, [F(j), Y] ) \\
& \simeq C(X, \lim_{j \in J} [F(j), Y] ) \\
\end{aligned}
$$
Since this is natural in $X$, $[ \mathrm{colim}_{j \in J} F(j), Y ] \simeq \lim_{j \in J} [F(j), Y]$ by the Yoneda lemma.


text:
Q: Unable to understand function-pointers in c++ I am reading The C++ Programming Language by Bjarne Stroustrup. It states an example to explain function-pointers:
int cmp1(const void∗ p, const void∗ q) // Compare name strings
{
  return strcmp(static_cast<const User∗>(p)−>name,static_cast<const User∗>(q)−>name);
}

Then it uses this cmp1 in ssort, something like this:
int main()
{
  cout << "Heads in alphabetical order:\n";
  ssort(heads,6,sizeof(User),cmp1);
  print_id(heads);
  //Rest of function body
}

My question is: is &cmp1 being passed as an argument in ssort() because we can't pass a function as an argument, we can only pass a function-pointer?

A:
My question is: is &cmp1 being passed as an argument in ssort() because we can't pass a function as an argument, we can only pass a function-pointer?

Your code does not use &cmp1. Hence, your question does not match your code.
Still, a function can be passed without using the addressof operator (&).
ssort(heads, 6, sizeof(User), &cmp1);

is the same as
ssort(heads, 6, sizeof(User), cmp1);

Functions decay to function pointers in this context.

A: A functions name indeed represent the starting address of the executable code for the function. So it's more like the arrays where its name can be used as pointer to the array itself. Also go through
https://www.geeksforgeeks.org/function-pointer-in-c/


text:
Q: How to pop UIImagePickerController's navigation I'm choosing a photo from the Photo Library, then creating a custom overlay/crop view with two buttons: Cancel, and Choose. Cancel should pop to the previous view to go back to the Photo Library to select a different image.
I'm trying to figure out how to get at the UIImagePickerController's navigation back target, but It keeps crashing on me.
I appreciate your responses.
Here is the code I'm using:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];

    UIViewController *cropController = [[UIViewController alloc]init];

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHeight = screenRect.size.height;

    UIView *cropView = [[UIView alloc]initWithFrame:CGRectMake(0,0,screenWidth,screenHeight)];

    UIButton *cancelButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 50)];
    [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor colorWithRed:(16.0/255.0) green:(100.0/255.0) blue:(230.0/255.0) alpha:1.0] forState:UIControlStateHighlighted];

    [cancelButton addTarget:self action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];

    UIButton *chooseButton = [[UIButton alloc]initWithFrame:CGRectMake(250, 0, 70, 50)];
    [chooseButton setTitle:@"Choose" forState:UIControlStateNormal];
    [chooseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [chooseButton setTitleColor:[UIColor colorWithRed:(16.0/255.0) green:(100.0/255.0) blue:(230.0/255.0) alpha:1.0] forState:UIControlStateHighlighted];

    UIView *buttonsView = [[UIView alloc]initWithFrame:CGRectMake(0, 518, 320, 50)];

    [buttonsView addSubview:chooseButton];
    [buttonsView addSubview:cancelButton];

    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:cropView.frame];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:originalImage];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.frame = scrollView.bounds;

    scrollView.backgroundColor = [UIColor blackColor];
    scrollView.minimumZoomScale = 1.0  ;
    scrollView.maximumZoomScale = imageView.image.size.width / scrollView.frame.size.width;
    scrollView.zoomScale = 1.0;
    scrollView.contentSize = imageView.image.size;
    scrollView.delegate = self;

    [scrollView addSubview:imageView];

    [cropView addSubview:scrollView];

    [cropView addSubview:buttonsView];

    cropController.view = cropView;

    [picker pushViewController:cropController animated:YES];

}

Edit: crash log:
2013-12-20 21:28:39.009 [15197:70b] -[SettingsTableViewController popViewControllerAnimated:]: unrecognized selector sent to instance 0x1095cff0
2013-12-20 21:28:39.012 [15197:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SettingsTableViewController popViewControllerAnimated:]: unrecognized selector sent to instance 0x1095cff0'
*** First throw call stack:
(
    0   CoreFoundation                      0x01ab45e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x0175d8b6 objc_exception_throw + 44
    2   CoreFoundation                      0x01b51903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
    3   CoreFoundation                      0x01aa490b ___forwarding___ + 1019
    4   CoreFoundation                      0x01aa44ee _CF_forwarding_prep_0 + 14
    5   libobjc.A.dylib                     0x0176f874 -[NSObject performSelector:withObject:withObject:] + 77
    6   UIKit                               0x004cd0c2 -[UIApplication sendAction:to:from:forEvent:] + 108
    7   UIKit                               0x004cd04e -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61
    8   UIKit                               0x005c50c1 -[UIControl sendAction:to:forEvent:] + 66
    9   UIKit                               0x005c5484 -[UIControl _sendActionsForEvents:withEvent:] + 577
    10  UIKit                               0x005c4733 -[UIControl touchesEnded:withEvent:] + 641
    11  UIKit                               0x0050a51d -[UIWindow _sendTouchesForEvent:] + 852
    12  UIKit                               0x0050b184 -[UIWindow sendEvent:] + 1232
    13  UIKit                               0x004dee86 -[UIApplication sendEvent:] + 242
    14  UIKit                               0x004c918f _UIApplicationHandleEventQueue + 11421
    15  CoreFoundation                      0x01a3d83f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
    16  CoreFoundation                      0x01a3d1cb __CFRunLoopDoSources0 + 235
    17  CoreFoundation                      0x01a5a29e __CFRunLoopRun + 910
    18  CoreFoundation                      0x01a59ac3 CFRunLoopRunSpecific + 467
    19  CoreFoundation                      0x01a598db CFRunLoopRunInMode + 123
    20  GraphicsServices                    0x02d7a9e2 GSEventRunModal + 192
    21  GraphicsServices                    0x02d7a809 GSEventRun + 104
    22  UIKit                               0x004cbd3b UIApplicationMain + 1225
    23  App                            0x00012872 main + 178
    24  libdyld.dylib                       0x0638370d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

A: The UIImagePickerController (picker in the code you show) is the UINavigationController. You want the pop message to go to it (picker), not to self. Your self is not a UINavigationController so naturally you crash when the pop message is sent to it.

A: Refer matt's answer
Replace this
[picker pushViewController:cropController animated:YES];

with
[self.navigationController pushViewController:cropController animated:YES];


text:
Q: HTML JavaScript Conditional href link based on timer I am trying to re-direct user to a specific page based on condition. If Timer still running open booknow.html if timer expired open booknowcode.html
Pseudo code

*

*Timer still running

*User clicks Book Now button
If condition :
a) if timer still running -> send user to booknowcode.html page
b) if timer expired -> send user to booknow.html page

// Set the date we're counting down to
var countDownDate = new Date("June 30, 2021 09:17:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Output the result in an element with id="timer"
  document.getElementById("timer").innerHTML = days + "d " + hours + "h " +
    minutes + "m " + seconds + "s " + "Discount 15%";

  // If the count down is over, write Expired text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("timer").innerHTML = "EXPIRED";
  }
  //===if timer still running then redirect to dicount page (distance more than zero) Start ===
  let link;

  if (distance <= 0) {
    link = "booknow.html";
  } else {
    link = "booknowcode.html";
  }
  document.getElementById("demo").innerHTML = link;
  //===if timer still running then redirect to dicount page (distance more than zero) End ===

}, 1000);

    <button class="btn btn-info" type="button" onclick="">Book Now</button>

So how do I replace booknow.html with booknowcode.html based on the timer condition?

A: You should set the href instead of the innerHTML.
document.querySelector("#conditional-button a").href = link;

A: Like this
Version 1

*

*Remove the button and make it a link

*give the link an ID

*change to document.getElementById("link").href = "booknowcode.html"; when timer expires

// Set the date we're counting down to
var countDownDate = new Date("June 30, 2021 09:17:25").getTime();
// Get today's date and time
var now = new Date().getTime();

// Find the distance between now and the count down date
var distance = countDownDate - now;

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  now = new Date().getTime();

  // Find the distance between now and the count down date
  distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Output the result in an element with id="timer"
  document.getElementById("timer").innerHTML = days + "d " + hours + "h " +
    minutes + "m " + seconds + "s " + "Discount 15%";

// If the count down is over, write Expired text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("timer").innerHTML = "EXPIRED";

  //===if timer stops, the link changes  ===

    document.getElementById("link").href = "booknowcode.html";
  }

}, 1000);

  Book Now</button>

Version 2

*

*Remove the link around the button and make it a button

*Add an eventListener on the click of the button

*Test the distance in the click handler

*change document.getElementById("demo").innerHTML = link;
to location  = link when running

// Set the date we're counting down to
var countDownDate = new Date("June 30, 2021 09:17:25").getTime();
// Get today's date and time
var now = new Date().getTime();

// Find the distance between now and the count down date
var distance = countDownDate - now;

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  now = new Date().getTime();

  // Find the distance between now and the count down date
  distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Output the result in an element with id="timer"
  document.getElementById("timer").innerHTML = days + "d " + hours + "h " +
    minutes + "m " + seconds + "s " + "Discount 15%";

  // If the count down is over, write Expired text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("timer").innerHTML = "EXPIRED";
  }
  //===if timer still running then redirect to dicount page (distance more than zero) Start ===
  let link;

}, 1000);
document.getElementById("but").addEventListener("click", function() {
  if (distance <= 0) {
    link = "booknow.html";
  } else {
    link = "booknowcode.html";
  }
  document.getElementById("demo").innerHTML = link;
  // change this to
  // location  = link;
  // when running

  //===if timer still running then redirect to dicount page (distance more than zero) End ===
})

  <button class="btn btn-info" id="but" type="button">Book Now</button>

A: Just apply your new link to the  (which I gave a data-attribute to make our replacement exact)
if (distance <= 0) {
  // ....
  document.querySelector('a[data-rel=book-link]').setAttribute('href', link)

I wasn't sure why you had a button inside of an anchor tag, so I removed the button and applied the css to the a and it should look the same.

// Set the date we're counting down to
//var countDownDate = new Date("June 30, 2021 09:17:25").getTime();
countDownDate = new Date().getTime() + 10000;
// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Output the result in an element with id="timer"
  document.getElementById("timer").innerHTML = days + "d " + hours + "h " +
    minutes + "m " + seconds + "s " + "Discount 15%";
  let link;

  // If the count down is over, write Expired text
  if (distance <= 0) {
    clearInterval(x);
    document.getElementById("timer").innerHTML = "EXPIRED";
    link = "booknow.html";
    document.querySelector('a[data-rel=book-link]').setAttribute('href', link)

  //===if timer still running then redirect to dicount page (distance more than zero) Start ===
  } else {
    link = "booknowcode.html";
  }
  document.getElementById("demo").innerHTML = link;
  //===if timer still running then redirect to dicount page (distance more than zero) End ===

}, 1000);

  Book Now


text:
Q: Accessible Tiles I'm aiming for an accessible Website with tiles to group content. They are implemented as a styled div which has no other syntactical purpose than to group its content.

    Profile
    Messages
    My Documents

    Jobs
    Education
    FAQ

    .tile {
    background-color: white;
      border-width:   2px;
      border-radius:  4px;
      border-color:   transparent;
    }

I'd like to provide information for screen readers that its content belongs together. On the other hand I can't use global IDs (like with using the WAI ARIA group-role).
Is there any syntactical technique to tell my screenreader-users which rich-text contents belong together without the use of global IDs?
(Q1) Would
 be a valid, understandable solution?
Kind Regards
EDIT: Added example; Added Question (Q1)

A: My first instinct would be to make each of these a list - it adds some extra markup, but it is a nice way to group related concepts. Another option (you could use both of these together, if you wanted) is to use an invisible header. An h2, h3, or whatever the appropriate header level is for each of these blocks, with the css making it invisible (not via display: none or visibility: hidden, though; look up "accessible screen-reader text" for more details on this pattern.)
You could also use a role=group with an appropriate aria-label on each parent div, if you want, but I think the list and/or header semantics are more common.


text:
Q: Qbasic - trying to call a sub, but i get a message that says "Expected CALL, subname, (...)" Here is the code, it takes 5 names and alphabetizes them. I have a sub that sorts the names but apparently i'm not calling it in the correct way.
DIM i AS INTEGER
DIM q AS INTEGER
DIM a AS STRING
DIM n(5) AS STRING
DIM z AS INTEGER
DIM x AS INTEGER
DIM y AS INTEGER
DIM g AS INTEGER

start:
CLS

FOR i = 1 TO 5
    INPUT "Name:", n(i) 'receiving 5 names
NEXT i

call Sort()                                **This is the line with the error**

PRINT "Names in Alphabetical Order:"
FOR i = 1 TO 5
    PRINT n(i)
NEXT i
INPUT "Again(y, n)", a
IF LCASE$(a) = "y" THEN GOTO start
IF LCASE$(a) <> "y" THEN STOP

'end of main program

SUB Sort (`enter code here`)
    FOR i = 1 TO 5
        FOR q = 1 TO 4
        IF LCASE$(n(q)) > LCASE$(n(q + 1)) THEN SWAP n(q), n(q + 1)
        IF LCASE$(n(q)) = LCASE$(n(q + 1)) THEN

            z = LEN(n(q))
            x = LEN(n(q + 1))
            IF z > x THEN g = x
            IF z < x THEN g = z

            IF z > 1 AND x > 1 THEN
                FOR y = 2 TO g
                    IF LCASE$(MID$(n(q), y, 1)) > LCASE$(MID$(n(q + 1), y, 1)) THEN
                        SWAP n(q), n(q + 1)
                        END
                    END IF
                    IF y = g THEN SWAP n(q), n(q + 1)
                NEXT y
            END IF
        END IF
    NEXT q
NEXT i

END SUB

I have tried putting a parameter in the sub, "SUB Sort(n())", the array that has the names in it, but it said incorrect array type.

A: Your problem is the fact that you typed SORT() when there are no arguments.
Invoking a SUB or FUNCTION with correct syntax can be a bit strange in QB at first, and the syntax for the CALL keyword makes things even more confusing:
' No arguments means you MUST NOT include the () afterward.
CALL SubNameE

' One non-array argument: n
CALL SubNameX(n)

' Two non-array arguments: a, b
CALL SubNameY(a, b)

' An array argument and a non-array argument: arr(), v
CALL SubNameZ(arr(), v)

Notice how arrays are passed to SUB and FUNCTION procedures using name().  The interpreter probably gets confused when you write call SORT() as SORT() is the syntax for an array, not a SUB/FUNCTION call with no arguments.
You can also write the above lines of code without the CALL keyword if that helps you:
' No arguments means only the procedure name is listed.
SubNameE

' One non-array argument: n
SubNameX n

' Two non-array arguments: a, b
SubNameY a, b

' An array argument and a non-array argument: arr(), v
SubNameZ arr(), v

Note that for a SUB or FUNCTION to accept an array argument, it must have them declared, like this:
SUB SORT (n() AS STRING)
' or if you wanted to use a type suffix
SUB SORT (n$())

A: Here is an easy way to pass an array to a sort subroutine in qb64:
DIM n(5) AS STRING
n(1) = "zachary smith"
n(2) = "xerox johnson"
n(3) = "yackle jones"
n(4) = "arnold aglet"
n(5) = "beth anderson"
CALL Sort(n())
FOR i = 1 TO 5: PRINT n(i): NEXT
END
SUB Sort (n() AS STRING)
FOR i = 1 TO 5
    FOR j = i + 1 TO 5
        IF n(i) > n(j) THEN SWAP n(i), n(j)
    NEXT
NEXT
END SUB

Here is an easier way to call a sort subroutine without specifying a parameter:
DIM SHARED n(5) AS STRING
n(1) = "zachary smith"
n(2) = "xerox johnson"
n(3) = "yackle jones"
n(4) = "arnold aglet"
n(5) = "beth anderson"
CALL Sort
FOR i = 1 TO 5: PRINT n(i): NEXT
END
SUB Sort
FOR i = 1 TO 5
    FOR j = i + 1 TO 5
        IF n(i) > n(j) THEN SWAP n(i), n(j)
    NEXT
NEXT
END SUB


text:
Q: Jersey ContainerRequestFilter Executing but Response is HTTP Status 401 - Unauthorized The ContainerRequestFilter named AppAuthenticationFilter executes properly and yet the response is HTTP Status 401 - Unauthorized.
AppAuthenticationFilter is located in daksh.userevents.storage.apps.api.
Link for the project.

A: I solved it by registering the multiple API Resource Packages as well as the multiple ContainerRequestFilter implementation classes in web.xml.
Please Note:
For resources: Use the packages in which the classes are contained.
For providers: Use the class names.
Keep the packages semi-colon/comma separated.
Example:
For Resource Packages:
<init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>
        my.first.package;
        my.second.package;
        my.third.package
    </param-value>
</init-param>

For Providers:
<init-param>
    <param-name>jersey.config.server.provider.classnames</param-name>
    <param-value>
        my.nth.package.XYZFilter;
        my.mth.package.ABCFilter
    </param-value>
</init-param>


text:
Q: Meaning of the direction of the cross product I was doing calculations with torque and then I came across something very confusing:
I understand that the magnitude of the torque is given by product of the displacement(from the center of rotation) at a point and the force applied at that point. This magnitude perhaps, says something about how "powerful" the rotation is. The question that confuses me, however, is what does the direction of the cross product tell? The direction is perpendicular both to the force and the displacement. What really is this the direction of?

A: When studying angular things - torque, angular velocity, angular momentum, etc. - physicists do a clever thing to avoid having to describe curves. You see, you might be tempted to draw a curved arrow for a torque, indicating that you are twisting something around in a circular-ish way. But then when you try to add two such arrows together, all of a sudden you realize your notation no longer has a natural, intuitive meaning.
Instead, we draw the arrow pointing perpendicular to the plain of the curve you are tempted to draw. More precisely in the case of torque, perpendicular to the plain defined by the radial vector and the force vector. Note that this uniquely defines what plane your curved arrow must reside in, and, given the right-hand rule, clears up the ambiguity as to which way your curved arrow should point (if your right-hand fingers curl in the direction of the curved arrow you want to draw, your thumb points in the direction of the straight arrow you should draw instead).
It is then a simple matter to encode the magnitude of the torque/angular velocity/whatever in the length of this vector. The benefit is that you end up with straight arrows describing everything, and they add exactly as your torques should add - you have a genuine vector space, and are free to abstract away from all diagrams. And it is not even terribly counterintuitive - the torque vector is parallel to the axis around which you are applying torque. If you think about it long enough, you should be able to convince yourself that if you had to choose a single direction to define things, this is the least ambiguous.

A: Exactly like a force vector tells you the rate of change of momentum (both magnitude and direction), torque tells you the rate of change of angular momentum, both magnitude and direction.

A: It tells you whether the torque is clockwise or counterclockwise, in accordance with the right hand rule--point your thumb in the direction of the torque vector, and your fingers will curl around in the direction of rotation.

A: When you apply a force to a rigid body your force might contain a component that seeks to deform the body (and this is opposed by a force equal to that component), but the remainder of the force, the part orthogonal can rotate the body.  The two forces, the applied external force and the constraint force naturally lie in a plane.  If you never plan to go beyond 3D and don't like to visualize the plane in which things happen, then instead you can make a convention to represent planes with a vector orthogonal to them, and establish another convention about how the orientation of the vector orthogonal represents the two different directions you can rotate in a plane.  Then whenever you show someone a vector your audience/customers/etc. can wonder if you meant to refer to a plane or to a vector.
In 4D this artificial crutch is not possible, and no convention can save you, well I shouldn't say never maybe some people would sooner use complex vectors to represent the 6 independent planes that exist in 4D rather than to call a plane a plane.  Of course, an imaginary vector for a plane is almost good enough, but so close to doing it properly that you might as well introduce planes as objects and be done with it.


text:
Q: How to send POST data to a new page using Javascript? I'm trying to send POST data (files) to a new webpage or reload the page and keep the POST data using Javascript.
I can't use a form because I want to allow the user to be able to select multiple files one by one an that requires me to use preventDefault() and send the data using Javascript.
My code:

var storedFiles = [];

const form = document.querySelector('#myform');

document.addEventListener("DOMContentLoaded", initFileStorage, false);

function initFileStorage() {

  // add the change listener on file input
  document.getElementById("uploadFile")
    .addEventListener("change", handleFileSelect, false);

}

function handleFileSelect(e) {

  // check if any files has been selected. If not, exit
  if (!e.target.files) return;

  var files = e.target.files;
  var filesArr = Array.prototype.slice.call(files);

  // push new selected files into the common file storage
  filesArr.forEach((f) => storedFiles.push(f));

}

form.addEventListener('submit', (event) => {

  //disable default form action
  event.preventDefault();

  var uploadName = document.getElementById("uploadnaam").value;

  //create new formdata
  let formData = new FormData();
  formData.append("theFiles", storedFiles);
  formData.append("uploadName", uploadName);
  formData.append("th", 'th');

  //configure new XMLHttpRequest
  const xhr = new XMLHttpRequest();
  xhr.open("POST", "index.php", true);

  xhr.setRequestHeader("Content-Type", "multipart/form-data");

  //send data
  xhr.send(formData);

  xhr.onload = () => {

    JSON.stringify(storedFiles);

    console.log(storedFiles);

  };

});
<form title='upload files' id='myform'>

Upload File

  <input title='input your files here' type="file" id='uploadFile' name='files[]' multiple />

  <input type="text" id="uploadnaam" placeholder="naam upload (verplicht)" autocomplete="off">

  <button type='submit' id='mySubmitButton' name="save">UPLOAD</button>

</form>

So right now when you submit the files the page will not reload (my goal is to run a file called filesLogic.php and now I do that by including it in the header) the page that I want because I want filesLogic to run with the POST data. And if I remove the event.preventDefault() then the page will reload but the POST data will be lost. Does anyone know how I can run filesLogic.php/refresh the page with and keep the post data.


text:
Q: PnPPowershell work with user columns I'm new with PnPPowershell and trying to work with some data in columns. I'm trying to understand the values in user -- both single and multi user columns. I have this code (all the variables used are defined earlier if not shown, and the code does work.) and it outputs the following
$FieldNames = "ID","Title","SinglePerson","MultiPerson"
$listItems = (Get-PnPListItem -List $ListName -Fields $FieldNames -PageSize 1000).FieldValues

$listItems | ForEach-Object {
    $_.GetEnumerator() | Where-Object { $_.Key -IN $FieldNames } | ForEach-Object {
        Write-Host $_.Key $_.Value
    }
}

ID 2
Title Single and multi
SinglePerson Microsoft.SharePoint.Client.FieldUserValue
MultiPerson Microsoft.SharePoint.Client.FieldUserValue Microsoft.SharePoint.Client.FieldUserValue Microsoft.SharePoint.Client.FieldUserValue

I found this documentation which says that there is an Email property. So I can get the email(s) by using $_.Value.Email. But I need to know that it is a person column and not a text or other type of column.
How can I get the value of the SinglePerson and MultiPerson columns? When iterating over all the columns how can I know if I have a single person or multi person column?
This is just a test for learning and eventually I need to iterate over thousands of list items with about 50 columns of various types.

A: Maybe you could try CSOM. My test is to display the data of an Item, which can display the email address. Of course, you can also display all the Items in a column by looping. The following is my code, I hope it helps you a little:
#Variables for Processing

$SiteURL = "https://crescent.sharepoint.com/sites/PMO"

$ListName = "Projects"

$ItemID = "1"

 #Get Credentials to connect

$Cred = Get-Credential

 Try {    #Setup the context

    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

     #Get the List Item

    $List = $Ctx.Web.Lists.GetByTitle($ListName)

    $ListItem = $List.GetItemById($ItemId)

   $Ctx.Load($ListItem)    $Ctx.ExecuteQuery()     #Get the "Created By" column value of the Item

    $CreatedBy = $ListItem.FieldValues["Author"]

     #Get the User Object

    $User = $Ctx.Web.GetUserById($CreatedBy.LookupId)

   $Ctx.Load($User)    $Ctx.ExecuteQuery()

    $User | Select Email, Title, LoginName

}Catch {

    write-host -f Red "Error:" $_.Exception.Message

}

A: Maybe you could refer to the following two articles to implement with PowerShell:
Get-Set Person or Group (People Picker) Field Value using PowerShell in SharePoint
SharePoint Online: Read / Update Person or Group Field (People Picker) Values using PowerShell

If the answer is helpful, please click "√" on the left panel of the answer and kindly upvote it.


text:
Q: Alternative to "double entendre"? Does anyone know another word or way to say double entendre — in the non-bawdy sense of the word — as this phrase was only invented in the latter 1600's and so not around when Shakespeare wrote his plays, specifically as ever, the Merchant…
it is a straight statement... he is a good man... just one that two people take to mean two different ways is there a nice word for that when used purposefully?

A: You mean one of

*

*adianoeta

*allegory

*innuendo

A: Innuendo fits, but only in the romantic or sexual connotation.

A: If you want a term that Shakespeare himself (or at least his contemporaries) might have used, how about bawdy quips or more specifically bawdy puns?
(And I feel sure there's somewhere also in Romeo and Juliet where this subject comes up — Mercutio and Benvolio(?) are teasing Romeo about having the hots for Juliet, and he says something like "enough with the filthy jokes, guys! my love for her is pure and special!" — but I can't remember for the life of me remember his actual words, I'm up afraid.)

A: How about good old irony, subtext or perhaps a pun?

A: If you make a statement that, by accident, can reasonably interpreted two ways, you have said something ambiguous.
If you make a statement that, by design, can reasonably interpreted two ways and it's not dirty or sexual, you've said something with a double meaning or perhaps a hidden meaning.  (I can't think of any single word that describes it, but if one exists I'm sure Robusto will find it for you....)

A: another word that is appropriate in this context insinuate

A: Hate to reference a cartoon, but Archer calls out double entendre statements by saying "Phrasing" I think that is a logical "other" way to say it.
~Phrasing~
example:
https://www.youtube.com/watch?v=hyLWrKh2fB0

A: ...double entendre — in the non-bawdy sense of the word

Coined in 1375–1425; late Middle English:
Equivocality 1. allowing the possibility of several different meanings, as a word or phrase, especially with intent to deceive or
  misguide; susceptible of double interpretation; deliberately
  ambiguous: an equivocal answer.


text:
Q: use post and or get to submit post on a page and view in another. similar to a blog I am a little frustrated, but trying to work through this in my free time.  What I want is to create a blog page for my daughter and I am a bit of a beginner myself when it comes to web design, although I do know css and html like the back of my hand.  My question is with php and or mySQL  what I want is to have my daughter write her blog/story (she is 9) on one generic page for submitting text that I've written to a spot on her page on our family website, still in the making.  So I have learned how to post something, but not to a target space on a specific page.  I assume that you use an anchor tag on her page rose.html and getelmentbyID or post?  I'm now confused.  I can look up the connection sequence for php if someone doesn't want to explain all that to me, but bear with me, while I have some experience with php and mysql I am still a little green behind the ears.  Anything would help.

A: You'd be MUCH better off using something like WordPress - if you know HTML/CSS well you can customize it to be very useful to you.
It's dead simple to install and theirs a million guides out their for you to use.
http://wordpress.org/
Give it a shot, it'll make you life a lot easier.
Theming WordPress:
http://webdesignerwall.com/tutorials/building-custom-wordpress-theme

A: Say your dynamically posting a p message to a div from submitting words in a text box named "entry". You would just insert the php in the middle of the div where you want to see it. For example

<?php
    $post = $_POST['entry'];
     echo '
'.$post.'
';
?>

<form method="post" action="">
<textarea name="entry" cols="40" rows="5">
Enter your comments here...
</textarea>

<input type="submit" value="Submit" />
</form>


text:
Q: Python subprocess log stdout and stderr to named pipe I am starting a child process with subprocess.Popen in python3 and I need to direct all the output from stdout and stderr of this child process to a named pipe which is already created by some other process. There are other processes also writing to the same named pipe. Is there a way to do this?
i tried passing it as a string but that is not what is expected as popen needs file handles
subprocess.Popen(my_cmd, stdout="/path/to/named_pipe", stderr="/path/to/named_pipe", env=my_env)


text:
Q: Generate custom test result in Visual Studio 2008 I'm elaborating some unit tests and I'm not sure if what I want is possible with Visual Studio 2008.
Basically, I'm scanning some classes and for each of them, I want to know if this class is serializable and if it has a default constructor.
I would like to have in the Test Results View the list of ALL the classes that I had tested and if the test if successful or not.
So, if I'm scanning 325 classes, I want 325 entries in my test results panel.
Is it something possible with Visual Studio 2008, and if it's positive, how I'm gonna do it ?
Thanks, have a nice day.

A: Well, I didn't figure out my first choice, but I found something very interesting for me.
I simply use the Console.WriteLine(myStringBuilder.ToString());
It displays very nicely in the TestResult.
See : Bill Barnett's blog


text:
Q: how to add common variable for laravel and pass this data to all view all views I want to create a global variable and pass this into all view, so I can get this variable into all blade template
basically, my need is to pass my general setting controller value into my common blade view like header.blade.php
Thanks in advance

A: For that you will need to add some code in the App->Providers->AppServiceProvider.php like this:
public function boot()
    {
        view()->composer('*',function($view){

            $settings = Settings::firstOrNew(['id' => '1']);
            $view->with('settings', $settings );

        });
    }

A: According to Laravel documentation you can use view composer:
https://laravel.com/docs/5.8/views#view-composers
for using this feature in app > AppServiceProvider and in boot method you can use this approach for passing parameter to specific view If you have data that you want to be bound to a view each time that view is rendered. this approach meet your need perfectly. for example you want to pass a parameter named userName to header.
View()->composer('header', function ($view){
    $userName= "username"
    $view->with(['userName'=>$userName]);
});


text:
Q: VNC Connecting issue in SUSE Linux Enterprise Server 12 SP4 I have created one the following instance on AWS (SUSE Linux Enterprise Server 12 SP4 (HVM), SSD Volume Type - ami-0c55353c85ac52c96
SUSE Linux Enterprise Server 12 Service Pack 3 (HVM), EBS General Purpose (SSD) Volume Type. Public Cloud, Advanced Systems Management, Web and Scripting, and Legacy modules enabled) I have installed XRDP & Gnome Desktop Envoirnment.
Also I have set the status as Active & Enable for XRDP in system system services. I have executed the below commands but still the not able to login into the system
Updated the SUSE installed Gnone & XRDP
zypper update ( to update SUSE Linux Ent. Server)
zypper install -t pattern gnome-basic
zypper install xrdp

Enable VNC Remote Login

Open yast, Select "Network Services",
    Select first entry "Remote > Administration with VNC" Enable service

Configure Window Manager to use Gnome

Edit file /etc/sysconfig/windowmanager Change entry DEFAULT_WM="" to
  DEFAULT_WM="gnome"

Startup the RDP service and make it start automatically after Reboot
service xrdp start
chkconfig --set xrdp on
systemctl start xrdp
systemctl enable xrdp

But I am getting the below error : Let me know your thoughts so that I can fix this issue.

please wait, we now perform access control... Reply rom access
  control: Success Connecting to sesman ip 127.0.0.1 port 3350 sesman
  connect ok sending login info to session manager, please wait...
  xrdp_mm_process_login_response: login successfull for display 200
VNC started connecting Waiting 2000 ms for VNC to start... VNC
  connecting to 127.0.0.1 6100 VNC error - problem connecting


text:
Q: Oracle to MariaDB data migration We are in the process of migrating a fairly large Oracle database (approx. 200 tables) to MariaDB. We used CA ERwin to help create the MariaDB schema objects, and are now trying to figure out the best way to migrate the data. For example, if I use SQL Developer's export utility, the resulting Insert statements are created with Oracle syntax, which can differ quite a bit from MariaDB's syntax. Rather than handling every set of Inserts on an individual basis, I'm hoping somebody has been through this before and can suggest an alternative.
We looked at the MySQL Workbench Migration Wizard, but it doesn't directly support migration from Oracle to MariaDB/MySQL (no surprise as Oracle owns MySQL).
Has anybody come across a utility that will make this task easier and save time?  Thanks.


text:
Q: Pushing a Mongo or MySQL DB from a dev environment to prod -- Ignoring rows that exist I've been trying to find a way to take a database and "push" it up to a server, but have it ignore rows that collide (effectively, only inserting rows that have unique keys).  Is this possible?  I've tried Googling it a bit to no avail.

A: A lot depends on your exact use case, but you could try mongoexport and mongoimport to perform this for each collection. mongoimport supports a --upsert flag that allows you to update existing documents that already exist if that is desired behavior. If not it should reject documents with the same unique key.


text:
Q: test ActiveModel::Serializer that has a variable without using the controller tester I have an ActiveModel::Serializer class (class TaskSerializer < ActiveModel::Serializer) that I'm looking to test.
The serializer makes use of the current_user object, because it's in scope during the controller actions.
But I'm attempting to write a new rspec file. (task_serializer_spec.rb)
When I run
TaskSerializer.new(task).to_json

I get an error saying that the current_user method doesn't exist.
I can't mock the variable because we have "the method must exist" flag on our mocks.
I understand that there are some other parameters that I can pass in the NEW. but I can't find any docs on it.  Can someone offer a way to get things like current_user in the scope.

A: My answer might be a little late, but if someone ever ends up on this page, here is a way to do this:
app/serializers/task_serializer.rb :
class TaskSerializer < ActiveModel::Serializer
  attributes :id, :method_using_current_user, :whatever_other_attributes_goes_here

  delegate :current_user, to: :scope

  def method_using_current_user
    current_user.some_method_here
  end
 end

In your rspec test, you can than do something like this:
RSpec.describe TaskSerializer do

  let(:user) { create(:user) }
  # or any other user you want to create here

  before do
    # As current user is delegated to controller scope, we mock both here
    allow_any_instance_of(TaskSerializer).to  receive(:scope).and_return(ApplicationController.new)
    allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
  end

  # your test goes here
end

And voila.


text:
Q: Searching for a string in a file is not working in Python I am using this code to find a string in Python:
buildSucceeded = "Build succeeded."
datafile = r'C:\PowerBuild\logs\Release\BuildAllPart2.log'

with open(datafile, 'r') as f:
    for line in f:
        if buildSucceeded in line:
            print(line)

I am quite sure there is the string in the file although it does not return anything.
If I just print one line by line it returns a lot of 'NUL' characters between each "valid" character.
EDIT 1:
The problem was the encoding of Windows. I changed the encoding following this post and it worked: Why doesn't Python recognize my utf-8 encoded source file?
Anyway the file looks like this:
Line 1.
Line 2.
...
Build succeeded.
    0 Warning(s)
    0 Error(s)
...

I am currently testing with Sublime for Windows editor - which outputs a 'NUL' character between each "real" character which is very odd.

Using python command line I have this output:
C:\Dev>python readFile.py
Traceback (most recent call last):
  File "readFile.py", line 7, in <module>
    print(line)
  File "C:\Program Files\Python35\lib\encodings\cp437.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position 1: character maps to <undefined>

Thanks for your help anyway...

A: If your file is not that big you can do a simple find. Otherwise I would check to file to see if you have the string in the file/ check the location for any spelling mistakes and try to narrow down the problem.
f = open(datafile, 'r')
lines = f.read()
answer = lines.find(buildSucceeded)

Also note that if it does not find the string answer would be -1.

A: As explained, the problem happening was related to encoding. In the below website there is a very good explanation on how to convert between files with one encoding to some other.
I used the last example (with Python 3 which is my case) it worked as expected:
buildSucceeded = "Build succeeded."
datafile = 'C:\\PowerBuild\\logs\\Release\\BuildAllPart2.log'

# Open both input and output streams.
#input = open(datafile, "rt", encoding="utf-16")
input = open(datafile, "r", encoding="utf-16")
output = open("output.txt", "w", encoding="utf-8")

# Stream chunks of unicode data.
with input, output:
    while True:
        # Read a chunk of data.
        chunk = input.read(4096)
        if not chunk:
            break
        # Remove vertical tabs.
        chunk = chunk.replace("\u000B", "")
        # Write the chunk of data.
        output.write(chunk)

with open('output.txt', 'r') as f:
    for line in f:
        if buildSucceeded in line:
            print(line)

Source: http://blog.etianen.com/blog/2013/10/05/python-unicode-streams/


text:
Q: iPad + WCF duplex + protobuf I'm about to start building an iPad client for an existing WCF service that currently communicates via Duplex channel callbacks and pushes lightweight data transfer objects to the client at regular intervals. I'm planning to do this using monotouch.
I know that the iOS platform supports peer-to-peer communication, so my hope is that I can initiate a duplex communication channel from the service to the device after the device has initiated the first connection.
Will this approach work on an iPad?
Currently I'm using protobuf-net to squish my payload into a nice tight byte[] and the client deserializes it accordingly. Can I continue to do so?
Or should I expose a second interface with the service and implement a new polling model with XML response objects to compliment the push model for my existing client apps?
Any advice on a better way to approach this is appreciated.

A: I can't comment on the duplex, but re protobuf-net - yes, especially in v2; there is an iOS build in the zip, and I know of success stories using this with both monotouch and unity.


text:
Q: UNIX sed command help     sed -n '$'!p abc.txt | tail +2 > def.txt

I have the above mentioned sed command in my code - I am unable to figure out what it does -I am going through sed tutorials to find it out but am not able to - Can some one please help me in figuring out what it does - Thanks

A: Taking this in stages:
sed -n abc.txt

"Run abc.txt through sed, but don't print anything out."
sed -n '$!p' abc.txt

(Note that I've corrected what I think was a misplaced quote mark.)
"Run abc.txt through sed; if a line isn't the last line, print it (i.e. print all but the last line)."
I guess you know the rest, but note that tail +2 is obsolete syntax-- tail -n 2 would be better.
EDIT:
To remove the last two lines, try
sed 'N;$d'

or if that doesn't work, crude but effective:
sed '$d' | sed '$d'

A: As far as the sed command '$'!p is concerned:

*

*the $ matches only the last line of the input file.

*the ! negates the sense of the match (so that it matches all but the last line).

*the p prints out whatever was matched.

So basically this prints all but the last line of the file.
The -n option stops sed from performing its default action (to print the pattern space) - without that, you'd get one copy of the last line and two copies of all the other lines.
The quotes around $ are to stop the shell from trying to interpret it as a shell variable - I would have quoted the lot myself ('$!p') but that's a style issue, at least on bash. Other shells like csh (which uses ! for command history retrieval) may not be so forgiving.


text:
Q: Custom CFInclude for file customization Our code base has quite a bit of the following example as we allow a lot of our base pages to be customized to our customers' individual needs.
<cfif fileExists("/custom/someFile.cfm")>
    <cfinclude template="/custom/someFile.cfm" />
<cfelse>
    <cfinclude template="someFile.cfm" />
</cfif>

I wanted to create a custom CF tag to boilerplate this as a simple <cf_custominclude template="someFile.cfm" />, however I ran into the fact that custom tags are effectively blackboxes, so they aren't pulling in local variables that exist prior to the start of the tag, and I can't reference any variable that was created as a result of the tag from importing the file.
E.G.

<!--- This is able to use someVar --->
<!--- Pulls in some variable named "steve" --->
<cfinclude template="someFile.cfm" />
<cfdump var="#steve#" /> <!--- This is valid, however... --->

<!--- someVar is undefined for this --->
<!--- Pulls in steve2 --->
<cf_custominclude template="someFile.cfm" />
<cfdump var="#steve2#" /> <!--- This isn't valid as steve2 is undefined. --->

Is there a means around this, or should I utilize some other language feature to accomplish my goal?

A: Well, I question doing this at all but I know we all get handed code at times we have to deal with and the struggle it is to get people to refactor.
This should do what you are wanting.  One important thing to note is that you will need to ensure your custom tag has a closing or it won't work!  Just use the simplified closing, so like you had it above:
<cf_custominclude template="someFile.cfm" />

This should do the trick, called it has you had it :   custominclude.cfm
<!--- executes at start of tag --->
<cfif thisTag.executionMode eq 'Start'>
    <!--- store a list of keys we don't want to copy, prior to including template --->
    <cfset thisTag.currentKeys = structKeyList(variables)>
    <!--- control var to see if we even should bother copying scopes --->
    <cfset thisTag.includedTemplate = false>
    <!--- standard include here --->
    <cfif fileExists(expandPath(attributes.template))>
        <cfinclude template="#attributes.template#">
        <!--- set control var / flag to copy scopes at close of tag --->
        <cfset thisTag.includedTemplate = true>
    </cfif>
 </cfif>
 <!--- executes at closing of tag --->
 <cfif thisTag.executionMode eq 'End'>
    <!--- if control var / flag set to copy scopes --->
    <cfif thisTag.includedTemplate>
        <!--- only copy vars created in the included page --->
        <cfloop list="#structKeyList(variables)#" index="var">
            <cfif not listFindNoCase(thisTag.currentKeys, var)>
                <!--- copy from include into caller scope --->
                <cfset caller[var] = variables[var]>
            </cfif>
        </cfloop>
    </cfif>
 </cfif>

I tested it and it works fine, should work fine being nested as well.  Good luck!
<!--- Pulls in steve2 var from include --->
<cf_custominclude template="someFile.cfm" />
<cfdump var="#steve2#" /> <!--- works! --->


text:
Q: ArcScene - Spatial reference I am having trouble merging different layers in ArcScene. As there is no such thing as the "Georeferencing" used in ArcMap, I am not able to view two different Layers in one document.
Is there anyway to overlay two layers and show them in the same document? Or maybe any tool to spatial reference layers in a different kind of raster?

A: Are the layers on the same projection and of the same location? If they are you can go to properties and select the 'base heights' offset function to move them closer together (assuming this is a vertical difference issue?)
You can also use the same to drape one layer over the other if this is what you need?
TBH - its hard really knowing what you want as you haven't described the problem with much detail. Hope this solution helps.


text:
Q: Logic error in remove duplicates in a vector while preserving the order function void vectorDeduplicator(std::vector<std::string>& inputVector){
     for(int i = 0; i < inputVector.size() - 1; i++){
          for(int x = 1; x <= inputVector.size() - 1; x++)
                if(inputVector.at(i) == inputVector.at(x) && i != x){
                inputVector.erase(inputVector.begin() + x);
          }
     }
}
Input: 1 1 2 2 4 4 3 3 1 1 3 3 3 2 2
Output: [1,2,4,1,3,2]

You can see the function I'm trying to use to remove duplicates inside of a vector. It works when duplicates are adjacent. I wouldn't like to use a faster and an efficient method without knowing anything about it that already exists within the standard library or anything else. I'd like to learn the algorithm behind it as this is for learning purposes.

A: The problem is you ignore one value as you erase. You need to decrement x:
#include <vector>
#include <iostream>

void vectorDeduplicator(std::vector<int>& inputVector)
{
     for(int i = 0; i < inputVector.size() - 1; i++)
     {
          for(int x = 1; x < inputVector.size(); x++)
          {
                if(inputVector.at(i) == inputVector.at(x) && i != x)
                {
                    inputVector.erase(inputVector.begin() + x);
                    x--; // go one back because you erased one value
                }
          }

        // to debug
        for(const auto& x : inputVector)
            std::cout << x << " ";
        std::cout << std::endl;
     }
}

int main(){

    std::vector<int> vector{1, 1, 2, 2, 4, 4, 3, 3, 1, 1, 3, 3, 3, 2, 2};

    vectorDeduplicator(vector);

    // output
    for(const auto& x : vector)
        std::cout << x << " ";

    return 0;
}

The output then is:
1 2 2 4 4 3 3 3 3 3 2 2
1 2 4 4 3 3 3 3 3
1 2 4 3 3 3 3 3
1 2 4 3
1 2 4 3


text:
Q: What item should I put my enchanted book on? I got extremley lucky when fishing and got a book with a lot of enchants...
it has thorns 2, Depth strider 3, Bane of athropods 4, quick charge 2, and channeling.
I do have a trident (2 actually, I got 2 in a row. I am lucky)

A: *

*Thorns isn't the best enchantment, so you shouldn't really put it on many things. It takes away 3 durability points if another enemy hits you and it gets damaged by the piece of armor.

*Bane of Arthropods is a really bad enchantment. It only works on a few mobs such as spiders, and silverfish (and a few more) by doing a bit more damage to them.

*Quick charge is a good enchantment that allows crossbows to charge faster (which can be useful, actually! quick charge can go up to level 3). Channeling is an enchantment that allows you to summon a bolt of lightning during a thunderstorm.

*Channeling can sometimes be useful (for collecting mob heads) but is also hard to use, because thunderstorms are very rare.

*Probably the best enchantment to use in this situation is Depth Strider 3, because it allows you to swim as fast as you can walk on land.
In this situation, Depth Strider 3 is the enchantment to use.
Note: Thorns will also be added to your boots, which means that it will take more durability, so try adding mending or unbreaking.


text:
Q: Run `php composer.phar dump-autoload` from code - Laravel 5.4 I'm trying to run these command from code, but having some trouble finding out how.

*

*php composer.phar dump-autoload -o

*php composer.phar require 'vendor/some-package'

*php composer.phar update 'vendor/some-package'
EDIT
Forgot to mention, that I don't want to use the exec function because of potential risk and the fact that's blocked on most servers by default.
I did manage to download the .phar file from code, but not how to run these commands. I'm trying to build a friendly as possible solution and don't want use to dumpautoload manually after installing something etc.
Code to download
 $composerPath = base_path('composer.phar');
 copy('https://getcomposer.org/composer.phar', $composerPath);

A: I have found a working solution. You can call these command with Symphony's process component.
$process = new \Symfony\Component\Process\Process('php composer.phar autoload-dump');
$process->setWorkingDirectory(base_path());
$process->run();

Worked it out into a class:
https://codeneverlied.com/using-composer-from-code/

A: you can runcomposer global require "laravel/envoy=~1.0"  to bring Laravel's envoy package into your project.  With envoy you can write something like
@servers(['localhost' => '127.0.0.1'])

@task('foo', ['on' => 'localhost'])
    php composer.phar dump-autoload -o
    php composer.phar require 'vendor/some-package'
    php composer.phar update 'vendor/some-package'
@endtask

but at some point the server will have to run envoy run task, this is also guessing on your question.  You may more elaborate more on what you are trying to actually do.

A: cd /tmp
wget https://getcomposer.org/composer.phar
chmod 755 composer.phar
php composer.phar --version


text:
Q: Blank screen at login. Intel intergrated graphics, ubuntu 12.04 Whenever I boot ubuntu 12.04 from grub, it takes me to the login screen but the screen is completely blank (no backlight at all). I'm running a 64-bit Compaq Presario CQ45 with Intel Intergrated Graphics (Intel(R) HD).
I can connect the laptop to an external display at see ubuntu fine on the external display, but I can't see ubuntu on my laptop screen unless I change the resolution down a little and then ubuntu appears on my laptop. But this only lasts for about 30 minutes and the screen goes blank again.

A: fn + [your display for projector, example F3 for leno]


text:
Q: In Quarto how do I write inline CSS I would like to color a word in a sentence that is being rendered in quarto to HTML.  In R Markdown I would just add a css tag but I don't see how to do that in quarto.  The quarto documentation says that it is possible to write inline css but there is no example.  There is a hyperlink that shows a R Markdown example:
```{css, echo=FALSE}
body {
  color: red;
}
```

When I do that, quarto displays the code as a code block and does not use the CSS.
How do I add a CSS code block to a quarto document?

A: Just surround the word you want to style by [] and write the styles in {}, like this
the color is [red]{style="color: red;"}

so the word red will be in the color red.
To add more details,
---
title: "inline style"
format: html
---

## inline style in Quarto

We can apply styles to a sentence or a word
by creating spans using `[]` to surround the
sentence or word that we want to style and
use `{}` to define the style that we want to
apply. For example,

The color of this word is [red]{style="color: red;"}.
And [this line has a yellow background]{style="background-color: yellow"}.

After rendering, we get this,


text:
Q: What's the proper way to write hex literal values in Delphi? In Python I can use string hex literal like "ab\xa1\x31_\x44\xf1\x10". Does Delphi has a similar syntax? I want to define a string that has this literal as initial value. I searched the document but didn't find anything related (The document is not easy to use).

A: You need to prefix the hex value of a character with #$, where # is the prefix for a character value and $ the prefix for hex.
The string above can be written like:
myString := 'ab'#$a1#$31'_'#$44#$f1#$10;


text:
Q: Multipart tiff and EXIF metadata In the tif format, when you add EXIF meta data it creates an new IFD (tif-direcory) and stores the exif metadata as fields. So when parsing a tif file with a single image and exif data is easy. But you can get multipart tiffs, where a tif can contain more then one image, the question is can each of these images have EXIF data?
Does this create a new IFD for each pictures metadata?
What is is the arrangement of the IFD's then?
The tif specification doesn't go into any detail, I know that when a single image tif file has EXIF data there is an offset field to the EXIF data, so I can jump to that location and do the parsing myself, but the Java Sanselan library gives me easy access to the EXIF IFD and fields, but if it is possible to multiple EXIF IFD's (one for each image) then the library doesn't tell me to which image the data belongs.
If you cannot have more then 1 EXIF IFD in a multipart tif file, then it'll be trivial! In other words:
Do I need to go to the effort of manually parsing the exif data? Because I only need to do this if you can attach EXIF data to each image inside a multipart tif.
Or does anyone know of a good Linux app that allows me to add EXIF data to tif files so I can figure it out for myself?

A: To answer your questions:

can each of these images have EXIF data? Does this create a new IFD for each pictures metadata? What is is the arrangement of the IFD's then?

Yes, each of these images can have it's own EXIF data. Each image is related to its own IFD and each EXIF data is a SUB-IFD inside the corresponding image IFD.

but the Java Sanselan library gives me easy access to the EXIF IFD and fields, but if it is possible to multiple EXIF IFD's (one for each image) then the library doesn't tell me to which image the data belongs.

I never used Sanselan and it's successor Apache Imaging so I guess there could be two things happening here: first, Sanselan may by default choose the first page for a multipage TIFF if you actually can insert EXIF to a multipage TIFF; or there might be a parameter which you can set somewhere with a method like setWorkingPage(int page) and this is what I am doing with "icafe" Java image library.
The following is a bit more detailed information as to what is happening inside a TIFF image when you need to add EXIF metadata:
For a single page TIFF, there is a "main" IFD which specifies all the information regarding the image contained there. When EXIF data is needed, an specially tag called "EXIF_SUB_IFD" is added to the main IFD. The value for this tag is an offset address with regards to the image stream start. Now if we jump to the address specified by the offset, we will actually find a "sub" IFD with exactly the same structure as the "main" IFD which contains all the EXIF data.
The above mentioned structure is exactly like a directory tree and hence the name IFD. There is however a subtle difference here: the main IFD should contain the actual image data but the EXIF sub-IFD doesn't. In fact, there is also a GPS sub-IFD which is in parallel with the EXIF sub-IFD and with the same structure as well. An interesting thing is the data for the EXIF can be stored anywhere inside the TIFF image stream (as long as it doesn't break other part of the directory and image data).
Now comes to the multipage TIFF. The pages can be related or not. The last 4 bytes of each page IFD points to the offset of another IFD. They are sometimes gathering together to serve as a "single" document which could be from a scanner. That said, each page is itself a "single" page TIFF which could contain it's own EXIF metadata just like a single page TIFF.

A: You probably want to check out ExifTool.  It works pretty well for what I use it on (JPEGs), but I've never used it with TIFF files containing multiple images.  Also check ImageMagick, he has a ton of useful tools.


text:
Q: Why is there a value printed and not NULL/0 after incrementing a pointer in C++? I am fairly new to C++, so excuse if this is quite basic.
I am trying to understand the value printed after I increment my pointer in the following piece of code
int main()
{
    int i = 5;
    int* pointeri = &i;
    cout << pointeri << "\n";
    pointeri++;
    i =7;
    cout << *pointeri << "\n";
}

When I deference the pointer, it prints a random Integer. I am trying to understand, what is really happening here, why isn't the pointer pointing at NULL and does the random integer have a significance  ?

A: The C++ language has a concept of Undefined Behavior. It means that it is possible to write code that does not constitute a valid program, and the compiler won't stop or even warn you. What such code does when executed is unknown.
Your program is a typical example. After the line int* pointeri = &i;, the pointer is pointing to the value i. After pointeri++ it is pointing to the memory location after the value i. What is stored at that location is unknown and the behavior of such code is undefined.
Needless to say, great care should be taken when coding in C++ in order to stay in the realm of defined behavior, in order to have meaningful and predictable results when running the program.

A:
why isn't the pointer pointing at NULL

Because you haven't assigned or initialised the pointer to null.

and does the random integer have a significance ?

No.

Why is there a value printed ...

Because the behaviour of the program is undefined.

A: As you know, a "pointer" is simply an integer variable whose value is understood to be a memory address.  If that value is zero, by convention we call it NULL and understand this to mean that "it doesn't point at anything."  Otherwise, the value is presumed to be valid.
If you "increment" a pointer, its value is non-zero and therefore presumed to be valid.  If you dereference it, you will either get "unpredictable data" or a memory-addressing fault.


text:
Q: Power BI Card data alignment I need to create a report like below. (figure 1)

I have created measures and added to the report using a Card. It's looks like below. (figure 2)

There is no alignment options available in Card Visual so I can't align data as I needed.
How could I create a report as shown in Figure 1 in Power BI?

A: You need this
https://appsource.microsoft.com/en-us/product/power-bi-visuals/wa104381651?tab=overview
Advanced card has the alignment properties.

A: You can put a rectangle behind, same background color, make your card visual as small as possible, remove title etc and position it on the rectangle, then send the rectangle 'to back', under Format. Messy but works. Grouping the 2 objects helps to keep them in place and resolves the click behaviour bringing the rectangle forward. Might work for you.

A: the best way to align properly is to select your card and go to the format options, and the general section.
You will find x-y coordinates what will allow you to perfectly align your visual.


text:
Q: Pass Json data using Jquery Ajax then display response Why is this not working? Jquery will take the value on change and send it using ajax in json format to a php file. then same jquery will take response and append it. $(#orderSummary) never display success for me to verify that it actually get a response.
         $(document).ready(function(){

   $("#prodcat").change(function(){
    var prodid = $(this).val();

        $("#orderSummary").append(prodid);

    $.ajax({
     type: 'POST',
     url: 'getproduct.php',
     data: {'prodcat':prodid},
     dataType: 'json',
     success:function(response){

        $("#orderSummary").append(success);

      var len = response.length;

      $("#product").empty();

      for( var i = 0; i<len; i++){
       var name = response[i]['name'];
       var detail = response[i]['detail'];
       var price = response[i]['price'];

       $("#product").append("<option value='"+name+"'>"+name+"</option>")
      }
     }
    });
   });
 });
</script>

A: You are appending wrong varaible
change
 $("#orderSummary").append(success);

to
 $("#orderSummary").append(response);

OR if you want to append success message to orderSummary then append it with ''
$("#orderSummary").append('success');


text:
Q: What is a good way to manage a large number of configurations in Netbeans? I'm working on a C++ project under Netbeans that consists of many classes used to create a number of main programs (here: simulation systems). I have a large number of those simulation systems plus test programs, thus I end up with a lot of main programs associated to my project. Generally, I just want to build one of those main programs, so I created a configuration for each of them. The number of configurations now grows and grows and becomes inconvenient. One reason I find it inconvenient, is that many configuration names have the same beginnings and become indistinguishable in the configuration pop down menu.
Is there any tool or plugin allowing a more efficient management of configurations?
Is there a different approach to my task of building many different main programs from one project? It would be wonderful if you could use variables like the name of the currently opened file in the build command of a configuration. In this case I would only need one configuration. (I asked about that in the Netbeans forum but haven't received any answers.)


text:
Q: Accessing self-defined Datatypes - Lambda function application order Got this:
data Cmd = PushK Int | Pop | Push Int
         deriving (Eq,Show)

type StackProgram = [Cmd]

Question:
How can I access the Int value of PushK?

> head [PushK 5, Pop]
PushK 5  -- Great!

> (\_ x -> x)PushK 5
5 -- Great!

> (\_ x -> x)(head [PushK 5, Pop])
Couldn't match expected type `t1 -> t' with actual type `Cmd'

Anyone have a solution?

A: You unwrap values out of a data constructor by using pattern matching, or by defining record syntax (in which case Haskell generates the getters itself).
Pattern matching
Since here the type is not defined as record, we thus have to use pattern matching:
getK :: Cmd -> Int
getK (PushK x) = x
-- ...

and probably you need to handle the cases of another data constructor.
We can also perform this pattern matching with a lambda expression:
(\(PushK x) -> x) (PushK 5)

Records
We can also define the command as a record:
data Cmd = PushK { k :: Int } | Pop | Push { p :: Int } deriving (Eq,Show)

Now Haskell has generated two functions k :: Cmd -> Int and p :: Cmd -> Int automatically, so in that case we can write:
k (PushK 5)

which will return 5.
Why did (\_ x -> x) PushK 5 return 5?
In Haskell functions are first class citizens. That means you can pass functions as arguments, return them as result. You here did not constructed a Cmd.
In fact PushK is a data constructor, and a function (with type Int -> Cmd), you thus called the lambda expression with two parameters: the first one is the pushK, and the second is 5. You simply omit the first parameter, and retun the second x.
But it is thus derived as:
   (\y x -> x) PushK 5
=  ((\y -> (\x -> x)) PushK) 5    -- (more verbose version)
-> (\x -> x) 5
-> 5

A: You may want to define a single catamorphism to deconstruct an arbitrary Cmd value.
cmdCata :: (Int -> a)  -- Function to apply to x in (PushK x)
        -> a           -- Value to replace Pop
        -> (Int -> a)  -- Function to apply to x in (Push x)
        -> Cmd         -- The value to deconstruct
        -> a           -- The result
cmdCata f _ _ (PushK x) = f x
cmdCata _ x _ Pop       = x
cmdCata _ _ f (Push x)  = f x

It takes two functions and a default value (for Pop) to turn any Cmd value into a value of type a. The following extracts the value wrapped by PushK or Push and rewraps it with Just (the function for PushK doing a little extra work just to show the difference between PushK and Push), and replaces Pop with Nothing.
> cmdCata (Just . (+3)) Nothing Just (PushK 5)
Just 8  -- 5 + 3
> cmdCata (Just . (+3)) Nothing Just Pop
Nothing
> cmdCata (Just . (+3)) Nothing Just (Push 20)
Just 20

Or if you just want an integer and a default value for Pop is fine:
> cmdCata id 0 id (PushK 5)
5
> cmdCata id 0 id Pop
0
> cmdcata id 0 id (Push 3)
3

Compare cmdCata to Data.Maybe.maybe, and think of what functions analogous to Data.Maybe.fromJust, Data.Maybe.catMaybes, etc, could be defined for your Cmd type.


text:
Q: Why does the text on this third column is pushed down? Well, I coded this page, but I got stuck at why does the third column is pushing down my text (or other elements). It uses the same style from the first box, but while the first box is ok, the third one is pushing the elements down by some pixels.
Like this:

HTML

                Índice

                    Sinopse

                    Tropas

                    Geladeira

                            Lógica

                            Gênio

                            Horror

                    Notas

                    Mídia

                    Referências

3º Column

CSS
* {
    margin:0;
    padding:0;
    font:normal normal 14px/20px Helvetica,Arial,sans-serif
}

h4 {
    font-size:14px;
    font-weight:700;
    text-transform:uppercase;
    padding-top:10px;
    border-bottom:2px solid #2a558c;
    margin-bottom:10px
}

#contentWrapper {
    display:table;
    border-spacing:0;
    width:100%;
    height:500px
}

#contentWrapper > div {
    display:table-cell
}

#sideBar {
    background-color:#E4E5DD;
    width:200px
}

#mainBody {
    background-color:#EEEEE6
}

#infoBar {
    background-color:#e4e5dd;
    width:200px
}

#footer {
    background-color:#323540;
    height:50px
}

.sidebarBox {
    background-color:#323540;
    height:30px;
    width:100%
}

.sidebarContent {
    padding:15px
}

I messed a lot with the Firebug and even tried to open it in IE and Chrome, with same results. Both columns use the same CSS, and this difference is freaking me out. I thought about "fixing" it with some negative margins, but I want to understand the problem first, insted of "workahacking" away.
Thanks a lot in advance!

A: Add vertical-align: top to #contentWrapper > div. Currently it is baseline.
Have a fiddle!
CSS
#contentWrapper > div {
    display: table-cell;
    vertical-align: top;
}

Without vertical-align: top, the div is basing its vertical alignment on .sidebarContent which has 15px of padding. This is resulting in the 15px gap.

A: Change the following and it should fix your problem.  I've found that when using display:table-cell it always mis-aligns the last cell unless I specifically give it a vertical alignment
#contentWrapper > div {
    display: table-cell;
    vertical-align:top;
}

Example

A: Add display:inline-block to this class:
.sidebarBox {
    background-color: #323540;
    height: 30px;
    width: 100%;
    display: inline-block;/*Add this*/
}

fiddle

A: .sidebarBox {
    float:right;
}

will work.


text:
Q: Labview interop assembly, exchanging Image between c# and labview I made an interop assembly.net dll with labview that takes in parameter an image, do some work on that image and then return the image.
After I added the dll to my c#.net project I can't figure out what kind of data type that goes with the image data type with labview that is referenced as "LVBaseRefnum".
I have succeeded before to call simple data types and cluster types, but I just couldn't know what c# data type goes with "LVBaserefnum" or what data type goes with the Image object.
In another hand the LVBaserefnum has a constructor that takes an int refnum as parameter.
LVBaseRefnum img = new LVBaseRefnum(int RefNum)

Does Anyone have an idea?

A: I think you have the standard C/C++ constructor in the Lab View Application Builder.
If yes, you have pointer. In C# you must declare the class and the usage of the self-compiled assembly (i think an interop assembly) as unsafe
Example
class FileReader
{
  const uint GENERIC_READ = 0x80000000;
  const uint OPEN_EXISTING = 3;
  IntPtr handle;

  [DllImport("kernel32", SetLastError=true)]
  static extern unsafe IntPtr CreateFile(
        string FileName,                    // file name
        uint DesiredAccess,                 // access mode
        uint ShareMode,                     // share mode
        uint SecurityAttributes,            // Security Attributes
        uint CreationDisposition,           // how to create
        uint FlagsAndAttributes,            // file attributes
        int hTemplateFile                   // handle to template file
        );

   [DllImport("kernel32", SetLastError=true)]
  static extern unsafe bool ReadFile(
        IntPtr hFile,                       // handle to file
        void* pBuffer,                      // data buffer
        int NumberOfBytesToRead,            // number of bytes to read
        int* pNumberOfBytesRead,            // number of bytes read
        int Overlapped                      // overlapped buffer
        );


text:
Q: Latch using only NPNs I've been trying to find a way to create a latching circuit with only NPNs and passives. I think I've found way:

My logic being that the resistors act like a potential divider and provide power to both transistors, and T2 is parallel to the switch, so it replaces it when saturated. When the switch is turned on, current flows down through T1's emitter and R2, making it saturated, and therefore making T2's emitter parallel to R2. T2 then becomes saturated and acts like the switch.
However, when I run it in a simulator starting with the switch off, current still flows (the yellow dots do move):

I can't see why current would flow, so is it a problem with the simulator or my logic?

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. A transistor appears as two back-to-back diodes when not configured properly.
With the above knowledge analyse your circuit again.

simulate this circuit
Figure 2. This circuit can't work. 'B' is at a lower potential than the base and emitter.

simulate this circuit
Figure 3. A transistor latch.
The circuit of Figure 3 is the basis of a thyristor.

*

*On power up Q1 and Q2 are off.

*When SW1 is closed current flows into the b-e junction of Q1. The c-e resistance drops as the transistor turns on.

*Q1 turning on draws current from the e-b junction of Q2. This then turns on and Q2's e-c resistance drops.

*Q1's base is now fed from Q2's collector. If SW1 is opened Q1 and Q2 will remain on. The circuit is latched.

*The only way to turn off the lamp is to interrupt V1 with another switch.


text:
Q: Android Intent Filter zip I want to use a Intent-filter , that makes the application open when a zip file is clicked in a fileexplorer
so which mimetype do i have to use ?
and what codee to get the path?
<activity
    android:name=".App"
    android:label="@string/app_name" >
    <intent-filter>
      <action android:name="android.intent.action.SEND" />

      <category android:name="android.intent.category.DEFAULT" />

      <data android:mimeType="text/plain" />

    </intent-filter>

    </activity>

Java-Code:
Intent intent = getIntent();

        // To get the action of the intent use
        String action = intent.getAction();
        if (action != Intent.ACTION_SEND) {
            throw new RuntimeException("Should not happen");
        }
        // To get the data use
        Uri data = intent.getData();
        URL url;
        try {
            url = new URL(data.getPath());
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

A: You can use the following IntentFilter:
<intent-filter>
    <action android:name="android.intent.action.VIEW"/>

    <category android:name="android.intent.category.DEFAULT"/>

    <data android:mimeType="application/zip"/>
</intent-filter>

When your Activity is started, it has a data URI from which you can get the zip file:
File zip = new File(getIntent().getData().getPath());


text:
Q: Installing IIS on Windows 7 I have installed IIS on my PC according to the guidelines in this link http://learn.iis.net/page.aspx/28/installing-iis-on-windows-vista-and-windows-7/  but when I type http://localhost in my browser it displays nothing. What is the reason for that.

A: They should make it clearer that
IF you are using Starter or Home Basic editions, the result you get is expected.


text:
Q: Simulating Bottlenecks using H2/Hibernate/C3P0 I want to run some local performance tests where I would like to simulate a database bottleneck.
I am using Hibernate with C3P0 and hitting an H2 database (Server Mode).
What I would like to do is find a way to artificially slow down the database queries in some manner.
I have tried limiting the size of my C3P0 connection pools, but it seems that despite that everything is able to keep up just fine.
Is there some property I can adjust either on H2 or maybe C3P0 that would allow me to essentially slow down the database queries?


text:
Q: scheme - convert a string to a list without #\ characters and with spaces If I have a following string after performing some operations - "this is a string"
I am trying to convert back to the list - (this is a string)
Using the built-in methong string->list I get (#\t #\h #\i #\s #\space #\i #\s #\space #\a #\space #\s #\t #\r #\i #\n #\g #\?).
How can I convert it to a list without all the #\ symbols as well as not having a space be replaced with #\space?

A: If you do not have string-split, you can still implement it with basic Scheme features.
(define (tokenize l)
  (let loop ((t '())
             (l l))
    (if (pair? l)
        (let ((c (car l)))
          (if (char=? c #\space)
              (cons (reverse t) (loop '() (cdr l)))
              (loop (cons (car l) t) (cdr l))))
        (if (null? t)
            '()
            (list (reverse t))))))

(define (string-split s)
  (map list->string (tokenize (string->list s))))

;; (string-split "this is a string") => ("this" "is" "a" "string")

A: You're confusing strings with symbols. To split a string by spaces, simply do this:
(string-split "this is a string")
=> '("this" "is" "a" "string") ; a list of strings

But if you really want to convert a string into a list of symbols, do this:
(define (convert string)
  (map string->symbol          ; convert each substring into a symbol
       (string-split string))) ; split the string by its spaces

(convert "this is a string")
=> '(this is a string) ; actually, a list of symbols (not strings!)