text:
Q: Get historical data using Instagram API endpoints. I am trying to fetch data using the Instagram API endpoints. Steps that I have followed
1. Register the client app.
2. Got the access token.
3. I am using this access token through out the url endpoints.
Ex. to get the data for recent media I am using this url endpoint: https://api.instagram.com/v1/users/self/media/recent/?access_token=ACCESS-TOKEN
However as I am in Sandbox mode, as per the documentation I get only the recent 20 media. Whereas my account contains in total 291 media.
Problems that I am facing:

*

*Not able to get next_url in the paginationpart.

*Usage of min_id and max_id in the url does not respond to any changes in the output or the data i.e fetched (Still get only 20 records/media)

Ex: https://api.instagram.com/v1/users/self/media/recent?access_token=XXXXXX&min_id=xxxxxx_xxxxx&max_id=xxxxxxx_xxxxxxx
Can anybody provide a solution as to how exactly I should get all of my historical data ?

A: You're in the sandbox mode so there's no way to achieve what you're trying to do before your app has been reviewed and approved (and gone live). From Instagram API documentation:

After your app has been reviewed and approved, you are ready to make it available to the general public. To switch your client from sandbox to live mode, you can use the button on the top section of the configuration screen for your app. When you are live, any Instagram user will be able to authorize your app, but you will have access only to the permissions that you were granted during the review.

A: Well, maybe you should try this library that allows you to scrape public info withou auth (client_id or access_token): https://github.com/raiym/instagram-php-scraper
$medias = Instagram::getMedias('kevin', 150);


text:
Q: Error Getting Dependencies for Matplotlib I am trying to install the python package matplotlib from source. I cannot install the package from the repository using sudo apt-get install python-matplotlib because I need to be able to install the package in a virtualenv using a requirmenets.txt file. When I follow the instructions to install dependencies I get the following error:
vagrant@vagrant-ubuntu-trusty-64:~$ sudo apt-get build-dep python-matplotlib
Reading package lists... Done
Building dependency tree
Reading state information... Done
Picking 'matplotlib' as source package instead of 'python-matplotlib'
The following packages have unmet dependencies:
 python3-all-dbg : Depends: libpython3-all-dbg (= 3.4.0-0ubuntu2) but it is not going to be installed
                   Depends: python3-dbg (= 3.4.0-0ubuntu2) but it is not going to be installed
                   Depends: python3.4-dbg but it is not going to be installed
 python3-all-dev : Depends: libpython3-all-dev (= 3.4.0-0ubuntu2) but it is not going to be installed
                   Depends: python3-dev (= 3.4.0-0ubuntu2) but it is not going to be installed
                   Depends: python3.4-dev but it is not going to be installed
 python3-numpy-dbg : Depends: python3-dbg but it is not going to be installed
E: Build-dependencies for python-matplotlib could not be satisfied.

How do I fix the problem? I have already run sudo apt-get update and
sudo apt-get upgrade to no avail. Could I just directly install the dependencies listed in the error message (I thought that was the point of the command)? I am not even using Python 3 so not concerned about having the packages installed (though not sure why I need them either). When I try running pip install -r requirements.txt in the virtual environment I still get an error on installing matplotlib.

A: Generally you get this message when you're missing some repository - you could check the list of your active repo from /etc/apt/sources.list. In your case you might miss the -srcrepo
What is strange is that python3-dev is from main repo so it should be activated by default.
You can add repo by editing the file /etc/apt/sources.list
sudo vi /etc/apt/sources.list

and add the following lines
deb-src http://archive.ubuntu.com/ubuntu/ trusty main restricted
deb-src http://br.archive.ubuntu.com/ubuntu/ trusty-updates main restricted

You can get more info about the available repo from this link
make sure to (re)run sudo apt-get update after you've done this change and you should be ok to install your dependencies

redpajama_set_name: RedPajamaStackExchange


text:
Q: QGIS project variable in map composer template file? I need to insert project variable into map composer file (.qpt) for showing specific legend item. The item is a layer constructed from a URL query that I need to dynamically change based on a project variable.
When I open another project, the layer URL query in the legend has a fixed value and the legend does not display the symbol, only the layer title, because in that project the layer has a URL query with a dynamic variable and the legend does not "find" the corresponding layer in the project.
...<layer-tree-layer name="Some Name" id="query_where_obec_3D598259_text__objectIds__time__geometry__geometryType_...">
    <customproperties>
     <Option type="Map">
      <Option name="cached_name" type="QString" value="Území obce"/>
     </Option>
    </customproperties>
   </layer-tree-layer>
   <custom-order enabled="0"/>
  </layer-tree-group>...

In the "ID" option i need to insert the QGIS variable.
Is this possible or is there another solution for this problem?
EDIT: I must have auto update turned off for custom legend item settings.
REPRODUCIBLE EXAMPLE: Create a label in map composer, save as template (.qpt) and insert a qgis variable in the .qpt file somehow and after opening the template in a new map composer it should appear in the label.

A: The correct syntax is labelText="[% @myvar %]":
<layer-tree-layer name="Some Name" id="[% @myvar %]">


text:
Q: What is the difference between CAPM.alpha and CAPM.jensenAlpha What is the difference between the two functions from the PerformanceAnalytics package CAPM.alpha and CAPM.jensenAlpha?
If I set Ra and Rb and no Rf=0, it gives me two different values for my return xts objects. (Ra being the excess returns of my portfolio and Rb the excess returns of the benchmark, thus no Rf)
It gives me an output:
> CAPM.jensenAlpha(portfolio,benchmark)
[1] 0.05676789

>CAPM.alpha(portfolio,benchmark)
[1] 0.006135824

My returns are monthly excess returns. Moreover, CAPM.alpha gives exactly the intercept in a regression of these monthly excess returns. What is then the value for CAPM.jensenAlpha? I first thought it could maybe be the annualized alpha, but calculating arithmetically *12 or geometrically (1+alpha)^12-1 doesnt do the trick...


text:
Q: SQL Server : searching between dates in string data type I have a table, which stores dates as type varchar.
In the SELECT statement, I want to extract ALL values of the table, but filter the data BETWEEN two dates.
I have tried converting and this is the closest I have gotten. any help would be appreciated. The dates I want to filter by is called opened
SELECT *
FROM table
WHERE Opened BETWEEN CONVERT(DATETIME, '01/08/2006', 103)
                 AND CONVERT(DATETIME, '01/05/2020', 103)

A: I would discourage you from using between with dates.  Here is a good explanation of why, provided by Aaron Bertrand.
select t.*
from table t
where t.opened >= '2016-08-01' and
      t.opened < '2020-05-02'

If your opened is in the same date format, then use:
select t.*
from table t
where convert(date, t.opened, 103) >= '2016-08-01' and
      convert(date, t.opened, 103) < '2020-05-02'

However, you should fix your table so the dates are stored using the correct types, not strings.


text:
Q: Generating unique sequential surrogate Key for each record in spark scala I am facing difficulty in generating unique sequential surrogate Keys to replace the null values in a column of a table. The table is obtained after joining a source table and reference table and the column is the primary key column ("account_key") of resultant table where null values should be replaced with unique sequence keys.
The unique keys generated should start with a number assigned to the source and the number should be incremented for each null value.
I tried the following
    var uniqueId = Table_NO.agg(max("No"))
// var uniqueID = 6000001 (for example)
//or a SQL statement can be written as "var uniqueId = sqlContext.sql(SELECT MAX (NBR) FROM Table"
    var a = sc.accumulator(uniqueID)
    def generate(s:Int):Int = {
        if (s==0)
        {
            a = a.add(1)
            return a.localValue
        }
        else
        {
            return s
        }
val NumGen = udf(generate(_:Int))
val KeyGen = table_n.withColumn("KEY_New", NumGen(table_n ("account_key")))

A: I think you can just use a windowing function, depending on your version it might look like this...
import org.apache.spark.sql.expressions._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._
val incrementbyOne = Window.partitionBy(lit("C")).orderBy(lit("C").asc)
    table_n.withColumn("identity_column", row_number().over(incrementbyOne))


text:
Q: Re-initialize variable or declare new? In C#, is there a benefit or drawback to re-initializing a previously declared variable instead of declaring and initializing a new one?  (Ignoring thoughts on conciseness and human readability.)
For example, compare these two samples:
DataColumn col = new DataColumn();
col.ColumnName = "Subsite";
dataTable.Columns.Add(col);

col = new DataColumn(); // Re-use the "col" declaration.
col.ColumnName = "Library";
dataTable.Columns.Add(col);

vs
DataColumn col1 = new DataColumn();
col1.ColumnName = "Subsite";
gridDataTable.Columns.Add(col1);

DataColumn col2 = new DataColumn(); // Declare a new variable instead.
col2.ColumnName = "Library";
gridDataTable.Columns.Add(col2);

A similar example involving loops:
string str;
for (int i = 0; i < 100; i++)
{
    str = "This is string #" + i.ToString(); // Re-initialize the "str" variable.
    Console.WriteLine(str);
}

vs
for (int i = 0; i < 100; i++)
{
    string str = "This is string #" + i.ToString(); // Declare a new "str" each iteration.
    Console.WriteLine(str);
}

Edit: Thank you all for your answers so far.  After reading them, I thought I'd expand on my question a bit:
Please correct me if I'm wrong.
When I declare and initialize a reference type like a System.String, I have a pointer to that object, which exists on the stack, and the object's contents, which exist on the heap (only accessible through the pointer).
In the first looping example, it seems like we create only one pointer, "str", and we create 100 instances of the String class, each of which exists on the heap.  In my mind, as we iterate through the loop, we are merely changing the "str" pointer to point at a new instance of the String class each time.  Those "old" strings that no longer have a pointer to them will be garbage collected--although I'm not sure when that would occur.
In the second looping example, it seems like we create 100 pointers in addition to creating 100 instances of the String class.
I'm not sure what happens to items on the stack that are no longer needed, though.  I didn't think the garbage collector got rid of those items too; perhaps they are immediately removed from the stack as soon as you exit their scope?  Even if that's true, I'd think that creating only one pointer and updating what it points to is more efficient than creating 100 different pointers, each pointing to a unique instance.
I understand the "premature optimization is evil" argument, but I'm only trying to gain a deeper understanding of things, not optimize my programs to death.

A: Your second example has a much clearer answer, the second example is the better one.  The reason why is that the variable str is only used within the for block.  Declaring the variable outside the for block means that it's possible for another piece of code to incorrectly bind to this variable and hence cause bugs in your application.  You should declare all variables in the most specific scope possible to prevent accidental usage.
For the first sample I believe it's more a matter of preference.  For me, I chose to create a new variable because I believe each variable should have a single purpose.  If I am reusing variables it's usually a sign that I need to refactor my method.

A: This sounds suspiciously like a question designed to provide information for premature optimization.  I doubt that either scenario is different in any way that matters in 99.9% of software.  The memory is being created and used either way.  The only difference is the variable references.
To find out if there is a benefit or drawback, you would need a situation where you really care about the size or the performance of the assembly.  If you can't meet the size requirements, then measure the assembly size differences between the two choices (although you're more likely to make gains in other areas).  If you can't meet the performance requirements, then use a profiler to see which part of your code is working too slowly.

A: It is primarily a readability issue, whether you use the same declared name or not doesn't matter, since either way you are creating two separate objects. You really should create the objects or variables with a single focus in mind, it will make your life easier.
As for your second example, the only real difference in intialization is that by placing your string outside the scope of the "for" loop, you are leaving it exposed to more outside influences, which can be useful at times. There is no memory or speed benefit for declaring it inside or outside of the loop. Remember, anytime you make a change to a string variable, you are essentially creating a new string. So, for example:
string test = "new string";
test = "and now I am reusing the string";

is the same as creating two separate strings, like:
string test1 = "new string";
string test2 = "and now I am reusing the string";

To get around this, you would use the StringBuilder class, which allows you to modify a string without creating a new string, and should be used in situations where a string will be heavily modified, especially inside a loop.

A: What about using the word "using" which destroy the object itself after the braces ends?
I am not sure but that's what I think. I'd like to know your opinions too.
For the second example, I use the second one always, I am not sure as well, but for example at some problems at the ACM-ICPC contest I used to have lost of bugs because forgetting to re-initialize, so I used this way.

A: For the most part, no, there should be no difference.  The main difference would be that local variables (in the case of classes, their "pointer") are stored on the stack and in your first case, if your function were for some reason recursive, having two local vars instead of one will cause you to run out of stack space faster in a deep-recursive function.  Getting close to that limit in either case would be a sign that you should probably use a non-recursive method.
Also, just to mention it, you could skip the variables altogether and write:
dataTable.Columns.Add(new DataColumn() { ColumnName = "Subsite" });
dataTable.Columns.Add(new DataColumn() { ColumnName = "Library" });

Which I believe performance-wise will be like having 2 local variables, but I could be wrong there.  I cant remember exactly what that produces in IL code though.


text:
Q: How can I make this type of custom EditText UI? I am trying to put borders on edit text and put a label on it. I have tried this one.

<stroke
    android:width="2dp"
    android:color="@color/colorPrimary"/>
<corners android:radius="15dp"/>

But I want the following one. Initially it will look like this.
After clicking it will be like this.

Would you please help?

A: use the material design Outline Box style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
this link may help you http://qaru.site/questions/1688917/custom-textinputlayout-android

A: As @ZahoorSaleem said, you can use the MaterialComponents for that.
You will need to add the design support library to your build file.
The layout would (simplified) look like this:
<TextInputLayout
  android:hint="Label"
  style="style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
    <TextInputEditText />
</TextInputLayout>

A: put the below code in drawable and use this attribute in edittext
 android:background="@drawable/nameofdrawablefile"
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="#CC0505"/>
    <stroke android:width="2dp" android:color="#CC0505" />
    <corners android:radius="5dp" />
</shape>


text:
Q: how to move space from /dev/sda2 to /dev/sda3 in fedora 9 I have some issues to move space one /dev/sda2 to /dev/sda3 it mean

Help me to solve this issue, I need to move space from /home to /

A: You need to reallocate free space from /dev/sda3 to /dev/sda2. As one of these partitions is your root (/) you will need to do this offline. If you burn a GParted live CD, you can boot into this and resize your partitions.
However, there is a risk that any partition resize operation may result in the loss of data so be sure you have backed up anything important.
Also, note that this would only be a temporary fix. At most I would suggest reallocating about 10GB over to your root to give you some room to manoeuvre, but you really need to address the incongruous sizes of your partitions. An 885GB root partition that is 100% full is very odd. It's entirely likely you are storing things on there that would be better placed in /home/, although currently your /home is too small at 20GB. A better ratio of parition sizes would be 20GB for root and 885GB for /home but it's difficult to see how you would address this at the moment without doing a fresh install and losing everything you currently have, unless you have some external storage you can back files up to.


text:
Q: How to get the start and end of Fiscal Year in C# based on current date? - Using SSIS Script Task I created an SSIS Package that reads through existing files and makes changes/moves based on the file names and sheets. I have a C# Script Task that a co-worker wrote which is manually updated for the start and end of the fiscal year; however, we have others using this package so I would like to automate the Fiscal Year dates.
How can I get the starting and ending date of the current Fiscal Year based on today's date?
I did find Working out start of financial year
and How to discover financial Year based on current datetime? however, I can't seem to get the top-voted answers to work. I'm using a Reference/Namespace of Microsoft.Office.Interop.Excel but I'm not sure if that makes a difference.

*

*Fiscal Year 2021 is 09/01/2020 to 08/31/2021

*Fiscal Year 2022 is 09/01/2021 to 08/31/2022

*Fiscal Year 2023 is 09/01/2022 to 08/31/2023

Today is 08/19/2022, the current Fiscal Year is 09/01/2021 - 08/31/2022, but when we hit 09/01/2022, it will change to 09/01/2022 - 08/31/2023.
This is what I use now, calling FYStart and FYEnd multiple times.
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
    public void Main()
    {

       //Update Fiscal Year Here (YYY, MM, DD):
       DateTime FYStart = new DateTime(2021, 09, 01);
       DateTime FYEnd = new DateTime(2022, 08, 31);

A: It sounds like you're saying that if the current month is less than 9, then the fiscal year started in the previous year. Otherwise it started this year.
If so, this can be represented in code by:
public static int GetFinancialYearStart(DateTime input)
{
    return input.Month < 9 ? input.Year - 1 : input.Year;
}

Then we can just call this method to set our start and end dates::
int fyStartYear = GetFinancialYear(DateTime.Now);
DateTime fyStart = new DateTime(fyStartYear, 09, 01);
DateTime fyEnd = new DateTime(fyStartYear + 1, 08, 31);

Or a shortened version:
var fyStart = new DateTime(GetFinancialYear(DateTime.Today), 09, 01);
var fyEnd = fyStart.AddYears(1).AddDays(-1);


text:
Q: Upgrading Sublime text 3 I want to upgrade Sublime Tex 3, downloaded the deb, but I get the following error:
Breaks existing package 'sublime-text-installer' conflict: sublime-text ()

How do I upgrade Sublime correctly?

A: Happened to me too. A quick search on the internet revealed that you can solve this by removing the deb package information using the following command in the terminal.
sudo dpkg -r sublime-text-installer

A: I assume you have sublime package so this worked for me
sudo apt-get install --only-upgrade sublime-text

A: sudo apt-get purge sublime-text-installer

run this before installing new package..!


text:
Q: extract wsdl password from soap ui project xml I have been given a url to a password protected wsdl and told to develop from it. The only other resource I have is a project setup xml for soap ui. The document works and I am able to import the project into soap ui and connect to the wsdl that way. I can even run operations. Unfortunately, I cannot figure out what the password is, so I have no way to view the wsdl directly, or (more importantly) have soap ui autogenerate the java client code.
I have found two usernames used in the xml document, but they are all used for individual operations. Putting them into my browser has not worked. Are there a wsdl username and password hidden somewhere in the soap ui document?
I also don't think I fully grasp the auth file thing. I went to USER_HOME and made a .metro folder, then put an extensionless file called "auth" in it and put "http://userName:password@remoteHost.wsdl?wsdl", but eclipse continued to ask for the auth file as though it did not exist.


text:
Q: How to pass both a Function and Prop to an onClick Event in React? I only see examples of people passing two functions but nothing on a prop and function simultaneously. Let's say I want the pass onClick={props.tested} (prop) and onClick={divTested} (function) at the same time. How do I do this??

A: Although I rarely see this done, you can indeed add properties to a function, and pass that "function with properties" into another function that is aware of those properties:

let functionWithProperties = function(a, b)
{
  return a + b;
}

// Add Properties to the function:
functionWithProperties.a = 5;
functionWithProperties.b = 10;

function doSomethingWithFunctionWithProperties(func)
{
  return func(func.a,func.b);
}

// Pass function with properties into another function
// that is aware of those properties:
let output = doSomethingWithFunctionWithProperties(functionWithProperties);

console.log(output); // 15


text:
Q: How to register a new user from android client on Ejabberd server How can I register a new user from android client on Ejabberd Server?
Are there a rest API to solve this issue?
Thank's in advance

A: If you enable account registration in mod_register configuration, you can use XMPP's In-Band-Registration.
Alternatively, you can run the ejabberd command "register" with several alternative ways, if you enable ejabberd_xmlrpc, mod_http_api, or mod_rest. See https://docs.ejabberd.im/admin/guide/managing/#ejabberd-commands


text:
Q: Unable to install "App" Xcode 11.5+ iOS 13.5.1 when you connect a second iPhone, it gives this error, details below. I tried to be guided by discussions:
https://developer.apple.com/forums/thread/124031 ,
https://apple.stackexchange.com/questions/242678/xcode-error-the-maximum-number-of-apps-for-free-development-profiles-has-been-re
Did not help
Details

Unable to install "App"
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402620383
--
The maximum number of apps for free development profiles has been reached.
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402620383
User Info: {
    DVTRadarComponentKey = 487925;
    MobileDeviceErrorCode = "(0xE8008021)";
    "com.apple.dtdevicekit.stacktrace" = (
    0   DTDeviceKitBase                     0x000000012646e81a DTDKCreateNSErrorFromAMDErrorCode + 233
    1   DTDeviceKitBase                     0x00000001264aff70 __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
    2   DVTFoundation                       0x000000010d16b155 DVTInvokeWithStrongOwnership + 73
    3   DTDeviceKitBase                     0x00000001264afca8 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1654
    4   IDEiOSSupportCore                   0x0000000126326e91 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.352 + 4165
    5   DVTFoundation                       0x000000010d29e7f4 __DVT_CALLING_CLIENT_BLOCK__ + 7
    6   DVTFoundation                       0x000000010d2a0436 __DVTDispatchAsync_block_invoke + 1194
    7   libdispatch.dylib                   0x00007fff68c7f6c4 _dispatch_call_block_and_release + 12
    8   libdispatch.dylib                   0x00007fff68c80658 _dispatch_client_callout + 8
    9   libdispatch.dylib                   0x00007fff68c85c44 _dispatch_lane_serial_drain + 597
    10  libdispatch.dylib                   0x00007fff68c865d6 _dispatch_lane_invoke + 363
    11  libdispatch.dylib                   0x00007fff68c8fc09 _dispatch_workloop_worker_thread + 596
    12  libsystem_pthread.dylib             0x00007fff68edaa3d _pthread_wqthread + 290
    13  libsystem_pthread.dylib             0x00007fff68ed9b77 start_wqthread + 15
);
}
--

System Information

macOS Version 10.15.6 (Build 19G46c)
Xcode 11.5 (16139)

A: Looks like you are using the free version of Apple Developer. They restrict how many devices you can push your app to, to 3 devices.
To free up space just delete the apps you already have installed by going Window -> Device and Simulators.
Then press SHIFT+CMD+K to clean the project; this worked for me!


text:
Q: Strongloop fails to install in Windows 7, sqlite3@3.0.5 Failed to exec install script I followed the strongloop pre installation requirments (http://docs.strongloop.com/display/SL/Installing+Node+and+StrongLoop+on+Windows) and everything was set without problems. However , each time I execute
npm install -g npm

the installation fails. In the npm-debug.log I see the reason for the failure is
info sqlite3@3.0.5 Failed to exec install script

sqlite3 was installed successfully in the global modules.

A: I opened my CMD in administrator's mode, and by default it opens in
c:\Windows\system32

executing
  c:\Windows\system32> npm install -g strongloop

fails with the error in the question. However, executing from the C:\ is OK.
C:\> npm install -g npm


text: Q: As an object approaches light speed does the increase in the stress/energy tensor distort space/time in the same way massive objects do? given that massive objects create gravity wells, why do objects approaching relativistic speeds not create a "gravity bow wave" due to the increase in the stress energy tensor?


text:
Q: How To make Bulk email Script using php I am making a bulk email script for 1k user and I want to send email but my script gives me error, timeout.
How to handle page timeout. any suggestion for backend run this script.
If user clicks send button then run this script backend if user close this page but script working.
    $Email_ID="";
    $queryUser=mysql_query("SELECT  `email` From `users`",$conn);
    while($User=mysql_fetch_array($queryUser))
    {
        $to = $User["email"];
        $Email_ID=$User["email"];
        $from = 'donotreply@abc.com';
        $from_name = 'Test bulk email';
        $senderMail="donotreply@abc.com";
        $senderName="abc";
        $message=$_POST["message"];
        $subject = $_POST["subject"];
        $html_content = $_POST["message"];
        $from = $senderName." <".$senderMail.">";
        $headers = "From: $from";
        $headers = "CC: jignesh.tplabs@gmail.com";
        $headers = "BCC: jignesh.tplabs@gmail.com";

        $semi_rand = md5(time());
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

        $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

        $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
        "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";

        $upload_file="";
        if(isset($_SESSION["uniqid"]))
        {
            $query=mysql_query("SELECT  * From `bulk_email_attchment` where `unique_id`='".$_SESSION["uniqid"]."' ",$conn);
            while($row=mysql_fetch_array($query))
            {
                        $files = "Attchment/".$row["name"];
                        $message .= "--{$mime_boundary}\n";
                        $fp =    @fopen($files,"rb");
                        $data =  @fread($fp,filesize($files));
                        @fclose($fp);
                        $data = chunk_split(base64_encode($data));
                        $message .= "Content-Type: application/octet-stream; name=\"".basename($files)."\"\n" .
                        "Content-Description: ".basename($files)."\n" .
                        "Content-Disposition: attachment;\n" . " filename=\"".basename($files)."\"; size=".filesize($files).";\n" .
                        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
                }
        }

        $message .= "--{$mime_boundary}--";
        $returnpath = "-f" . $senderMail;

        //send email
        $mail = mail($to, $subject, $message, $headers, $returnpath);

    }
}

A: You can set a cron script. So your email script handled by cron and run in background.

A: The Right Way: Create a php Queue, with a Named Pipe, that connects to another php script that would send the emails each time it is invoked. If you are just staring php, it'll take a while before all this is coded properly.
The Moderate but not ideal way: Set up a Cron Job to invoke your script (that would send 20 or so emails each time invoked. If your using a service like Godaddy, just google: "CronJob godaddy setup"
The Hacky Way: Have the script in a page that redirects to itself with a query string updating it on how many emails were sent:
After 20 emails for instance are sent, use the code:
$count = 20;
header('Location http://www.example.com/index.php?count='.$count);

I don't recommend using The Hacky Way because as a programmer, we should try to follow best practices, but I personally can't hold you back :)

A: Option 1
If you want to continue a script if the user aborts you can use ignore_user_abort().
// Ignore if a user aborts
ignore_user_abort(true);
set_time_limit(0);

// Send your emails here

For more information check the PHP ignore_user_abort() (documentation)[http://php.net/manual/fr/function.ignore-user-abort.php]
Option 2
Insert all submited form data into a database. You can then make a cron job that checks if there are new email jobs to submit and submit them. This way the user won't have to wait and you will not have the problem of them closing the browser.


text:
Q: JS - find all instances of a string and wrap in anchor tag I'm trying to figure out if it is possible to wrap all instances of a string with an anchor tag.
Basically on our site I want to find any instance of myBrand or myBrand.com and wrap them in an anchor like myBrand or myBrand.com.
However, I want to be able to find all instances of this no matter how far buried they are in various elements on my page and see if they already are linked, and this is where I am having an issue.
Edit
I've edited the snippet to what I have now but am still having difficulties:

document.querySelectorAll('body').forEach(function(el){
  var text = el.innerHTML.match(/myBrand/g);

  console.log(text.parentElement); // how do i get the parent?

  if(isAnchor(text.parentElement)){
    //
  }else{
      var newtext = el.innerHTML.replace(/myBrand/g, 'myBrand');
    el.innerHTML = newtext;
  }
});

function isAnchor(str){
    return /^\.*\<\/a\>/i.test(str);
}

myBrand

myBrand.com

This is a div that mentions myBrand

    This is myBrand's table header

  myBrand.com

myBrand.com

A: You can use replace with RegEx to set the innerHTML property like the following way:

document.body.innerHTML = document.body.innerHTML.replace(/myBrand(?!\.)/g, 'myBrand');
document.body.innerHTML = document.body.innerHTML.replace(/myBrand.com/g, 'myBrand.com');

  myBrand

myBrand.com

This is a div that mentions myBrand

        This is myBrand's table header

        myBrand.com

  myBrand.com

A: One problem with using innerHTML to replace the content of html is any data or events assigned to existing elements will be removed as soon as you set new html using innerHTML. And doing this at the level of document.body is a very bad idea.
So, I wrote a solution that uses text nodes instead. Text nodes cannot have events, so removing a text node and adding a new does not have any side affects (except for selection, which we can ignore for this case).

function iterateTextNodes(container, callback) {
    Array.from(container.childNodes).forEach(node => {
        if (node.nodeType === node.TEXT_NODE) {
            callback(node);
        } else if (node.tagName !== 'A') {
            /* Do not go inside anchor tags checking for text nodes,
               this get rids of the problem with nodes that are already
               inside anchor tags */
            iterateTextNodes(node, callback);
        }
    });
}

function getAnchor(href, content) {
    const anchor = document.createElement('A');
    anchor.appendChild(document.createTextNode(content));
    anchor.setAttribute('href', href);
    return anchor;
}

iterateTextNodes(document.body, function (node) {
    const parentNode = node.parentNode;
    // Check for myBrand.com first and then check for myBrand, to handle all the cases
    node.nodeValue.split('myBrand.com').forEach((string, i) => {
        i && parentNode.insertBefore(getAnchor('/', 'myBrand.com'), node);
        string.split('myBrand').forEach((string, i) => {
            i && parentNode.insertBefore(getAnchor('/', 'myBrand'), node);
            parentNode.insertBefore(document.createTextNode(string), node);
        });
    });
    parentNode.removeChild(node);
});

myBrand

myBrand.com

This is a div that mentions myBrand

    This is myBrand's table header

  myBrand.com

myBrand.com

A: You can use XPath for this:
function textContaining(phrase) {
  return document.evaluate(
    "//text()[contains(., '" + phrase + "')]",
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  )
}

You can then iterate through the results like so:
var result = textContaining(phrase)
for (var i = 0; i < result.snapshotLength; ++i) {
  var originalNode = result.snapshotItem(i)
  // ...
}

Once you've got a list of matching #text nodes, you simply need to filter out any whose .parentElement is an  tag.
Alternatively, you could use the jQuery .parents() function to check parents-of-parents, so as to account for cases like sometext, rather than just direct-child scenarios.


text:
Q: SQL Server Date Column + 7 Days less is than Today's Date I'm trying to work out a way to update a column (LostRenewalCount) if several / all conditions are met on the same row:

*

*RowSubType = 1

*Submission Status Code = BIN

*Policy Effective Date + 7 Days is Less than Todays date

Code:
update SubmissionActivitySLXStaging
set LostRenewalCount = case
                          when RowSubType = 'Renewal' then '1'
                          when [Submission Status Code] <> 'BIN' then '1'
                          when dateadd (dd, 7, [Policy Effective Date]) < GETDATE()) then '1'
                          else '0'
                       end

Any suggestions would be greatly appreciated.

A: I'd think about making one update statement per "condition" or set of conditions, like this:
UPDATE SubmissionActivitySLXStaging
   SET LostRenewalCount = 1
 WHERE RowSubType = 'Renewal'
   AND [Submission Status Code] <> 'BIN'
   AND DATEADD(DD, 7, [Policy Effective Date]) < GETDATE()

After that you can but update statements together with all the other "sets of conditions"
Reason to split it into multiple statements is that readability goes a long way!


text:
Q: Are boolean operations on TikZ shapes possible? The Situation
Many vector graphics editors (for instance, Inkscape, Adobe Illustrator and Microsoft Visio) permit the synthesis of new shapes by union, difference or intersection operators. A collection of Venn diagrams on TeXample demonstrates the use of clipping to fill unions and differences of shapes, however I have not yet seen any examples of construction of new shape outlines through boolean operations. Does this functionality exist in TikZ at all?
A Workaround
I have devised a workaround for the little diagram that I'm working on that takes advantage of Z-ordering to give the impression of a composite outline (i.e. the union of several shapes) by drawing a shape, drawing intersecting shapes and then redrawing the original shape without a line style. It is necessary to slightly shrink the redrawn shape to get constant apparent line weight all the way around:
\begin{tikzpicture}[scale=1]

% Draw all of the necessary shapes.
    \draw[fill=gray!30] ( 0.0,  0.0) circle (1cm and 0.5cm);
    \draw[fill=gray!30] ( 0.4,  0.5) circle (0.3cm);
    \draw[fill=gray!30] (-0.4, -0.5) circle (0.3cm);
    \draw[fill=gray!30] (-0.4,  0.4) circle (0.3cm);
    \draw[fill=gray!30] ( 0.4, -0.4) circle (0.3cm);

% Now draw a grey circle over the top with no outline.
    \draw[fill=gray!30,draw=none] (0,0) circle (0.99cm and 0.49cm);
    \draw[] (0,0) node {Q.M.};
\end{tikzpicture}

Needless to say this is probably the wrong way to go about this problem. Any better ways?
Example Output
at 200% zoom, as viewed in Evince.

Further Explorations
In my dabbling I have determined that fairly interesting effects can be had by judicious z-ordering of shapes with and without borders, for instance, giving the appearance of an ellipsoid with protrusions in front and behind. Shared in the hope it might be useful to someone.
\begin{tikzpicture}[scale=1]
% Draw lobes behind.
    \draw[fill=gray!30] ( 0.4,  0.4) circle (0.3cm);
    \draw[fill=gray!30] (-0.4, -0.4) circle (0.3cm);
% Draw ellipsoid.
    \draw[fill=gray!30] ( 0.0,  0.0) circle (1cm and 0.5cm);
% Draw lobes in front.
    \draw[fill=gray!30] (-0.4,  0.4) circle (0.3cm);
    \draw[fill=gray!30] ( 0.4, -0.4) circle (0.3cm);
% Now draw a grey circle over the top with no outline,
% shrunken to only clip a section of the lobes in front.
    \draw[fill=gray!30,draw=none] (0,0) circle (0.80cm and 0.35cm);
    \draw[] (0,0) node {Q.M.};
\end{tikzpicture}

A: It does seem, as Caramdir says in the comments, that the ideal way to do this would be to separate the drawing from the filling and do all of the drawing first and then the filling afterwards.  I don't think that this is doable as a single preexisting command, but where there's a TeX there's a TikZ, as the saying goes.  Here's a way that works by using layers.
Edit: Using the technique in "Z-level" in TikZ it is now possible to collapse the commands a little so that there's no need to introduce a new high-level command.  (Original solution left in for comparison.)  Caramdir's solution is probably the simplest when it is possible to give all the paths in a single command.  If that is not (for some reason) possible, the following is more adaptable.
\documentclass{standalone}
% \url{https://tex.stackexchange.com/q/11512/86}
\usepackage{tikz}

\pgfdeclarelayer{back}
\pgfsetlayers{back,main}

\def\drawfill#1;{
  \fill[gray!30] #1;
\begin{pgfonlayer}{back}
  \draw[line width=2pt] #1;
\end{pgfonlayer}}

\tikzset{%
  on layer/.code={
    \pgfonlayer{#1}\begingroup
    \aftergroup\endpgfonlayer
    \aftergroup\endgroup
  },%
  draw on back/.style={
    preaction={
      draw,
      on layer=back,
      line width=2pt
    },
    gray!30
  }
}

\begin{document}
\begin{tikzpicture}

\drawfill ( 0.0,  0.0) circle (1cm and 0.5cm);
\drawfill ( 0.4,  0.5) circle (0.3cm);
\drawfill (-0.4, -0.5) circle (0.3cm);
\drawfill (-0.4,  0.4) circle (0.3cm);
\drawfill ( 0.4, -0.4) circle (0.3cm);

    \draw[] (0,0) node {Q.M.};

\begin{scope}[yshift=-2cm]

\fill[draw on back] ( 0.0,  0.0) circle (1cm and 0.5cm);
\fill[draw on back] ( 0.4,  0.5) circle (0.3cm);
\fill[draw on back] (-0.4, -0.5) circle (0.3cm);
\fill[draw on back] (-0.4,  0.4) circle (0.3cm);
\fill[draw on back] ( 0.4, -0.4) circle (0.3cm);

    \draw[] (0,0) node {Q.M.};

\end{scope}
\end{tikzpicture}
\end{document}

Notice the extra large line width since half of the line width gets covered by the fills.

A: I just realized: There is a way to reuse paths: pre- and postactions.
\documentclass{minimal}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
    \draw[line width=0.8pt,postaction={gray!30,fill}]
        ( 0.0,  0.0) circle (1cm and 0.5cm)
        ( 0.4,  0.5) circle (0.3cm)
        (-0.4, -0.5) circle (0.3cm)
        (-0.4,  0.4) circle (0.3cm)
        ( 0.4, -0.4) circle (0.3cm);

    \draw[] (0,0) node {Q.M.};
\end{tikzpicture}
\end{document}

As in Andrew's solution the line width needs to be twice the normal line width (the default line width if 0.4pt). Note also that by listing all the shapes in a single \draw statement, they are considered to belong to a single path.


text:
Q: Joining multiple sources using mapping dataflows I have seen many examples of joining 2 sources in mapping dataflows but cannot grasp the concept clearly, and maybe join is not an answer to my problem after all.
I have few csv files in blob storage.
All different names and different columns.
for example:

*

*Customer

*Site

*service

*Vendor

from data perspective all tables have some sort of connection to another. You could easily join these tables together in sql using Pk and FK's.
What I want is, to get all these tables into one output file.
I am not sure if I should be using Join in ADF data flow, or UNION or merge in copy activity??
can someone help please!
Thanks

A: In ADF, you will build Joins visually inside the Data Flow component. Add a Data Flow activity to your pipeline canvas and inside of the data flow designer, add your source and a Join transformation. That is where you can set the relationships and join types.

A: You can join two sources in Azure Data Factory.
Create Data Flow Activity in Azure Data Factory.

In Data Flow, add Sources from blob storage and Select Join as shown in below image.

In Join activity, you can Select join type, also you can add Condition to join multiple sources. Refer below image.

Finally add Sink file and Run Pipeline.


text:
Q: Use iOS tableView to make menu? My app is a tab bar application. I have a more tab, and in that more tab I would like to have a table view with each row pointing to another screen. I thought I could accomplish this in storyboard by just control dragging each static row to a view controller but when I click the table rows in the simulator it crashes.

*

*How do I use iOS TableView to make a simple menu with static rows?

A: Figured it out. Embed the table view in a navigation controller.


text:
Q: How to find date of Second Sunday of March in Hive for any year? I want to retrieve the date of every second sunday of March for any given year in Hive.

A: select date_add("1901-03-01",cast(7-date_format("1901-03-01",'u') as int)+7);

A: This is how you do it. In the below query, All you need to do is change your year value and you will get your output.
SELECT  if(cast(from_unixtime(unix_timestamp('2019-03-14','yyyy-MM-dd'), 'u') AS int) ==7, date_sub(from_unixtime(unix_timestamp('2019-03-15','yyyy-MM-dd')), cast(from_unixtime(unix_timestamp('2019-03-15','yyyy-MM-dd'), 'u') AS int)), date_sub(from_unixtime(unix_timestamp('2019-03-14','yyyy-MM-dd')),cast(from_unixtime(unix_timestamp('2019-03-14','yyyy-MM-dd'), 'u') AS int)));

If it works for you, do not forget to thumbs up on the answer. :)
Spent half n hour to get to this, :)


text:
Q: why does gcc(default version on openSUSE 11.3) give an error on the statement int *p=malloc(sizeof(int));? malloc returns a void pointer.so why is it not working for me without typecasting the return value?
The error pretty clear said that gcc is not allowing conversion from void* to int*.

A: In C, you don't have to cast. In fact it's a bad idea to cast there since it can cause certain subtle errors.
However, casting is required in C++ so that would be my first guess, that you're somehow invoking the C++ compiler. Perhaps your source files are *.cpp or *.C both of which may be auto-magigically treated as C++ rather than C.
See here for more detail:

C++ source files conventionally use one of the suffixes '.C', '.cc', '.cpp', '.CPP', '.c++', '.cp', or '.cxx'; C++ header files often use '.hh', '.hpp', '.H', or (for shared template code) '.tcc'; and preprocessed C++ files use the suffix '.ii'. GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the same way as for compiling C programs (usually with the name gcc).

The fact that it knows you're trying to convert void* to int* means that you have a valid malloc prototype in place so I can't see it being anything other than the imposition of C++ rules.

A: Without code I can't help you properly, but you can try this:
p = (int*)malloc(sizeof(int));

Give more info about what you want to do and what you are allocating.


text:
Q: Parsing HTML into NSAttributedText - how to set font? I am trying to get a snippet of text that is formatted in html to display nicely on an iPhone in a UITableViewCell.
So far I have this:
NSError* error;
NSString* source = @"Nice try, Phil";
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithData:[source dataUsingEncoding:NSUTF8StringEncoding]
                                                           options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                     NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
                                                              documentAttributes:nil error:&error];

This kind of works. I get some text that has 'Nice' in bold! But... it also sets the font to be Times Roman! This is not the font face I want.
I am thinking I need to set something in the documentAttributes, but, I can't find any examples anywhere.

A: The answers above all work OK if you're doing the conversion at the same time as creating the NSAttributedString. But I think a better solution, which works on the string itself and therefore doesn't need access to the input, is the following category:
extension NSMutableAttributedString
{
    func convertFontTo(font: UIFont)
    {
        var range = NSMakeRange(0, 0)

        while (NSMaxRange(range) < length)
        {
            let attributes = attributesAtIndex(NSMaxRange(range), effectiveRange: &range)
            if let oldFont = attributes[NSFontAttributeName]
            {
                let newFont = UIFont(descriptor: font.fontDescriptor().fontDescriptorWithSymbolicTraits(oldFont.fontDescriptor().symbolicTraits), size: font.pointSize)
                addAttribute(NSFontAttributeName, value: newFont, range: range)
            }
        }
    }
}

Use as:
let desc = NSMutableAttributedString(attributedString: *someNSAttributedString*)
desc.convertFontTo(UIFont.systemFontOfSize(16))

Works on iOS 7+

A: I actually found a working solution to this problem:
Changing the font in your HTML response string before it gets parsed.
NSString *aux = [NSString stringWithFormat:@"%@", htmlResponse];

Example:
NSString *aux = [NSString stringWithFormat:@"%@", [response objectForKey:@"content"]];

Swift version:
let aux = "\(htmlResponse)"

A: Improving on Victor's solution, including color:
extension UILabel {
      func setHTMLFromString(text: String) {
          let modifiedFont = NSString(format:"%@", text) as String

          let attrStr = try! NSAttributedString(
              data: modifiedFont.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
              options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding],
              documentAttributes: nil)

          self.attributedText = attrStr
      }
  }

For this to work you will also need YLColor.swift of the uicolor to hex conversion https://gist.github.com/yannickl/16f0ed38f0698d9a8ae7

A: Using of NSHTMLTextDocumentType is slow and hard to control styles. I suggest you to try my library which is called Atributika. It has its own very fast parser. Also you can have any tag names and define any style for them.
Example:
let str = "Nice try, Phil".style(tags:
    Style("strong").font(.boldSystemFont(ofSize: 15))).attributedString

label.attributedText = str

You can find it here https://github.com/psharanda/Atributika

A: Joining together everyone's answers, I made two extensions that allow setting a label with html text. Some answers above did not correctly interpret the font family in the attributed strings. Others were incomplete for my needs or failed in other ways. Let me know if there's anything you'd like me to improve on.
I hope this helps someone.
extension UILabel {
    /// Sets the label using the supplied html, using the label's font and font size as a basis.
    /// For predictable results, using only simple html without style sheets.
    /// See https://stackoverflow.com/questions/19921972/parsing-html-into-nsattributedtext-how-to-set-font
    ///
    /// - Returns: Whether the text could be converted.
    @discardableResult func setAttributedText(fromHtml html: String) -> Bool {
        guard let data = html.data(using: .utf8, allowLossyConversion: true) else {
            print(">>> Could not create UTF8 formatted data from \(html)")
            return false
        }

        do {
            let mutableText = try NSMutableAttributedString(
                data: data,
                options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue],
                documentAttributes: nil)
            mutableText.replaceFonts(with: font)
            self.attributedText = mutableText
            return true
        } catch (let error) {
            print(">>> Could not create attributed text from \(html)\nError: \(error)")
            return false
        }
    }
}

extension NSMutableAttributedString {

    /// Replace any font with the specified font (including its pointSize) while still keeping
    /// all other attributes like bold, italics, spacing, etc.
    /// See https://stackoverflow.com/questions/19921972/parsing-html-into-nsattributedtext-how-to-set-font
    func replaceFonts(with font: UIFont) {
        let baseFontDescriptor = font.fontDescriptor
        var changes = [NSRange: UIFont]()
        enumerateAttribute(.font, in: NSMakeRange(0, length), options: []) { foundFont, range, _ in
            if let htmlTraits = (foundFont as? UIFont)?.fontDescriptor.symbolicTraits,
                let adjustedDescriptor = baseFontDescriptor.withSymbolicTraits(htmlTraits) {
                let newFont = UIFont(descriptor: adjustedDescriptor, size: font.pointSize)
                changes[range] = newFont
            }
        }
        changes.forEach { range, newFont in
            removeAttribute(.font, range: range)
            addAttribute(.font, value: newFont, range: range)
        }
    }
}

A: A more generic approach is to look at the font traits while enumerating, and create a font with the same traits (bold, italic, etc.):
extension NSMutableAttributedString {

    /// Replaces the base font (typically Times) with the given font, while preserving traits like bold and italic
    func setBaseFont(baseFont: UIFont, preserveFontSizes: Bool = false) {
        let baseDescriptor = baseFont.fontDescriptor
        let wholeRange = NSRange(location: 0, length: length)
        beginEditing()
        enumerateAttribute(.font, in: wholeRange, options: []) { object, range, _ in
            guard let font = object as? UIFont else { return }
            // Instantiate a font with our base font's family, but with the current range's traits
            let traits = font.fontDescriptor.symbolicTraits
            guard let descriptor = baseDescriptor.withSymbolicTraits(traits) else { return }
            let newSize = preserveFontSizes ? descriptor.pointSize : baseDescriptor.pointSize
            let newFont = UIFont(descriptor: descriptor, size: newSize)
            self.removeAttribute(.font, range: range)
            self.addAttribute(.font, value: newFont, range: range)
        }
        endEditing()
    }
}

A: Figured it out. Bit of a bear, and maybe not the best answer.
This code will go through all the font changes. I know that it is using "Times New Roman" and "Times New Roman BoldMT" for the fonts.
But regardless, this will find the bold fonts and let me reset them. I can also reset the size while I'm at it.
I honestly hope/think there is a way to set this up at parse time, but I can't find it if there is.
- (void)changeFont:(NSMutableAttributedString*)string
{
    NSRange range = (NSRange){0,[string length]};
    [string enumerateAttribute:NSFontAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
    UIFont* currentFont = value;
    UIFont *replacementFont = nil;

    if ([currentFont.fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch].location != NSNotFound) {
        replacementFont = [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:25.0f];
    } else {
        replacementFont = [UIFont fontWithName:@"HelveticaNeue-Thin" size:25.0f];
    }

    [string addAttribute:NSFontAttributeName value:replacementFont range:range];
}];

}

A: Thanks for the answers, I really liked the extension but I have not converted to swift yet.  For those old schoolers still in Objective-C this should help a little :D
-(void) setBaseFont:(UIFont*)font preserveSize:(BOOL) bPreserve {

UIFontDescriptor *baseDescriptor = font.fontDescriptor;

[self enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, [self length]) options:0 usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {

    UIFont *font = (UIFont*)value;
    UIFontDescriptorSymbolicTraits traits = font.fontDescriptor.symbolicTraits;
    UIFontDescriptor *descriptor = [baseDescriptor fontDescriptorWithSymbolicTraits:traits];
    UIFont *newFont = [UIFont fontWithDescriptor:descriptor size:bPreserve?baseDescriptor.pointSize:descriptor.pointSize];

    [self removeAttribute:NSFontAttributeName range:range];
    [self addAttribute:NSFontAttributeName value:newFont range:range];

}];    }

Happy Coding!
--Greg Frame

A: Here is an extension for NSString that returns an NSAttributedString using Objective-C.
It correctly handles a string with HTML tags and sets the desired Font and Font color while preserving HTML tags including BOLD, ITALICS...
Best of all it does not rely on any HTML  markers to set the font attributes.
@implementation NSString (AUIViewFactory)

- (NSAttributedString*)attributedStringFromHtmlUsingFont:(UIFont*)font fontColor:(UIColor*)fontColor
{
    NSMutableAttributedString* mutableAttributedString = [[[NSAttributedString alloc] initWithData:[self dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding)} documentAttributes:nil error:nil] mutableCopy]; // parse text with html tags into a mutable attributed string
    [mutableAttributedString beginEditing];
    // html tags cause font ranges to be created, for example "This text is bold now." creates three font ranges: "This text is " , "bold" , " now."
    [mutableAttributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, mutableAttributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL* stop)
    { // iterate every font range, change every font to new font but preserve symbolic traits such as bold and italic (underline and strikethorugh are preserved automatically), set font color
        if (value)
        {
            UIFont* oldFont = (UIFont*)value;
            UIFontDescriptor* fontDescriptor = [font.fontDescriptor fontDescriptorWithSymbolicTraits:oldFont.fontDescriptor.symbolicTraits];
            UIFont* newFont = [UIFont fontWithDescriptor:fontDescriptor size:font.pointSize];
            [mutableAttributedString removeAttribute:NSFontAttributeName range:range]; // remove the old font attribute from this range
            [mutableAttributedString addAttribute:NSFontAttributeName value:newFont range:range]; // add the new font attribute to this range
            [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:fontColor range:range]; // set the font color for this range
        }
    }];
    [mutableAttributedString endEditing];
    return mutableAttributedString;
}

@end

A: Swift 4+ update of UILabel extension
extension UILabel {
    func setHTMLFromString(text: String) {
        let modifiedFont = NSString(format:"%@" as NSString, text)

        let attrStr = try! NSAttributedString(
            data: modifiedFont.data(using: String.Encoding.unicode.rawValue, allowLossyConversion: true)!,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue],
            documentAttributes: nil)

        self.attributedText = attrStr
    }
}

iOS 9+
extension UILabel {
    func setHTMLFromString(htmlText: String) {
        let modifiedFont = NSString(format:"%@" as NSString, htmlText) as String

        //process collection values
        let attrStr = try! NSAttributedString(
            data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue],
            documentAttributes: nil)

        self.attributedText = attrStr
    }
}

A: Yes, there is an easier solution. Set the font in the html source!
NSError* error;
NSString* source = @"Nice try, Phil";
source = [source stringByAppendingString:@""];
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithData:[source dataUsingEncoding:NSUTF8StringEncoding]
                                                           options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                     NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
                                                              documentAttributes:nil error:&error];

Hope this helps.

A: Swift 5  Solution for UILabel and UITextView
extension UITextView {
func setHTMLFromString(htmlText: String) {
    let modifiedFont = String(format:"%@", htmlText)

    let attrStr = try! NSAttributedString(
        data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
        options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue],
        documentAttributes: nil)

    self.attributedText = attrStr
}

}
extension UILabel {
func setHTMLFromString(htmlText: String) {
    let modifiedFont = String(format:"%@", htmlText)

    let attrStr = try! NSAttributedString(
        data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
        options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue],
        documentAttributes: nil)

    self.attributedText = attrStr
}

}
Usage for UILabel
self.label.setHTMLFromString(htmlText: htmlString)

Usage for UITextView
self.textView.setHTMLFromString(htmlText: htmlString)

Output

A: Swift 2 version, based on the answer given by Javier Querol
extension UILabel {
    func setHTMLFromString(text: String) {
        let modifiedFont = NSString(format:"%@", text) as String

        let attrStr = try! NSAttributedString(
            data: modifiedFont.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding],
            documentAttributes: nil)

        self.attributedText = attrStr
    }
}

Swift 3.0 and iOS 9+
extension UILabel {
    func setHTMLFromString(htmlText: String) {
        let modifiedFont = String(format:"%@", htmlText)

        let attrStr = try! NSAttributedString(
            data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
            documentAttributes: nil)

        self.attributedText = attrStr
    }
}

Swift 5 and iOS 11+
extension UILabel {
    func setHTMLFromString(htmlText: String) {
        let modifiedFont = String(format:"%@", htmlText)

        let attrStr = try! NSAttributedString(
            data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
            options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue],
            documentAttributes: nil)

        self.attributedText = attrStr
    }
}

A: #import "UILabel+HTML.h"

@implementation UILabel (HTML)

- (void)jaq_setHTMLFromString:(NSString *)string {

    string = [string stringByAppendingString:[NSString stringWithFormat:@"",
                                              self.font.fontName,
                                              self.font.pointSize]];
    self.attributedText = [[NSAttributedString alloc] initWithData:[string dataUsingEncoding:NSUnicodeStringEncoding]
                                                           options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                     NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                                documentAttributes:nil
                                                             error:nil];
}

@end

This way you don't need to specify which font you want, it will take the label font and size.

A: Swift 3 String extension including a nil font. The property without font is taken from other SO question, do not remember which one :(
extension String {
    var html2AttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else {
            return nil
        }

        do {
            return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
        }
        catch {
            print(error.localizedDescription)
            return nil
        }
    }

    public func getHtml2AttributedString(font: UIFont?) -> NSAttributedString? {
        guard let font = font else {
            return html2AttributedString
        }

        let modifiedString = "\(self)";

        guard let data = modifiedString.data(using: .utf8) else {
            return nil
        }

        do {
            return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
        }
        catch {
            print(error)
            return nil
        }
    }
}

A: *

*Swift Solution

The below approach works. You can very well provide the font family, font size, and color in this approach. Feel free to suggest changes or any better way of doing this.
extension UILabel {

func setHTMLFromString(htmlText: String,fontFamily:String,fontColor:String) {

    let modifiedFont = String(format:"%@", htmlText)

    do{
        if let valData = modifiedFont.data(using: .utf8){
            let attrStr = try NSAttributedString(data: valData, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html.rawValue], documentAttributes: nil)
            self.attributedText = attrStr
        }
    }catch{
        print("Conversion failed with \(error)")
        self.attributedText = nil
    }
}

A: Actually, an even easier and cleanr way exists. Just set the font after parsing the HTML:
 NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
                                                                     options:@{
                                                                               NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                               NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                                          documentAttributes:nil error:nil];
    [text addAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Lato-Regular" size:20]} range:NSMakeRange(0, text.length)];


text:
Q: Unitarity Gauge : how to undo the gauge transformation I will simplify the argument.
Let's consider a Gauge Boson (like the gauged one of U(1), $A_\mu$). Then, consider the Higgs boson with exponential representation, then $$H = e^{i\pi(x)/v}\left(\begin{array}{c}0 \\ v+h(x) \end{array}\right)$$ where $\pi$ is the goldstone boson coming from SSB of U(1) and $v$ is the Higgs vev.
Let's do a Gauge transformation to kill the $\pi$. Under U(1) gauge transformation of parameter $\alpha(x)$ the field transforms as
$$
A_\mu(x) \rightarrow A'_\mu(x) = A_\mu(x) + \frac{1}{e}\partial_\mu\alpha(x)
$$
$$
\pi(x) \rightarrow \pi'(x) = \pi(x) + \alpha(x) v
$$
so I choose $\alpha(x) = -\pi(x)/v$.
The Higgs boson becomes $$H=\left(\begin{array}{c}0\\v+h(x)\end{array}\right)$$ and the $A_\mu$ becomes $$A'_\mu = A_\mu -\frac{1}{e}\partial_\mu\frac{\pi(x)}{v}.$$
Now, the question is: How can I perform the inverse gauge transformation?
If I use the same rules give above and I choose now $\alpha(x) =+\pi(x)/v$ I get
$$
A'_\mu \rightarrow A_\mu +\frac{1}{e}\partial_\mu\frac{\pi(x)}{v} - \frac{1}{e}\partial_\mu\frac{\pi(x)}{v} -\frac{1}{e}\frac{\partial_\mu \pi(x)}{v} = A'_\mu
$$
where I performed the transformation over $A_\mu$ and $\partial_\mu\pi(x)$. So, it seems I can't define the inverse transformation in the usual way. I should expect $A'_\mu \rightarrow A_\mu$. Since $\pi(x)$ transforms under gauge transformation, does its derivative transforms in the same way?$$\partial_\mu\pi(x) \rightarrow \partial_\mu\pi'(x) = \partial_\mu\pi(x) + \partial_\mu\alpha(x) v$$


text:
Q: Merging two documents from same collection - mongoose I have multiple documents in a collection with data field as array of string. I want to perform following operations:-

*

*Compare data field of one selected document with other documents data field.

*If any one of the value from selected data field matches with other document data field, I want to merge the documents together

Input:
{
  "_id": "6323ec74eee734b4ba790f4c",
  "data": [
    "test 1", "test 2", "test 3"
  ],
  "__v": 0
}

{
  "_id": "6323ec74eee78fb4ba790fd3",
  "data": [
    "test 1", "test 8", "test 100"
  ],
  "__v": 0
}

{
  "_id": "6323ec74eee78fb4ba790f98",
  "data": [
    "test 83", "test 2", "test 123"
  ],
  "__v": 0
}

Newly merged document will be like
Output:
{
  "_id": "6323ec74eee78fb4ba790f98",
  "data": [
    "test 1", "test 2", "test 3", "test 8", "test 100", "test 83", "test 123"
  ],
  "__v": 0
}

A: When you want to group all the documents, you need to add {_id: null}
It means group all documents.
So you can try this:
  db.collection.aggregate([
  {
    "$unwind": "$data"
  },
  {
    $group: {
      _id: null,
      data: {
        "$addToSet": "$data"
      }
    }
  }
])

output:
[
  {
    "_id": null,
    "data": [
      "test 2",
      "test 8",
      "test 100",
      "test 83",
      "test 123",
      "test 3",
      "test 1"
    ]
  }
]


text:
Q: Displaying hints via a status bar in a non-modal form The canonical method of displaying hints in a status bar is via the following code:
    Constructor TMyForm.Create;
    begin
     inherited create (nil);
     ...
     Application.OnHint:= MyHint;
     ...
    end;

    procedure TMyForm.MyHint (Sender: TObject);
    begin
     sb.simpletext:= Application.Hint;
    end;

    procedure TMyForm.FormClose(Sender: TObject; var Action: TCloseAction);
    begin
     Application.OnHint:= nil;
     ...
    end;

The above works fine when a program consists of modal forms, but it is problematic when non-modal forms are used (not necessarily MDI). In these cases, a non-modal form is created and Application.OnHint is assigned to a procedure within the non-modal form; the status bar displays hints from the form. But should another non-modal form be created, Application.OnHint is now assigned to the same procedure within the second form. Moving the mouse over the control with a hint in the first, non-active, form causes that hint to be displayed in the status bar of the second form!
How can I cause each non-modal form to display hints that originate only from its own controls? One possibility is removing hints from controls when a form becomes inactive and restoring them when the form becomes active again, but that is very inelegant. The problem is with the Application.OnHint event.

A: It turns out that the OP simply wants each form's status bar to display all hints from that form (not minding it also displaying hints from other forms as well).
So this is trivial. Just give all your forms a status bar and drop a TApplicationEvents component onto each form. Create a handler for each component's OnHint event:
procedure TForm6.ApplicationEvents1Hint(Sender: TObject);
begin
  StatusBar1.SimpleText := Application.Hint;
end;

And then everything will just work:

Update
It seems that the OP does mind that. One solution, then, is to do like this:
procedure TForm6.ApplicationEvents1Hint(Sender: TObject);
begin
  if IsHintFor(Self) then
    StatusBar1.SimpleText := Application.Hint
  else
    StatusBar1.SimpleText := '';
end;

on all your forms. But only one time do you need to define the helper function
function IsHintFor(AForm: TCustomForm): Boolean;
begin
  Result := False;
  var LCtl := FindDragTarget(Mouse.CursorPos, True);
  if Assigned(LCtl) then
    Result := GetParentForm(LCtl) = AForm;
end;

This unfortunately does waste a few CPU cycles, since it calls FindDragTarget several times each time Application.Hint is changed, in a sense needlessly since the VCL already has called it once. But this shouldn't be detectable.

Update 2
To make this work also for menus (which may also be navigated using the keyboard, in which case the mouse cursor may be anywhere on the screen), I think the following additions will suffice:
Declare a global variable next to the IsHintFor helper function:
var
  GCurrentMenuWindow: HWND;

function IsHintFor(AForm: TCustomForm): Boolean;

and extend this function like so:
function IsHintFor(AForm: TCustomForm): Boolean;
begin
  if GCurrentMenuWindow <> 0 then
    Result := Assigned(AForm) and (GCurrentMenuWindow = AForm.Handle)
  else
  begin
    Result := False;
    var LCtl := FindDragTarget(Mouse.CursorPos, True);
    if Assigned(LCtl) then
      Result := GetParentForm(LCtl) = AForm;
  end;
end;

Then, to make menu bars work, add the following to each form class with a menu bar:
    procedure WMEnterMenuLoop(var Message: TWMEnterMenuLoop); message WM_ENTERMENULOOP;
    procedure WMExitMenuLoop(var Message: TWMExitMenuLoop); message WM_EXITMENULOOP;
  end;

implementation

procedure TForm6.WMEnterMenuLoop(var Message: TWMEnterMenuLoop);
begin
  inherited;
  GCurrentMenuWindow := Handle;
end;

procedure TForm6.WMExitMenuLoop(var Message: TWMExitMenuLoop);
begin
  inherited;
  GCurrentMenuWindow := 0;
end;

Finally, to make context menus work, add the following to the unit with the helper function:
type
  TPopupListEx = class(TPopupList)
  protected
    procedure WndProc(var Message: TMessage); override;
  end;

{ TPopupListEx }

procedure TPopupListEx.WndProc(var Message: TMessage);
begin
  inherited;
  case Message.Msg of
    WM_INITMENUPOPUP:
      for var LMenu in PopupList do
        if TObject(LMenu) is TPopupMenu then
          if TPopupMenu(LMenu).Handle = Message.WParam then
          begin
            var LComponent := TPopupMenu(LMenu).PopupComponent;
            if LComponent is TControl then
            begin
              var LForm := GetParentForm(TControl(LComponent));
              if Assigned(LForm) then
                GCurrentMenuWindow := LForm.Handle;
            end;
            Break;
          end;
    WM_EXITMENULOOP:
      GCurrentMenuWindow := 0;
  end;
end;

initialization
  FreeAndNil(PopupList);
  PopupList := TPopupListEx.Create;

end.

Result:

Disclaimer: Not fully tested.

A: I'm going to give a partial answer as my researches into this topic have yielded something that works on one form but not on another.
With regard to the form where my solution works, there is a TDBGrid along with some buttons; the grid has a defined hint. The solution for this form is as follows:
    uses
      Controls;

    type
     TMyForm = class (TForm)
     ...
     public
      Procedure CMMouseEnter (var msg: TMessage); message CM_MouseEnter;
      Procedure CMMouseLeave (var msg: TMessage); message CM_MouseLeave
     end;

    Procedure TMyForm.CMMouseEnter (var msg: TMessage);
    begin
     inherited;
     if msg.lparam = integer (dbGrid1)
      then sb.simpletext:= dbGrid1.Hint
    end;

    Procedure TMyForm.CMMouseLeave(var msg: TMessage);
    begin
     inherited;
     if msg.lparam = integer (dbGrid1)
      then sb.simpletext:= ''
    end;

Whilst this code works, I don't like that integer (dbGrid1) cast; is there a better way of doing this?
Where doesn't this code work? Another form has a page control holding two tabsheets; on one tabsheet there are speedbuttons with hints, and on the other tabsheet there is a dbgrid with a hint. Writing similar code to the above doesn't work - the value of msg.lparam upon entering CMMouseEnter would appear to be the value of casting the page control (maybe its handle?). So how does one get to the controls with defined hints?


text:
Q: How do I find the names of classes in modules for TypeScript So in this code:
import * as fs from "fs"

class FsAsyncFactory {

    private static fsSync: any

}

export default FsAsyncFactory

I've put the type of this prop private static fsSync: any as any but it's going to be the fs variable imported at the top - how do I figure out what the class is called?
I guessed something like FileSystem but it didn't work. I don't have a deep enough understanding of TypeScript to figure it out.
I have "@types/node": "^8.0.50", in my dev dependencies and I've gone into node_modules/@types/node/index.d.ts but I can't see anything that quite makes sense? Thanks!

A: You can use the "type of" command of typescript.
import * as fs from "fs"

class FsAsyncFactory {

   private static fsSync: typeof fs

}

export default FsAsyncFactory

And then inside your class
constructor(){
 //...//
 FsAsyncFactory.fsSync. //ide recognizes fsSync is of type "fs" and gives you full prediction of fs functions
 //...//
}

Question: What is this typeof and why cant I use just class names?
Basically as I understand by reading the node/index.d.ts the fs is just a module that is being exported. Basically an object with some typed functions with their own documentation. In that case we don't have a class name or an interface to declare our other variables which are equal to fs. The typeof command of typescript is a type query, basically if no class or interface is implemented on the source variable it will just expect the same properties of the source to be presented in the target.
Another approach with your issue could be the use of Type Aliases
import * as fs from "fs"
type FileSystem = typeof fs

class FsAsyncFactory {

   private static fsSync: FileSystem

}

export default FsAsyncFactory

This will create a new type called FileSystem which will expect every object which is declared as FileSystem type, to implement every function of the fs module.
Question: How can I use Bluebird's promisifyAll with typescript?
import * as fs from "fs"
import * as Bluebird from "bluebird"

const fsProm : FileSystem = Bluebird.promisifyAll(fs)

fsProm.writeFile('filename','some data') // Typescript error function expects at least 3 parameters
   .then(console.log)

Unfortunately, from my point of view promisifyAll will change a strict typed function to something else without leaving any definitions of what changed, that is very bad for typescript. After some search I couldn't find any solid solution that will work on all cases, check this issue.
Maybe your best bet is to declare your promisidied variable to type any and continue working without intellisense.


text:
Q: openerp gtk client 6.1 - form tab label In the new openERP gtk client 6.1, a new feature is causing confusing at times. the tab label of a certain record in form view is now as such:
Object: (Id, Name)
instead of the good 'ol
Object
Sometimes it just adds the name of the record and not both name and id, depends on the object's name whether it's a many2one field or not.
Ive been trying to pinpoint where in the new gtk client code is this added but i cant find it. i think it's in /bin/widget/view/form_gtk but im not sure.
another thing, once you good people tell me where the new code is added it's easy to modify the client on linux based OS, but how about patching the client on windows instead of building a new exe installer? i would very much appreciate it if someone could share some insight about this matter. I've already seen this Create exe open erp client GTK on launchpad, but when i followed it step by step on XP, i encountered errors. i think it's outdated. Thanks in advance

A: In the project lp:openerp-tools you will find the solution. There is the official script with the .exe is created.
BTW, you dont need to recreate the .exe, you can run python on windows as an script (exactly as in Linux does, I don give support for windows never, but i know in end clients it is frequent problem.
Regards, and i hope it can help you.

A: Noup..
In openerp-tools where the tools to build the .exe, not the tag problem, this is really easy if you know a little of python + gtk.
But BTW it should be cool if you post the solution you found for future people that need something like you...
Regards.


text:
Q: Get link to particular paragraph in HTML without id I want to direct my readers to a particular place in a third-party HTML webpage. The paragraph of interest looks like this:

qwerty

blah blah

Like you can see, none of the elements have ids (so this http://webpage/#id wouldn't work). However, the word within the
 tag is unique and cannot be found anywhere else in the document. Is there a way to provide a link that will take users directly to that spot on the webpage?

A: You can't link to just some text in the page, so it's not possible if you don't control the site.
The closest thing you can do that I'm aware of is use citebite, which creates a new page with an id inserted so it can take you to that section. However, it's pretty hit or miss in my experience.

A: Better way to do this work is using id attribute in element.
But you can use jquery :contains selector to find element that contain hash. Then get top position of element and scroll window to it position.

window.location.hash = "id";

var hash = window.location.hash.replace("#", "");
var scrollTop = $("h1:contains(" + hash + ")").offset().top;

window.scrollTo(0, scrollTop);
div {
    height: 300px;
}

id

id2


text:
Q: Continuous complex functions on a compact set From real analysis I know that every continuous real-valued function on a compacted set is bounded. I am just thinking will this also hold for complex-valued function? Or do I need to replace "continuous" with other thing like "holomorphic" to make it true?

A: Consider the following fact from general topology:
Let $X,Y$ be topological spaces. If $f: X \to Y$ is continuous it maps compact sets to compact sets.
In particular, for $Y = \mathbb C$ a continuous map $f$ maps compact sets to compact sets.
Also, by Heine-Borel, a compact set in $\mathbb C$ is closed and bounded. Therefore the image of the compact set is bounded therefore $f$ is bounded.


text:
Q: How do I update EntityFramework in most elegant way? Here's my model - two tables Contacts and Companies. Contacts are bound to each Company with their Company_ID property And I use EntityFramework.
When I want to add contacts to a company, I go through the ones I want to add and change their Company_ID property to the Company_ID of the company I want to add them into.
But then it doesn't update the Contacts in that Company, they are the same old ones unless I do the following:
Context.Dispose();
Context = new CompanyContactsEntity();

But this is not efficient as I just want to update the current instance and NOT create a new one.

A: Try to avoid assigning the Identifiers. try to assign the entity reference instead.
For instance:
Company company = ...//look-up/cerate for your company, etc.
Contact contact = ...//look-up/create for the contact
contact.Company = company; // Assign an instance reference but not the ID


text:
Q: How can I upload a blob as file? I tried upload a blob to firebase with below the code. But, I didn't succeed. Could you please help me.
My reference: https://firebase.google.com/docs/storage/web/upload-files#upload_from_a_blob_or_file
var auth = firebase.auth();
var storageRef = firebase.storage().ref();

function mUpload() {
var i_note = document.getElementById('note').value;

var mblob = new Blob([i_note], {type: "text/plain;charset=utf-8"});

// var file = new File([mblob], "filename")
var file = new File([mblob], "filename", {type: 'text/plain', lastModified: Date.now()});

var metadata = {
'contentType': file.type
};

storageRef.child('Books/myfile.txt').put(file, metadata).then(function(snapshot) {
var url = snapshot.metadata.downloadURLs[0];
}).catch(function(error) {
console.error('Upload failed:', error);
});
}

Very very thanks for helping..


text:
Q: How to improve the speed of a Laravel page that that queries for a large amount of data It takes to long for the server to respond to the query.  Part of the problem is running the data through a Laravel API Resource to restrict what data is delivered.
I am already using eager loading to improve the speed of the query and have used explain to ensure that it is efficient.  The database is well indexed and running Aurora DB from AWS.
I have tried using Redis for caching but the possible permutations of filtering, sorting and paginating the data make it seem impractical.  I wasn't able to get good results with this as warming the cache for all variations isn't possible. And because the user preferences for sorting and filtering are stored locally in the browser there isn't a simple default state to warm the cache for either.


text:
Q: Decomposition of a matrix into multiplication of three matrices What is the necessary condition for a real, dense matrix $A_{m\times n}$ to be written as $$B_{m×c}C_{c×k}D_{k×n}$$ where $c,k\ll m,n$?

A: I'd think of this in terms of linear maps - we have a linear map $A : \mathbb{R}^n \to \mathbb{R}^m$ and want to know when it factors as
$$ \mathbb{R}^n \to \mathbb R ^k \to \mathbb R^c \to \mathbb R^m.$$
A linear map cannot increase dimension, so a necessary condition for this factorization is that $\operatorname{rank} A \le \min(c,k)$; otherwise one of the inner maps would lose too much dimension. In fact, this is necessary and sufficient - this is essentially the Rank factorization.


text:
Q: How to break page in crystal report after name change? I created one report that displays all the items purchased by Hotels. Now what i want is : If hotel name is change then page must be break and if hotel name is same then in same page. and also want grand total for particular hotel.
can anyone help me for this ?

A: In Report -> Group Expert you need to have a group set up based on Hotel Name.
Then in Section Expert select the Hotel Name group and click on the Paging tab on the right hand side and tick "New Page After"


text:
Q: Firefox unmaximizes when I exit fullscreen mode When firefox is maximized if i enter fullscreen mode (e.g. with F11, or open video in fullscreen) and then exit it, firefox becomes unmaximized with a little gap between window borders and screen borders. I searched for it, but found nothing. I use ubuntu 18.04 on xfce, and didn't experience that kind of problem on Gnome or KDE. I don't even know if it's a WM issue, or something wrong with firefox. Maybe somebody knows how to fix it?

A: Its a bug in current (64) version related to CSD support. This will be fixed once you upgrade to 65 or 66 (depends on release schedule).

A: I have the same problem in Centos 7.6. A workaround is to unmaximze the window before you press F11. Then you manually make the window as big as it would be when you maximize it. Next you press F11. And when press F11 again it returns to the size it had before the fullscreen.


text:
Q: Collectionview and diffable section with multiple cells I'm trying to create a custom layout with UICollectionViewLayout and UICollectionViewDiffableDataSource.
I want 1 section with cells and both cells need to scroll horizontally simultaneously.
But right now I can only get the top cell to show, see the picture below.
Here's what I've tried so far:

Create Layout

func createLayout() -> UICollectionViewLayout {

    let sectionProvider = { (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in

        guard let sectionKind = Section(rawValue: sectionIndex) else { return nil }
        let section: NSCollectionLayoutSection

        // orthogonal scrolling section of images
        if sectionKind == .image {
            let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(self.view.frame.width), heightDimension: .fractionalHeight(0.5))
            let item = NSCollectionLayoutItem(layoutSize: itemSize)
            item.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)

            let groupSize = NSCollectionLayoutSize(widthDimension: .absolute(self.view.frame.width), heightDimension: .absolute(self.view.frame.height))

            let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])

            section = NSCollectionLayoutSection(group: group)
            section.orthogonalScrollingBehavior = .paging
            section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 10, trailing: 0)
            // info
        } else if sectionKind == .info {
            section = NSCollectionLayoutSection.list(using: .init(appearance: .sidebar), layoutEnvironment: layoutEnvironment)
            section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)
        } else {
            fatalError("Unknown section!")
        }

        return section
    }
    return  UICollectionViewCompositionalLayout(sectionProvider: sectionProvider)
}

Configure Datasource

func configureDataSource() {
    // data source

    dataSource = UICollectionViewDiffableDataSource<Section, Art>(collectionView: collectionView) {
        (collectionView, indexPath, item) -> UICollectionViewCell? in
        guard let section = Section(rawValue: indexPath.section) else { fatalError("Unknown section") }
        switch section {
        case .image:
            return collectionView.dequeueConfiguredReusableCell(using: self.configuredGridCell(), for: indexPath, item: item)
        case .info:
            return collectionView.dequeueConfiguredReusableCell(using: self.configuredListCell(), for: indexPath, item: item)
        }
    }
}

applyInitialSnapshots

func applyInitialSnapshots() {
    // set the order for our sections

    let sections = Section.allCases
    var snapshot = NSDiffableDataSourceSnapshot<Section, Art>()
    snapshot.appendSections(sections)
    dataSource.apply(snapshot, animatingDifferences: false)

    // recents (orthogonal scroller)

    var imageSnapshot = NSDiffableDataSourceSectionSnapshot<Art>()
    imageSnapshot.append(self.arts)

    dataSource.apply(imageSnapshot, to: .image, animatingDifferences: false)

    var allSnapshot = NSDiffableDataSourceSectionSnapshot<Art>()
    allSnapshot.append(self.arts)
    dataSource.apply(allSnapshot, to: .info, animatingDifferences: false)
}

A: For achieving horizontal scroll you can set property for your section as
section.orthogonalScrollingBehavior = .continuous

The easiest way to achieve behaviour like you expect you can combine different group size
    let item1 = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
                                                                          heightDimension: .fractionalHeight(1)))
    let item2 = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
                                                                          heightDimension: .fractionalHeight(0.2)))

    item1.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10)
    item2.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10)

    let group1 = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
                                                                                heightDimension: .fractionalHeight(0.5)),
                                                    subitems: [item1])

    let group2 = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
                                                                                heightDimension: .fractionalHeight(0.5)),
                                                  subitems: [item2])
    let group3 = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
                                                                                heightDimension: .fractionalHeight(1)),
                                                  subitems: [group1, group2])

    let section = NSCollectionLayoutSection(group: group3)
    section.orthogonalScrollingBehavior = .continuous
    return UICollectionViewCompositionalLayout(section: section)


text: Q: xll sdk: When we get xltypeRef instead of xltypeSref. Trying to get xltypeRef as it provides sheet id Trying to get xltypeRef as it returns sheet id. When I call the udf function from VBA it returns xltypeRef and I get the sheet Id but deploying involves registry entries which I want to avoid. I get xltypeSref when I call the same udf function from Excel which does not give sheet id.  Is there any way to get xltypeRef instead of xltypeSref when I call udf directly from Excel?


text:
Q: Sencha field set form panel is working in safari not in iOS simulator Below code is working in Safari without any issues but same piece of code is not working in iOS. Does fieldset have any issues with iOS ?
Environment:
Sencha Touch V2.0
iOS v5.0 simulator
Ext.application({
    name: 'Sencha',
    launch: function() {
    var formPanel = Ext.create('Ext.form.Panel', {
    fullscreen: true,

    items: [{
        xtype: 'fieldset',
        items: [
            {
                xtype: 'textfield',
                name : 'name',
                label: 'Name'
            },
            {
                xtype: 'emailfield',
                name : 'email',
                label: 'Email'
            },
            {
                xtype: 'passwordfield',
                name : 'password',
                label: 'Password'
            }
        ]
    }]
});

    }

});

Could you any help us why above code is not working in iOS.

A: I had a similar Problem. I set the requirements in the app.js to this
requires:
[
    'Ext.form.FieldSet',
    'Ext.field.Password'
]

worked for me, but i´m not sure it is the same kind of problem.

A: What do you see when opened at an iOS device?
I don't see any errors in your code. A fieldset in Sencha Touch normally works just fine in iOS.


text:
Q: how to make border around text plus add number between line How can I achieve something like the image below by using CSS, Bootstrap, or other client-side options?

A: check fieldset and legend tags,
W3C: https://www.w3schools.com/tags/tag_legend.asp

A: You can try this:

body {
  padding: 10px;
}
fieldset {
  position: relative;
  padding-left: 50px;
}

legend {
  position: absolute;
  display: block;
  top: 50%;
  left: -15px;
  top: 30%;
  background: #fff;
}
<fieldset>
  <legend>Title</legend>
  <input type="radio" id="radio"> Click me

    Text Input:
    <input type="text" name="name" id="name" value="" tabindex="1" />

</fieldset>

A: Try this it will help you, i made it with custom css tricks, you can adjust font size according to your need.

.outterCon{
  max-width: 700px;
  margin: auto;
}
.box{
  position: relative;
  border: solid 2px #000;
  width: 200px;
  padding: 10px;
  padding-left: 20px;
}
.legendCon{
  font-size: 20px;
    font-weight: 700;
    position: absolute;
    width: 30px;
    text-align: center;
    left: -15px;
    top: calc(50% - 15px);
    background: #fff;
}

01

QualityThis is test text This is test text This is test text


text:
Q: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data - NodeJS vueJS Estou usando uma aplicação com vuejs e node, e preciso pegar informações através de um .json, mas ao fazer a requisição obtenho o seguinte erro:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
O meu Json está correto, segue o código:
getCars(){

        fetch('../data/carros.json')
        .then(resp => resp.json())
        .then(data => console.log(data));
        }
    },

    mounted(){
       this.getCars();
}


text:
Q: Use secondary IP as outgoing IP on SOCKS5 traffic that uses this IP I have a server that runs OpenVPN on it's primary IP.
There is also a second IP I connect to using SSH as a SOCKS5 setup like this:

ssh -C2qTnN -D 1337 me@<secondary-ip>

I go to whatismyip.com from each connection and I want to see the primary IP when I connect through the VPN and the secondary when I connect through the SOCKS5 proxy (assuming my browser is using the proxy obviously) but now always the primary IP shows.
What trickery do I need to do to fix this?
Edit: this is on a vps and the different IP addresses are on interfaces venet0:0 and venet0:1