text:
Q: how to insert textView in an imageView to be able to save it in device well I explain the image comes from another activity and I show it here with the textview on top, but when I save the image it is not saved with the text that I place on top of it, I have not found the way to do it, if you can help me thanks.
Seen around there that you have to draw on top of the image but I don't know how, I don't know if there will be another way.
activity xml
 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="375dp"
        android:layout_height="377dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="30dp"
        android:layout_marginEnd="16dp"
        />

    <TextView
        android:id="@+id/txtPrecio"
        android:layout_width="172dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="150dp"
        android:text="TextView"
        android:textColor="@color/black"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/txtDescripcion"
        android:layout_width="173dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="100dp"
        android:text="TextView"
        android:textColor="@color/black"
        android:textSize="20dp" />
</RelativeLayout>

<Button
    android:id="@+id/btnGuardar"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginBottom="43dp"
    android:text="@string/guardar"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent" />

Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);

    Button btnGuardar = (Button) this.findViewById(R.id.btnGuardar);

    Bundle extras = getIntent().getExtras();
    String[] message = extras.getStringArray("message");

    TextView precio = findViewById(R.id.txtPrecio);
    TextView descripcion = findViewById(R.id.txtDescripcion);

    for(int i=0;i<message.length;i++) {
        precio.setText(message[0]);
        descripcion.setText(message[1]);
    }

    Intent intent = getIntent();
    bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");

    ImageView imageView2 = this.findViewById(R.id.imageView2);
    imageView2.setImageBitmap(bitmap);

    btnGuardar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkPermissionStorage();
        }
    });

}

private void checkPermissionStorage() {
    if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.P){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                guardarFoto();
            }else{
                ActivityCompat.requestPermissions(
                        this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_PERMISSION_WRITE_STORAGE
                );
            }
        }else {
            guardarFoto();
        }
    }else{
        guardarFoto();
    }
}

public void guardarFoto() {
    OutputStream fos = null;
    File file = null;

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
        ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues();

        String fileName = System.currentTimeMillis() + "image_example";

        values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/MyApp");
        values.put(MediaStore.Images.Media.IS_PENDING, 1);

        Uri collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
        Uri imageUri = resolver.insert(collection, values);

        try {
            fos = resolver.openOutputStream(imageUri);
        } catch (FileNotFoundException e){
            e.printStackTrace();
        }

        values.clear();
        values.put(MediaStore.Images.Media.IS_PENDING, 0);
        resolver.update(imageUri, values, null, null);

    }else{
        String imageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
        String filename = System.currentTimeMillis() + ".jpg";
        file = new File(imageDir, filename);

        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e){
            e.printStackTrace();
        }
    }

    boolean saved = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    if(saved){
        Toast.makeText(this, "Imagen guardada", Toast.LENGTH_SHORT).show();
    }

    if(fos!=null){
        try {
            fos.flush();
            fos.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    if(file!=null){
        MediaScannerConnection.scanFile(this, new String[]{
                file.toString()
        }, null, null);
    }

}


text:
Q: Change Tab text size In MainActivity, I have implemented ActionBar with TabListener and Viewpager.
I need to change the selected Tab's text size to a bit bigger size.
This is how onCreate() method looks like, with these implementations.
    actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    viewPager = (ViewPager) findViewById(R.id.pager);
    vpAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    viewPager.setAdapter(vpAdapter);

    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
    });

    ActionBar.TabListener tabListener = new ActionBar.TabListener() {
        @Override
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            viewPager.setCurrentItem(tab.getPosition());

        }

        @Override
        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
        }
    };

    Tab tab = actionBar.newTab()
            .setText(getString(R.string.basic_setup))
            .setTabListener(tabListener);
    actionBar.addTab(tab);

    tab = actionBar.newTab()
            .setText(getString(R.string.location))
            .setTabListener(tabListener);
    actionBar.addTab(tab);

    tab = actionBar.newTab()
            .setText(getString(R.string.advanced_setup))
            .setTabListener(tabListener);
    actionBar.addTab(tab);

My idea is that I should be able to modify this in ActionBar.TabListener's onTabSelected() method, but I don't know how could I do it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Constructing a unit vector in the direction of largest component I am dealing with $\ell_\infty$ norms, and I need a "mathematical" way to take a vector of $p$ length (We'll call it $x$), and construct a vector pointing in the direction of $\|x\|_\infty$.
I know in English, I can say "And I then construct $\hat x$ such that $\hat x$ is pointing in the direction of the the maximum component of $x$"...... but I'd like a mathematical way to present that.
Thank you all!
EDIT: To be more clear, what I want to happen is all elements of the vector that are NOT equal to the $\ell_\infty$ norm be set to zero.


text:
Q: Error: "python setup.py egg_info" failed with error code 1" for installing osmnx I'm trying to install a really important python package osmnx for python 3.7. Below is what I got. I searched on this for the afternoon and tried updating the setuptools but it didn't work.

Microsoft Windows [Version 10.0.17134.590] (c) 2018 Microsoft
  Corporation. All rights reserved.
C:\Users\jelly>pip install osmnx Collecting osmnx   Using cached
  https://files.pythonhosted.org/packages/94/1f/88209842ca41ef8b6a547838bb5872ca03b505a1493927fd17a98cd8e38d/osmnx-0.9-py2.py3-none-any.whl
  Requirement already satisfied: matplotlib>=2.2 in
c:\users\jelly\appdata\roaming\python\python37\site-packages (from
  osmnx) (3.0.3) Collecting Rtree>=0.8.3 (from osmnx)   Using cached
  https://files.pythonhosted.org/packages/33/0d/0bcb0fdd759570e85697189f675fa462131e5636482f2832288bbe4bb6f7/Rtree-0.8.3-py3-none-any.whl
  Requirement already satisfied: pandas>=0.23 in d:\program files
  (x86)\python37-32\lib\site-packages (from osmnx) (0.24.1) Requirement
  already satisfied: networkx>=2.2 in d:\program files
  (x86)\python37-32\lib\site-packages (from osmnx) (2.2) Collecting
  geopandas>=0.4 (from osmnx)   Using cached
  https://files.pythonhosted.org/packages/f0/5d/916b7268ef551fa9647ce12220e9a68006374f1ce5b0ddaf1cd0df2880b7/geopandas-0.4.1-py2.py3-none-any.whl
  Requirement already satisfied: requests>=2.21 in d:\program files
  (x86)\python37-32\lib\site-packages (from osmnx) (2.21.0) Collecting
  Shapely>=1.6 (from osmnx)   Using cached
  https://files.pythonhosted.org/packages/a2/fb/7a7af9ef7a35d16fa23b127abee272cfc483ca89029b73e92e93cdf36e6b/Shapely-1.6.4.post2.tar.gz
      Complete output from command python setup.py egg_info:
      Traceback (most recent call last):
        File "", line 1, in
        File "C:\Users\jelly\AppData\Local\Temp\pip-install-2g0vnj5r\Shapely\setup.py",
  line 80, in
          from shapely._buildcfg import geos_version_string, geos_version, \
        File "C:\Users\jelly\AppData\Local\Temp\pip-install-2g0vnj5r\Shapely\shapely_buildcfg.py",
  line 200, in
          lgeos = CDLL("geos_c.dll")
        File "d:\program files (x86)\python37-32\lib\ctypes__init__.py", line 356, in init
          self._handle = _dlopen(self._name, mode)
      OSError: [WinError 126] The specified module could not be found
----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in
  C:\Users\jelly\AppData\Local\Temp\pip-install-2g0vnj5r\Shapely\

A: The OSMnx documentation recommends installing with conda. If you prefer to use pip, you need to make sure you install all the C extension dependencies on your system first (which is really difficult and time consuming on windows; for example the error you're getting says you haven't installed the geos dependency). I recommend using conda to install it like:
conda config --prepend channels conda-forge
conda create -n ox --strict-channel-priority osmnx

A: Please see the final solution here for any other osmnx users. A million thanks to Professor Boeing.
https://github.com/conda-forge/osmnx-feedstock/issues/42


text:
Q: Regex can't getting the blank spaces and I can't split the string correctly? I'm creating a Regex in Python where I need to find a blank spaces in a string
Example
000#0123456789#ASimpleName#123456 000#987654321#OtherSimpleName#8765432
000#0123456789#ASimpleName#EUA 000#987654321#OtherSimpleName#8765432

In this case, if I use re.split('\s') I solve my problem, but I can find this
000#0123456789#A simple Name#123456 000#987654321#Other Simple Name#8765432
000#0123456789#ASimpleName#EUA 000#987654321#OtherSimpleName#8765432

I've tried to use this expression [\d|\w]\s\d, but the Regex get 6 0 and A 0, but I need only the blank space.

A: You may use the following regex with re.split:
\s+(?=000#)

Or, if there may be any 3 digits:
\s+(?=\d{3}#)

See the regex demo and the https://jex.im/regulex diagrams:

Details

*

*\s+ - matches and consumes 1 or more whitespace chars

*(?=\d{3}#) - makes sure that, immediately to the right of the current location, there are 3 digits followed with #. (?=000#) returns true only if the three digits are zeros. # may not be necessary here, but that depends on the actual data and requirements.


text:
Q: Can XML properties of a BIRT report be gathered under a specific name? I am trying to create BIRT Reports by writing XML code instead of drag and drop design method, using BIRT 4.4.2.
I would like to know if I can call the border properties with a name instead of writing the same XML property code for an element of report sharing exact same properties with the other one.
I have tried to call them with an ID value but could not make it work.
<property name="fontFamily">"Arial"</property>
<property name="fontWeight">bold</property>
<property name="color">#0000FF</property>
<property name="borderBottomStyle">none</property>
<property name="borderLeftStyle">none</property>
<property name="borderRightStyle">none</property>
<property name="borderTopStyle">none</property>
<property name="textAlign">center</property>
<property name="dataSet">Data Set</property>

For instance, I have lots of cells with no border styles so I want to use this XML many times but instead I want to call all the 8 lines with a single name like:
<property name="noBorderProperties"></property>

Thank you for your answers.

A: The best way to achieve this (in the BIRT designer as well) is to use styles.
E.g. create a style named "BlueBoldCenteredNoborder" and apply it to the cells.
Of course this doesn't work with the dataSet property, but this cannot be set for cells inside a grid/table anyway.


text:
Q: What's the difference between DOCUMENT_URI and URI_REQUEST in SSI? When looking at a SSI printenv dump I see a variable URI_REQUEST.
When reading the Apache mod_include docs I see DOCUMENT_URI which they define as "The (%-decoded) URL path of the document requested by the user."
Anyone know the difference between the two?
TIA.

A: REQUEST_URI includes the Query String (?q=testing...) where DOCUMENT_URI does not.

A: ok. seems like it is exactly the opposite according to Apache docs and RFC 2616.
REQUEST_URI does not contain the query string.
DOCUMENT_URI does contain the query string.
cheers,
Rob


text:
Q: Yii2 не возвращает extraFields Имеется класс User с определенными полями. Он наследует ActiveRecord
public function fields() {
    return [
        'id',
        'name' => 'full_name'
    ];
}

public function extraFields() {
    return [
        'email',
        'role' => function($model) {
            $auth = Yii::$app->authManager;
            return array_values($auth->getRolesByUser($model->id))[0]->name;
        },
        'city' => function($model) {
            return City::findCityById($model->city);
        }
    ];
}

Если я попробую получить данные из него с extraFields, например,
http://localhost:8080/api/users?expand=email

переопределив метод index в ActiveController,
public function actionIndex() {
    return User::find()->where(['id' => Yii::$app->user->id])->orWhere(['parent' => Yii::$app->user->id])->all();
}

то extraFields мне не вернуться, но будет возращено, то что написано в fields.
А вот если я верну
public function actionIndex() {
    return new ActiveDataProvider([
       'query' => User::find()->where(['id' => Yii::$app->user->id])->orWhere(['parent' => Yii::$app->user->id])
    ]);
}

extraFields будут возвращены, но так же будут переданы дополнительные заголовки, которое мне не нужны в данном случае.
Как я понимаю это происходит, потому что all Возвращает не массив пользователей, а массив ActiveRecord. Хотя, если не переопределять метод, то extraFields будут возвращаться, но мне это не подходит, так как запрос должен возвращать только данные о детях пользователя, который сделал запрос, и о нем самом.
Может я не правильно переопределяю метод Index? Или может надо сделать правило(rbac), которое должно ограничивать отображаемых пользователей.


text:
Q: Using RESTful web service to hide GET parameters I had posted a question sometime ago, regarding hiding GET parameters, but never got any replies.
Redirect a user to instagram login using POST
With respect to same issue, I thought I can solve it using RESTful web service to hide my GET parameters.
I am able to make RESTful GET requests to instagram but the issue is, that, instagram after receiving the GET request, it is suppose to redirect back to my web-application to a specified URL.
How do I achieve this using RESTful web services? Because I do get a response including the HTTP status codes but how do I achieve the redirect which is suppose to happen from Instagram.
Thanks
Environment : Java 1.6, JSF-2, Jersey


text:
Q: CSS: Progress bar, second background is appearing below bar instead of overlapping I'm trying to create a Progress Bar. If user has completed 20%, a bar with my set colour is being created with the correct width. But for some reason, its appearing below my progress bar instead of overlapping and I have no idea why.
Bonus question: Any ideas why text is not aligned to center?

CSS:
.progress-bar {
    height: 20px;
    width: 126px;
    background: #BABABA;
    position: relative;
}

.progress-bar span {
    font-size: 1.1rem;
    font-weight: 600;
    line-height: 15px;
    text-align: center;
    position: relative;
}

.progress-bar div.bar {
    height: 20px;
    background: #336291;
    position: absolute;
}

EJS:

                            <%= gamedata[i].progressPercentage %>
                            <div class="bar" style="width:<%= gamedata[i].progressPercentage %>;">

A: You should put the correct coordinates, so append the following lines:
.progress-bar div.bar {
    /* your code here */

    top: 0;
    left: 0;
}

Bonus answer: your text is aligned in the center but your DOM element is not. What I suggest doing is giving automatic lateral margin and treating it as a block, like so:
.progress-bar span {
    font-size: 1.1rem;
    font-weight: 600;
    line-height: 15px;
    display: block;
    margin: auto;
    position: relative;
}

A: try this code nothing big changes. Some small changes in css and HTML.
.progress-bar {
        height: 20px;
        width: 126px;
        background: #BABABA;
        position: relative;
    }

    .progress-bar span {
        font-size: 1.1rem;
        font-weight: 600;
        line-height: 15px;
        text-align: center;
        position: relative;
    }

    .progress-bar div.bar {
        height: 20px;
        background: #336291;
        position: absolute;
    }

Hear is html code:

      <div class="bar" style="width:<%= gamedata[i].progressPercentage %>;">
          <%= gamedata[i].progressPercentage %>


text:
Q: Is there a way to determine locks that a given query might apply on SQL objects? Consider a simple query, as simple as a select statement:
select * from Teachers where Name like N'%John%'

As soon as I start this query, it finishes. Thus, I get no chance to see sp_who2 to find out what type of lock this query has applied on database objects.
I can inflate this query with transaction statements:
begin transaction

select * from Teachers where Name like N'%John%'

-- Here, I won't commit transaction, thus holding the lock

But frankly, that doesn't seem the proper way for natural locking detection, because I've manipulated the default behavior using transaction statements.
Do we have a tool, like Display Estimated Execution Plan to show us some information about locking of a given query? If not, how can we find out what type of lock a given query can apply on a database, because they get executed TOO fast to be detected.

A: Unfortunately you cannot determine the lock beforehand that a query may apply.
You can check Different techniques to identify blocking in SQL Server

In order to resolve a blocked process, we first need to determine
  which process is the blocking process and then if possible kill the
  blocking process. There are many different ways in SQL Server to
  identify a blocks and blocking process that are listed as follow:

*

*Activity Monitor

*SQLServer:Locks Performance Object

*DMVs

*

*sys.dm_exec_requests

*sys.dm_tran_locks

*sys.dm_os_waiting_tasks

*SQL Server Profiler Locks Event Category


text:
Q: What is the difference in meaning between two sentences?
*

*If properly maintained, cars remain operational for several years.

*If properly maintained, cars will remain operational for several years
What difference to the meaning of the sentence does using will make?

A: tl;dr - very little difference, if any; it's more a matter of style.

will modal verb
  1 Expressing the future tense.
  'you will regret it when you are older'
  2 Expressing inevitable events.
  'accidents will happen'
  - ODO

There are two ways it could be argued that the addition of will changes the sense of the original sentence:

*

*the assertion only applies to future maintenance (cf definition 1); or

*it makes the assertion stronger (cf definition 2).

In practice, though, the simple present "remain" can already be considered forward-looking. One could argue that the original can be considered to be a statement expressing a timeless truth, so it can be applied to past maintenance. However, to the extent that holds, the second version (with will) can also be considered a 'timeless' statement, also applicable to past maintenance.
There is some justification for asserting that will emphasises the assertion. However, the if-then structure already qualifies the assertion, making the will-emphasis somewhat redundant.
The addition of the word will is mostly stylistic, adding very little to the meaning of the sentence.


text:
Q: is there any easy var to handle button state in react? i need hand of help.
I have input type range (value slider) and icons on my react page.
Slider by moving it changes value of sum variable.(Its Done).
Icons must on click toggle each true/false state and add each value to sum variable if false or remove its value if true.
It is something like basket system.
Question is, how to easy handle this job?
1 each icon on click must highlight
2 each icon on click must check its state if false then add price to total if true remove price from total.

A: Have you tried something like this?
function Form() {
  function handleSubmit(e) {
    e.preventDefault();
    console.log('You clicked submit.');
  }

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}


text:
Q: How to get divider line in function/option table in Wolfram Workbench In the tutorial pages in the documentation to my package, I have a table that contains functions and their definitions.   In the sample tutorial page, I see a divider line separating the header from the rest of the rows in the table, which you can see:

How do I create one for my own tutorial page?  I can't seem to find it in the Documentation Tools palette.


text:
Q: Trouble booting after moving Ubuntu 18.04 across drives Background
I'm on VirtualBox 6.0.12. I had a drive which contained a /boot partition, and an encrypted (LUKS) main partition. I wished to remove the encryption and apparently the best way to do this was to migrate Ubuntu to a new drive.
Prior Actions
I used this answer to move the partition contents. I moved both /boot and the main / partition contents. As far as I can tell, it moved it just fine.
https://askubuntu.com/a/741727/128596
As part of step 5 of the above answer, I used the steps below through used of a live CD (no errors reported).
https://askubuntu.com/a/88432/128596
After doing this it seems to boot the Ubuntu partition okay, but got stuck at the (basic looking) Ubuntu 4 dot loading screen (like this one but with 18.04 text).
When I got stuck there, I looked to other answers and I tried to run boot-repair from the live CD but I just got back to the 4 dot loading screen.
Later Events
If I wait for long enough I get dropped to an initramfs screen, and upon trying to exit it I get this behaviour.
Playing around with enabling/disabling 3D acceleration and changing VirtualBox graphics driver don't seem to work.

Question
What actions, if any, can I take to fix this?


text:
Q: How to run Android app or install on PlayStore if unavailable for API30? I have a android app where I want to run other apps. If these apps are not installed already, I would like to open PlayStore to let the user install them:
var info : ApplicationInfo? = null
try {
    info = pm.getApplicationInfo(packageName, 0) as ApplicationInfo
} catch (e: PackageManager.NameNotFoundException){
    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = Uri.parse("market://details?id=$packageName")
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    context.startActivity(intent)
}

if (info != null) {
    val intent = pm.getintentForPackage(packageName) as Intent
    context.startActivity(intent)
}

This snippet works so far good for API 26 (Android 8) for instance. But for API 30 (Android 11) the getApplicationInfo() throws a NameNotFoundException always, even when I already installed the app.
Whats wrong here?

A: On Android 11, methods on PackageManager like getApplicationInfo() no longer work by default. You need to either:

*

*Not call them, or

*Add a <queries> element to your manifest, whitelisting the third-party apps that you wish to find, or

*Request the MANAGE_ALL_APPS permission (and run the risk of your app being banned from the Play Store)

In your case, the <queries> element is probably a safe choice, assuming that your list of application IDs that you are looking for is knowable at compile time.


text:
Q: How to use Xamarin Profiler standalone for profile the app I am working on xamarin forms in visual studio community 2017. How to profile the xamarin forms app using xamarin profiler.
Any help would be appreciated.

A: From the documentation:

You will need to be a Visual Studio Enterprise subscriber to unlock
  this feature in either Visual Studio Enterprise on Windows or Visual
  Studio for Mac on a Mac.

So sadly you can't use the great features of Xamarin Profiler using Visual Studio Community, you need Enterprise. You can also get a trial for 30/90 days if I remember, so consider it.
If you want to profile iOS version of your app, I think you should be able to use Instruments tool from XCode, please follow this instructions: Profiling Xamarin.iOS Applications with Instruments. To open it, go for Tools → Instruments in Visual Studio for Mac.
If you want to profile Android app, check out Profiling Android Apps, it describes how to do it from Android Studio.


text:
Q: Set xWorkb = New workbook not working, ActiveX error I have some code below, It works like a charm but I'm curious about some things.

*

*Why can't I make a Set xWorkb = new Workbook statement? Instead I use the Dim xWorkb as new Workbook, which works. But I've learned (hopefully correct) that using the new statement within a Dim is bad practice, and that you should create the object seperately. So why doesn't it work? I get a ActiveX component can't create object error, but the xWorkb is still being created later as an object right due to the new statement in the Dim section? Makes me confusing.

*Why can't I use the excel.application.workbooks when defining variable xApp? Is it because I have to specify a workbook and can't just leave the workbooks empty like that? I get a type mismatch error when I'm trying to change excel.application to excel.application.workbooks.
Sub tester()

    Dim xWorkb As New Workbook
    Dim xApp As Excel.Application: Set xApp = New Excel.Application
    Dim xFiles_target() As Variant
    Dim file_path As String

    xFiles_target = Array("Bella.xls", "Fizz.xls", "Milo.xls", "Jake.xls")
    file_path = Dir("C:\Users\hans\Desktop\")

    Do While Len(file_path) > 0
        Debug.Print file_path
        If UBound(Filter(xFiles_target, file_path)) >= 0 Then
        Debug.Print "found " & file_path
        Set xWorkb = xApp.Workbooks.Open("C:\Users\hans\Desktop\" & file_path)
        xApp.ActiveSheet.Cells(2, 2) = "tester"
        xWorkb.Save
        xWorkb.Close
        End If
        file_path = Dir

    Loop

End Sub

A: You cannot create new workbooks with New because workbooks are coupled with Application and must be created with Workbooks.Add or Workbooks.Open.
Dim xWorkb as new Workbook does not work - it appears to work because you don't access xWorkb between declaring it and assigning it with Workbooks.Open. If you did, you would get the same  ActiveX component can't create object error.
The error is because Excel.Workbook does not have any public constructors.
You cannot define a variable as excel.application.workbooks because that is not a type. It is a property named Workbooks, of type Excel.Workbooks, that belongs to an object named Application of type Excel.Application.
You can declare the variable as Excel.Workbooks, but you probably don't want to, because you will need to create an Excel.Application to use it anyway.


text:
Q: Python: Two Equations, One Variable Solve Help. I am relatively new to Python and struggling with the most basic of functions.
I have two equations that I am trying to set equal to one another in order to solve for a single variable. Sounds simple enough. However, I am unable to find a combination of functions to return an answer. Any help would be greatly appreciated for this newbie.
Problem: Solve for x by setting equations E and F equal to one another. E and F represent the expected value of pw1 and qw2 respectively.
import cvxpy as cvx
import numpy as np
import sympy as sym
from sympy import symbols, Eq, solve
import scipy as sc
from scipy import linalg
from scipy.optimize import fsolve

#Define Variable
x = symbols('x')

#Define Wealth Function:
def u(w):
    return ((w/20000)-1)**3

#Define Parameters
p = np.array([0.931, 1/21, 1/56, 1/292, 1/10720, 1/52835, 1/739688, 1/18492204, 1/258890850])
q = np.array([0.969, 1/37, 1/238, 1/7459, 1/648976, 1/5153633, 1/175223510])
c1 = 1
c2 = 2
a1 = np.array([0, 1, 2, 5, 50, 500, 5000, 1000000, 200000000])
a2 = np.array([0, 4, 7, 100, 10000, 1000000, 200000000])

#Define Outcome
w1 = x - c1 + a1
w2 = x - c2 + a2

#Define Expected Value Function
E = Eq(np.dot(p,u(w1)))
F = Eq(np.dot(q,u(w2)))

print(solve((E,F),(x)))

Python only returns "[]".

A: Try removing Eq and replace with E = np.dot(p,u(w1)) and F = np.dot(q,u(w2)). And then solve by print(solve(E-F, x)). I get something like [-3398286.84918693, 1731058.4098883 - 3066517.03142943*I, 1731058.4098883 + 3066517.03142943*I]
import numpy as np
import sympy as sym
from sympy import symbols, Eq, solve
import scipy as sc
from scipy import linalg
from scipy.optimize import fsolve

#Define Variable
x = symbols('x')

#Define Wealth Function:
def u(w):
    return ((w/20000)-1)**3

#Define Parameters
p = np.array([0.931, 1/21, 1/56, 1/292, 1/10720, 1/52835, 1/739688, 1/18492204, 1/258890850])
q = np.array([0.969, 1/37, 1/238, 1/7459, 1/648976, 1/5153633, 1/175223510])
c1 = 1
c2 = 2
a1 = np.array([0, 1, 2, 5, 50, 500, 5000, 1000000, 200000000])
a2 = np.array([0, 4, 7, 100, 10000, 1000000, 200000000])

#Define Outcome
w1 = x - c1 + a1
w2 = x - c2 + a2

#Define Expected Value Function
E = np.dot(p,u(w1))
F = np.dot(q,u(w2))

print(solve(E-F, x))

prints
[-3398286.84918693, 1731058.4098883 - 3066517.03142943*I, 1731058.4098883 + 3066517.03142943*I]


text:
Q: Echo Value From Array Where I'm probably going about this in completely the wrong way but I've got it half working!
I have a table (prices) which contains a 'pack' reference number and a 'price' for each pack.
I'm trying to echo different prices for each pack on the same page but seem to have got a bit lost!
eg. Pack 1 is £12 and pack 2 is £17. I'd like to be able to echo these values in different places on the same page.
Up to now I have...
 <?php
    $con = mysql_connect('*****');
    mysql_select_db('****');
    $query = "SELECT * FROM prices WHERE pack=2";
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result)){
    ?>

Then I have...
<?php echo $row['price'];}?>

further down the page where I want the price to appear.
This is fine if I only need the price for pack 2 on that page but if I want different prices on the same page it wont work.
I realise the WHERE pack=2 in the query is controlling the value echoed but I need to echo the price WHERE pack=1 and pack=2 on the same page.
Is there any way I can remove the WHERE from the query and have some kind of ECHO WHERE where I need the prices to appear on the page.
Hope this all makes sense and someone can point me in the right direction.
Cheers,
Bruce

A: I suggest using PDO, but you can do it like this:
$query = "SELECT * FROM prices WHERE pack=1 OR pack=2 ORDER BY pack ASC";
$result = mysql_query($query);
$prices = array();
while($row = mysql_fetch_array($result)){
    $prices[$row['pack']] = $row['price'];
}

Then, $prices[1] will contain price for pack=1, and $prices[2] will contain price for pack=2;
If you shall need more than packs 1 and 2, use IN clause:
$query = "SELECT * FROM prices WHERE pack IN (1, 2, 5, 7) ORDER BY pack ASC";

A: You should place price any where in page but inside while loop not outside while loop
<?php
    $con = mysql_connect('*****');
    mysql_select_db('****');
    $query = "SELECT * FROM prices WHERE pack=2";
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result))
    { ?>
          // place your HTML
         Price <input type="text" value="<?= $row['price'] ?>" />
   <?php } ?>

A: You should use mysqli_connect() instead of older mysql_connect() as function is deprecated.
Try this way:-
 $link = mysqli_connect("host","username","password","db_name") or die("Error " . mysqli_error($link));

 $query = "SELECT * FROM prices WHERE pack IN ( 1,2 )";
 // If you want all pack prices then use below query
 // $query = "SELECT * FROM prices";

   //execute the query.

 $result = $link->query($query);

   //display information:

 while($row = mysqli_fetch_array($result)) {
    echo $row['pack'] .'='. $row['price'] . "<br>";
 }


text:
Q: Not able to send flags when using RVM wrapper I'm trying to use crontab with my RVM setup (creating a backup using backup gem).
My crontab entry runs the following command several times a day:
/home/user/.rvm/gems/ruby-2.1.1/wrappers/backup -t app

However, for some misterious reason, the -t flag is beeing changed to _t (dash turns to underscore so also --trigger changes to __trigger). In cause of that, i'm not able to use that bin correctly. Error message says:

Could not find command "_t"

Please note that using backup -t app works fine, just using a wrapper fails.
Is there any reason behing such behavior? What can i do to run a wrapper with non-underscored flags? Thanks in advance.


text:
Q: How to force UFW to be enabled after every restart (currently "inactive")? I have enabled the UFW in terminal using "sudo ufw enable" ... But, UFW does not appear to start when the computer starts.
After the computer starts, I check the status of the UFW using "sudo ufw status verbose" ... I expect to see "Status: active" in terminal but, instead, I am seeing "Status: inactive".
How do I force the UFW to run at startup?
Thanks.

A: Edit your /etc/ufw/ufw.conf and make,
ENABLED=yes


text:
Q: clean url and javascript load order problem in php I am trying to build a php webpage.packing.php contains :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <meta name="description" content="Fresh Sliding Thumbnails Gallery with jQuery and PHP" />
        <meta name="keywords" content="jquery, images, gallery, full page, thumbnails, scrolling, sliding, php, xml"/>
        <link rel="stylesheet" href="css/style.css" type="text/css" media="screen"/>

<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />

<script type="text/javascript" src="js/jquery-1.6.1.js"></script>

<link rel="stylesheet" type="text/css" href="css/site.css" />

<script type="text/javascript" src="js/ddsmoothmenu.js">

</script>
        <script type="text/javascript" src="js/jquery.gallery.js"></script>

<script type="text/javascript" >
$(document).ready( function(){

  // Menu

  ddsmoothmenu.init({
    mainmenuid: "smoothmenu1", //menu DIV id
    orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
    classname: 'ddsmoothmenu', //class added to menu's outer DIV
    //customtheme: ["#1c5a80", "#18374a"],
    contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
});
});

</script>

and my .htaccess is
RewriteEngine On
RewriteRule ^packing/Pure packing.php?id=pure
RewriteRule ^packing/ExtraVirgin packing.php?id=EV

Now when I open my php it rendersproperly say I open packing.php
But when I open using the clean URL it gives an error in firebug stating $ is not defined.
Now I know the problem is due to the wrong loading order of javascripts.
Why does it happen And how can I solve it ?
Thank you.

A: When you use your clean URLs, the browser thinks it's in a different directory (/packing/pure). The relative URLs that point to your JS files will no longer work.
Use absolute URLs instead:
 <script type="text/javascript" src="/js/jquery.gallery.js">

A: There could be an issue with the paths? You're not giving path's, but you're changing paths from the root (packing.php) to a 2nd level (packing/Pure). It is probably looking for your .js files in the wrong path, like packing/js/ instead of just /js.
Try using absolute paths for your loading:
<script type="text/javascript" src="/js/jquery-1.6.1.js"></script>

(notice the slash!)
or even
<script type="text/javascript" src="http://yoursite.com/js/jquery-1.6.1.js"></script>


text:
Q: Why WCF nettcpBinding is slow on local machine I am trying to check the WCF latency on my local machine. And it takes 2-4 millisecond/request (which seems to slow). I am not sending or receiving any complex object (so no serialization/deserialization involved).
Here is the service part:
    public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

Here is the server's config.
  <system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<bindings>
  <netTcpBinding>
    <binding name="defaultNetTcpBinding" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="00:10:00" openTimeout="00:10:00" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647" maxBufferSize="2147483647">
      <readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" />
      <security mode="None"></security>
    </binding>
  </netTcpBinding>
    </bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  <services>
    <service name="WcfTestApplication.Service1">
      <endpoint address="net.tcp://localhost/WcfTestApplication/Service1.svc" contract="WcfTestApplication.IService1" binding="netTcpBinding" />
      <endpoint address="mex" contract="IMetadataExchange" binding="mexTcpBinding"/>
    </service>
  </services>

And here is the client code
            NetTcpBinding binding = new NetTcpBinding();
        binding.Security.Mode = SecurityMode.None;
        EndpointAddress address = new EndpointAddress("net.tcp://localhost/WcfTestApplication/Service1.svc");
        ChannelFactory<IService1> channelFactory = new ChannelFactory<IService1>(binding, address);
        IService1 _clientProxy = channelFactory.CreateChannel();

        Stopwatch watch = new Stopwatch();
        watch.Start();
        for (int i = 0; i < 1000; i++)
        {

            IService1 _clientProxy1 = channelFactory.CreateChannel();
            var data = _clientProxy1.GetData(4);
            ((IClientChannel)_clientProxy1).Close();
        }
        watch.Stop();
        Console.WriteLine(watch.ElapsedMilliseconds.ToString());
        Console.ReadLine();

Updated:
Strange enough, there is no difference when I change binding to Named pipe. It still takes 2-4 millisecond/request.


text:
Q: How to replace empty space with character PHP I have this strange issue with my string $content 1stText 2ndText 3rdText 4thText, 5thText, 6thText, that I cannot replace empty space with character. The main purpose is that I have to put my string in array, each element will have it's own name afterwards. However, as I am parsing data from another website, get stuck on this:
if ($child->nodeName == "div"){
    $textContentArray = preg_split('/\n/', $child->textContent);
    $counter = 0;
    $counter2 = 0;
    foreach ($textContentArray as &$value)
    {
        if (trim($value) != "")
        {
            $counter2++;
            $string = preg_replace('/\s+/', ';', $content);
            $test = explode(';', $string);
            var_dump($string);

echo $string gives me
1stText2ndText3Text4Text;5Text;6Text
while var_dump: string(2) "1stText" string(18) "2ndText" string(3) "3Text" string(16) "4Text"
4Text(4thText, 5thText, 6thText) consists of three words, so between them, character ";" is added, but between text nodes - not.
I have tried many variations that I found here, simple str_replace doesn't work here somehow. As I am copying string from the table, maybe that would be the issue? But still, why I cannot save it in array separately?

A: Try this way to remove extra spaces from string with single space. then try to replace that single space with ; character, finally explode as you wish to get that final array.
$str = preg_replace( "/\s+/", " ", $content );

#replaced multiple space with single space
$str = "1stText 2ndText 3rdText 4thText, 5thText, 6thText,";
$re = "/\\s+/m";
$subst = ";";
$result = preg_replace($re, $subst, $str);
$final=explode(';',$result);

echo '<pre>';
print_r($final) ;
echo '</pre>';

EDIT: print_r(array_map('trim',explode(";",$result)));


text:
Q: Is my notebook battery charging even when the indicator has stopped flashing? I just bought a new battery for my Fujitsu-Siemens PA-1510. The battery label claimed that, in order to have a long living battery it is important to charge it at least 10 hours before the first use.
So I put it in my Notebook and connected the power. After 1 hour, the charging indicator stopped flashing, trying to convince me that the battery is fully charged. But I wanna charge it 10 hours. Is the battery still charging, even so the indicator switched from "red blinking" to "green constant". Do I have a chance at all to charge it 10 hours?

A: Assuming it's a lithium-ion battery pack, charging for a specified length of time (such as 10 hours) permits calibrating the battery gauge so it knows where the charge tops out. If you stop charging early, the battery may be only partially charged, but the battery gauge (software or firmware) will think that is the point where the charging has topped out; thus it will be miscalibrated and will erroneously show the battery as fully charged. So follow the manufacturer's advice for the first charge, as well as for recharges for the same length of time to recalibrate from time to time as the battery ages.
There are some old myths floating around about battery "memory" and how overcharging a battery is bad for it. That only applies to nickel-cadmium (NiCd) batteries, though, which almost no one uses anymore. For lithium batteries, the opposite is true: it's bad to let them drain all the way to an empty charge. The usual recommendation when storing a Li-ion battery unused for months at a time is actually to leave it half-charged.


text:
Q: Cumulative array sum in Ruby What is the slickest, most Ruby-like way of calculating the cumulative sum of an array?
Example:
[1,2,3,4].cumulative_sum

should return
[1,3,6,10]

A:  irb> a = (1..10).to_a
 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 irb> a.inject([0]) { |(p,*ps),v| [v+p,p,*ps] }.reverse[1..-1]
 #=> [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

We could also take a note from Haskell and make a ruby version of scanr.
irb> class Array
   >   def scanr(init)
   >     self.inject([init]) { |ps,v| ps.unshift(yield(ps.first,v)) }.reverse
   >   end
   > end
#=> nil
irb> a.scanr(0) { |p,v| p + v }
=> [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
irb> a.scanr(0) { |p,v| p + v }[1..-1]
=> [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
irb> a.scanr(1) { |p,v| p * v }
=> [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

A: class Array
  def cumulative_sum
    sum = 0
    self.map{|x| sum += x}
  end
end

A: Also you can read about scanl — feature you need, but that isn't yet implement in Ruby, as far as I know. Here are examples and sample source code of it: http://billsix.blogspot.com/2008/11/functional-collection-patterns-in-ruby.html
UPD:
The above link is dead, so instead I'll say that my Ruby implementation of Wolfram Mathematica's FoldList[] as a part of gem "mll" here can  be simplified for OP's purpose while being Enumerable:
def fold_list array
  start = 0
  Enumerator.new do |e|
    array.each do |i|
      e << start += i
    end
  end
end

irb> fold_list([1,2,3]).to_a
=> [1, 3, 6]

A: Here is one way
a = [1, 2, 3, 4]
a.inject([]) { |x, y| x + [(x.last || 0) + y] }

If it is OK that the answer is more than one statement, then this would be cleaner:
outp = a.inject([0]) { |x, y| x + [x.last + y] }
outp.shift # To remove the first 0

A: One more approach ( though I prefer khell's)
(1..10).inject([]) { |cs, i| cs << i + (cs.last || 0) }

I saw the answer posted by hrnt after posting my answer. Though two approaches look the same, solution above is more efficient as the same array is used in each inject cycle.
a,r = [1, 2, 3, 4],[]
k = a.inject(r) { |x, y| x + [(x.last || 0) + y] }
p r.object_id
#  35742260
p k.object_id
#  35730450

You will notice r and k are different. If you do the same test for the solution above:
a,r = [1, 2, 3, 4],[]
k = a.inject(r) { |cs, i| cs << i + (cs.last || 0) }
p r.object_id
# 35717730
p k.object_id
# 35717730

The object id for r and k are the same.

A: unearthing this for one more approach, that modifies the array in-place
class Array
  def cumulative_sum!
    (1..size-1).each {|i| self[i] += self[i-1] }
    self
  end
end

can also be generalized :
  def cumulate!( &block )
    (1..size-1).each {|i| self[i] = yield self[i-1], self[i] }
    self
  end

  >> (1..10).to_a.cumulate! {|previous, next| previous * next }
  => [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

A: Try this code
[1,2,3,4].inject([]){ |acc, value| acc << acc.last.to_i + value.to_i }

=> [1, 3, 6, 10]

A: The Haskell function we want is scanl, not scanr.
class Array
  def scanl(init)
    self.reduce([init]) { |a, e| a.push(yield(a.last, e)) }
  end
end

[1,2,3,4].scanl(0) { |a, b| a + b }[1..-1]
=> [1, 3, 6, 10]


text:
Q: Python: call method of another class, specified as parameter of function I know the simplified example below is embarrassingly ugly ... hence why I have come to SO to share it with the world.
I would like to be able to call a class method from cls, specifying the particular method within callmethod.
class cls(object):
    def __init__(self, var1):
        self.var1 = var1
    def method1(self):
        return self.var1 ** 2
    def method2(self):
        return self.var1 ** 3

def callmethod(method, var1):
    methods = {'method1' : cls(var1).method1(),
               'method2' : cls(var1).method2()
              }
    return methods[method]

callmethod('method1', 2)
Out[56]: 4

Is there a way to go about this without creating a (possibly large and cumbersome) dict that links a string form of each method to the actual thing?

A: What you're looking for is likely just:
def callmethod(method, arg)
    inst = cls(arg)
    return getattr(inst, method)()

You can think of a.b as a syntax sugar for getattr(a, "b")


text:
Q: How to new a new access token from a refresh token using vb.net? I don't know if you can help me understand the right way forward with this issue. I need to provide a little bit of background first.
I have a VB.Net Console Utility that uses the Google V3 Calendar API. This utility has the following process to authenticate:
Private Function DoAuthentication(ByRef rStrToken As String, ByRef rParameters As OAuth2Parameters) As Boolean
    Dim credential As UserCredential
    Dim Secrets = New ClientSecrets() With {
        .ClientId = m_strClientID,
        .ClientSecret = m_strClientSecret
    }
    'm_Scopes.Add(CalendarService.Scope.Calendar)
    m_Scopes.Add("https://www.googleapis.com/auth/calendar https://www.google.com/m8/feeds/ https://mail.google.com/")

    Try
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, m_Scopes,
                                                                 "user", CancellationToken.None,
                                                                 New FileDataStore("PublicTalkSoftware.Calendar.Application")).Result()

        ' Create the calendar service using an initializer instance
        Dim initializer As New BaseClientService.Initializer() With {
            .HttpClientInitializer = credential,
            .ApplicationName = "~~~~~~~~~~"
        }
        m_Service = New CalendarService(initializer)

        rStrToken = credential.Token.AccessToken.ToString()
        rParameters.AccessToken = credential.Token.AccessToken
        rParameters.RefreshToken = credential.Token.RefreshToken
    Catch ex As Exception
        ' We encountered some kind of problem, perhaps they have not yet authenticated?
        Return False
    End Try

    Return True
End Function

This part of the application process works fine. The data store file gets created and once the user has authenticated it all seems to just work find from there on. The user will be able to update the calendar without any further authenticating on there part.
Now, I also have a part of my MFC (the main application) project that sends emails for the user. This uses the following CkMainManW library.
For the most part that works too. If the user has correctly set up their credentials it is fine. However, if they are using GMail, then I do things slightly differently. This is to avoid the need to have the "Allow third party apps" option to be ticked in the Google account.
So, for GMail users, we send emails like this:
mailman.put_SmtpUsername(strUsername);
mailman.put_OAuth2AccessToken(strGoogleToken);

As you can see, I use the OAuth2AccessToken. This actual value passed is the credential.Token.AccessToken.ToString() value stored from when the user authenticated. Now, I have since understood that this actual token only lasts for one hour. This would explain why some users have to repeatedly run my calendar authentication again to get a new access token.
Clearly, when I do the calendar authentication which uses the data store file, it does something under the hood the avoid the user being asked all the time to authenticate.
Now, I have read this tutorial about using the Chilkat Library for this. I notice now that in the sample code it has a comment:
//  Now that we have the access token, it may be used to send as many emails as desired
//  while it remains valid.  Once the access token expires, a new access token should be
//  retrieved and used.

So, with all the background, how do I resolve my issue? So I have a data store file that contains the original access token from when they authorised and a refresh token. This file was created by the VB.Net command line module.
By the sounds of it, the Chilkat routine needs an access token that is valid. So, what is the right way for me to get an updated access token from the refresh token, so that when I send emails it won't fail after an hour?
Update
I am getting myself confused. I changed my code so that it called the DoAuthentification call above to get the refresh token and access token. But I am finding that the actual data store file is not getting revised. The text file is not being revised.
I have to revoke access and then do the authentication to get the data store file revised. And it is only once it has been revised that the access token will work for sending emails.

A: I think I have found the solution. I saw this answer:
https://stackoverflow.com/a/33813994/2287576
Based on the answer I added this method:
Private Function RefreshAuthentication(ByRef rStrAccessToken As String, ByRef rStrRefreshToken As String) As Boolean
    Dim parameters As New OAuth2Parameters
    With parameters
        .ClientId = m_strClientID
        .ClientSecret = m_strClientSecret
        .AccessToken = rStrAccessToken ' Needed?
        .RefreshToken = rStrRefreshToken
        .AccessType = "offline"
        .TokenType = "refresh"
        .Scope = "https://www.googleapis.com/auth/calendar https://www.google.com/m8/feeds/ https://mail.google.com/"
    End With

    Try
        Google.GData.Client.OAuthUtil.RefreshAccessToken(parameters)
        rStrAccessToken = parameters.AccessToken
        rStrRefreshToken = parameters.RefreshToken
        RefreshAuthentication = True
    Catch ex As Exception
        RefreshAuthentication = False
    End Try
End Function

I am not sure if I need to pass in the existing access token or not before refreshing. But either way, the tokens get updated and I can proceed with sending emails.

A: FYI, in the end it became apparent that I did not need any bespoke Refresh at all because the system manages it for you under the hood.
Private Async Function DoAuthenticationAsync() As Task(Of Boolean)
    Dim credential As UserCredential
    Dim Secrets = New ClientSecrets() With {
        .ClientId = m_strClientID,
        .ClientSecret = m_strClientSecret
    }

    Try
        credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, m_Scopes,
                                                             "user", CancellationToken.None,
                                                             New FileDataStore("xxx.Calendar.Application"))

        ' Create the calendar service using an initializer instance
        Dim initializer As New BaseClientService.Initializer() With {
            .HttpClientInitializer = credential,
            .ApplicationName = "yy"
        }

        m_Service = New CalendarService(initializer)

    Catch ex As Exception
        ' We encountered some kind of problem, perhaps they have not yet authenticated?
        ' Can we isolate that as the exception?
        m_logger.Error(ex, "DoAuthenticationAsync")

        Return False
    End Try

    Return True
End Function

I have not required any bespoke Refresh of tokens for a long time now.


text:
Q: Django: How to update multiple rows in admin table? I got the next problem: I want tu update the "TOTAL PAGADO" field with the previous column "PRECIO TOTAL" by selecting multiple rows and then apply an action called "Saldar precio" which return the "SALDO" field to 0.
enter image description here
and the return is that:
enter image description here
i've been trying something like that:
**models.py**
class PedidoCliente(Pedido):
    class Meta:
        verbose_name = "Pedidos (Ingresos)"
        verbose_name_plural = "Pedido (Ingresos)"

    def get_precio_total(self):
            detalle_pedido = DetallePedidoCliente.objects.filter(pedido=self)
            precio_total = 0
            for detalle in detalle_pedido:
               precio_total += detalle.precio_venta
            return "%.2f" % (precio_total, )

     precio_total = property(get_precio_total)

class DetallePedidoCliente(DetallePedido):
    class Meta:
        verbose_name = "Detalle pedido"
        verbose_name_plural = "Detalle pedido"

    precio_venta = models.DecimalField(max_digits=16, decimal_places=2, default = 0)

**admin.py**
class PedidoClienteAdmin(admin.ModelAdmin):
      list_display = (... ,'precio_total',...)
      actions = [...,'saldar_precio',...]

      def saldar_precio(self, request, queryset):
          t_p = queryset.update(total_pagado= queryset[0].get_precio_total())
      return t_p

where .get_precio_total() is a calculated column, not a field.
I know that the problem here is that 0, that only return the first selected value, but i dont know how to solve it.
It's my first time doing a question here so sorry if i'm breaking some posts rules (and sorry for my english)
Thanks!
SOLUTION
The problem here was that calculated column wasn´t a field, so i transform it to a field. How?
**models.py**
class PedidoCliente(Pedido):
    class Meta:
        verbose_name = "Pedidos (Ingresos)"
        verbose_name_plural = "Pedido (Ingresos)"

    precio_final_nuevo = models.DecimalField(max_digits=10, decimal_places=2,verbose_name="Precio $")

    @property
    def get_precio_total(self):
            detalle_pedido = DetallePedidoCliente.objects.filter(pedido=self)
            precio_total = 0
            for detalle in detalle_pedido:
               precio_total += detalle.precio_venta
            return "%.2f" % (precio_total, )

     def save(self, *args, **kwargs):
        self.precio_final_nuevo = self.get_precio_total_nuevo
        super(PedidoCliente, self).save(*args, **kwargs)

So, now i can call 'precio_final_nuevo' as a field, which stores the calculated column 'precio_total'.

A: You can use the F expression to address this issue. It will allow you to get another column on the same row
from django.db.models import F

total_qs_updated = queryset.update(total_pagado=F('precio_total'))

update:
calculate the 'precio_total' in db
from django.db.models import IntegerField, Case, When, Value

total_qs_updated = queryset.update(total_pagado=Case(
    When(
        detallepedidocliente__isnull=False,
        then=Sum('detallepedidocliente__precio_venta')
    ), default=Value(0)))


text:
Q: What are the steps for factorizing $1 - ab - cd + abcd$? I can see that $1 - ab - cd + abcd$ factors to $(1-cd)(1-ab)$ but only because I tried a lot of different factors in a trial and error method, so it took me a while. I was wondering what the pattern to observe is and what the general/efficient method for factoring something like this is?

A: The steps are usually called "factoring by grouping."  As all factoring is basically educated trial-and-error, you should be encouraged that you found the correct factorization.  Anyway, here's more detail about factoring by grouping:
$$
\begin{align*}
  1 - ab - cd + abcd &= (1-ab) - (cd - abcd) \\
  &= (1-ab) - cd(1 - ab) \\
  &= (1-ab)(1-cd).
\end{align*}
$$
The crucial steps are: finding groups that look very similar -- with a goal of factoring a gcd from each group.  If each group now contains the same expression in parentheses, then that expression can be factored out.
Hope this helps!


text:
Q: Not able to retrieve Plist value to NSDictionary I use following code to display the plist into NSDictionary/NSMutableDictionary ,but when i print that variable it returns null value? please help me?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *Path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Recent.plist"];
NSLog(@"%@",Path); //Path is correct

NSDictionary *d=[[NSDictionary alloc]initWithContentsOfFile:Path];
NSMutableDictionary *data = [[NSMutableDictionary alloc]initWithContentsOfFile:Path];
NSLog(@"%@",d);

A: Buddy ,Your code is correct ,but please make sure that your plist root is array or dictionary
i think it should be array in your case
please try this code ,i just change that NSMutableDictionary to NSMutableArray in your code
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *Path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Recent.plist"];
NSLog(@"%@",Path);

NSMutableArray *d = [[NSMutableArray alloc]initWithContentsOfFile:Path];

It has to work


text:
Q: Как сохранить данные с таймера в Pagination JavaScript? Имеется 5 страниц и таймер. Задача состоит в том, чтобы сохранить в итоге время, проведённое пользователем на каждой странице.
Т.е., когда произойдёт клик на следующую страницу, то счётчик обнулится и начнёт отсчёт сначала. А данные о проведенном времени сохранятся в переменную для каждой страницы

var timer = 0;
var interval = setInterval(function() {
  timer++;
  $('.timer').text(timer);
}, 1000);
body {
  background: #222;
}

.timer {
  font-size: 2.5em;
  padding: 10px;
  text-align: center;
  margin: 0 auto;
  background: #ccc;
}

.pagination {
  display: inline-block;
}

.pagination a {
  color: black;
  float: left;
  padding: 8px 16px;
  text-decoration: none;
}

.pagination a.active {
  background-color: #4CAF50;
  color: white;
}

.pagination a:hover:not(.active) {
  background-color: #ddd;
}

0

  «
  1
  2
  3
  4
  5
  »

Как бы это реализовать и вывести на отдельной странице в конце? То есть:

*

*страница 1 - время 1 мин 10 сек

*страница 2 - время 1 мин
и так далее.

A: Записывай все в локальную память браузера, иначе при переходе между страницами переменную ты сразу же потеряешь.
Запись:
localStorage.setItem('page-1', JSON.stringify(timer_value));

Чтение (используй на финальной странице):
var page1 = JSON.parse(localStorage.getItem('page-1'));

Если у тебя перехода между страницами нет и ты рассматриваешь вариант с табами на одной страницу то первым делом почитай про замыкания и оператор let.
В прочем в самом примитивном виде можно обойтись и без них.

var timer = 0;
var interval = setInterval(function() {
  timer++;
  $('.timer').text(timer);
}, 1000);

var data = {
  'page-1': 0,
  'page-2': 0,
  'page-3': 0,
  'page-4': 0,
  'page-5': 0,
}

function updateResult(){
$("#result").html(JSON.stringify(data));
}

$(".page").click(function(e){
  if(!$(this).hasClass("active")){
    data[$(".page.active").attr("data-val")]+=timer;
    timer = 0;
    updateResult();
    $(".page.active").removeClass("active");
    $(this).addClass("active");
  }
});
body {
  background: #fff;
}

.timer {
  font-size: 2.5em;
  padding: 10px;
  text-align: center;
  margin: 0 auto;
  background: #ccc;
}

.pagination {
  display: inline-block;
}

.pagination a {
  color: black;
  float: left;
  padding: 8px 16px;
  text-decoration: none;
}

.pagination a.active {
  background-color: #4CAF50;
  color: white;
}

.pagination a:hover:not(.active) {
  background-color: #ddd;
}

0

  «
  1
  2
  3
  4
  5
  »

Result


text:
Q: OpenCL clCreateBuffer() crashes the program I have taken up OpenCL programming as part of a university project and I have a bit of a problem when I try to input data to a buffer object during the clCreateBuffer() routine.
The program is a simple two-dimensional matrix addition. The code is as follows:
#define _CRT_SECURE_NO_WARNINGS
#define PROGRAM_FILE "add_kernel.cl"
#define ADD_FUNC "add_matrix"
#define MATRIX_DIM 256

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#ifdef MAC
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif

/* Find a GPU associated with the first available platform */
cl_device_id create_device() {

   cl_platform_id platform;
   cl_device_id dev;
   int err;

   /* Identify a platform */
   err = clGetPlatformIDs(1, &platform, NULL);
   if(err < 0) {
      perror("Couldn't identify a platform");
      exit(1);
   }

   /* Access a GPU */
   err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &dev, NULL);
   if(err < 0) {
      perror("Couldn't access any GPU type");
      exit(1);
   }

   return dev;
}

cl_program build_program(cl_context ctx, cl_device_id dev, const char* filename) {

   cl_program program;
   FILE *program_handle;
   char *program_buffer, *program_log;
   size_t program_size, log_size;
   int err;

   /* Read program file and place content into buffer */
   program_handle = fopen(filename, "r");
   if(program_handle == NULL) {
      perror("Couldn't find the program file");
      exit(1);
   }
   fseek(program_handle, 0, SEEK_END);
   program_size = ftell(program_handle);
   rewind(program_handle);
   program_buffer = (char*)malloc(program_size + 1);
   program_buffer[program_size] = '\0';
   fread(program_buffer, sizeof(char), program_size, program_handle);
   fclose(program_handle);

   /* Create program from file */
   program = clCreateProgramWithSource(ctx, 1,
      (const char**)&program_buffer, &program_size, &err);
   if(err < 0) {
      perror("Couldn't create the program");
      exit(1);
   }
   free(program_buffer);

   /* Build program */
   err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
   if(err < 0) {

      /* Find size of log and print to std output */
      clGetProgramBuildInfo(program, dev, CL_PROGRAM_BUILD_LOG,
            0, NULL, &log_size);
      program_log = (char*) malloc(log_size + 1);
      program_log[log_size] = '\0';
      clGetProgramBuildInfo(program, dev, CL_PROGRAM_BUILD_LOG,
            log_size + 1, program_log, NULL);
      printf("%s\n", program_log);
      free(program_log);
      exit(1);
   }
   return program;
}

int main(){

    /* Host/device data structures */
   cl_device_id device;
   cl_context context;
   cl_command_queue queue;
   cl_program program;
   cl_kernel add_kernel;
   size_t global_size;
   cl_ulong mem_size;
   cl_int i, j, err, check;

   /* Data and buffers */
   cl_uint matrix_dim;
   float a_mat[MATRIX_DIM][MATRIX_DIM], b_mat[MATRIX_DIM][MATRIX_DIM],
         c_mat[MATRIX_DIM][MATRIX_DIM], check_mat[MATRIX_DIM][MATRIX_DIM];
   cl_mem a_buffer, b_buffer, c_buffer;

   /* Initialize A, B, and check matrices */
   srand((unsigned int)time(0));
   for(i=0; i<MATRIX_DIM; i++) {
      for(j=0; j<MATRIX_DIM; j++) {
         a_mat[i][j] = (float)rand()/RAND_MAX;
      }
   }
   srand((unsigned int)time(0));
   for(i=0; i<MATRIX_DIM; i++) {
      for(j=0; j<MATRIX_DIM; j++) {
         b_mat[i][j] = (float)rand()/RAND_MAX;
         check_mat[i][j] = 0.0f;
      }
   }
   for(i=0; i<MATRIX_DIM; i++) {
      for(j=0; j<MATRIX_DIM; j++) {
            check_mat[i][j] += a_mat[i][j] + b_mat[i][j];
      }
   }

   /* Create a device and context */
   device = create_device();
   context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
   if(err < 0) {
      perror("Couldn't create a context");
      exit(1);
   }

   /* Build the program */
   program = build_program(context, device, PROGRAM_FILE);

   add_kernel = clCreateKernel(program, ADD_FUNC, &err);
   if(err < 0) {
      perror("Couldn't create a kernel");
      exit(1);
   };

    /* Create buffers */
   a_buffer = clCreateBuffer(context,
         CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
         sizeof(a_mat), a_mat, &err);
   if(err < 0) {
      perror("Couldn't create buffer A");
      exit(1);
   };
   b_buffer = clCreateBuffer(context,
         CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
         sizeof(b_mat), b_mat, &err);
   if(err < 0) {
      perror("Couldn't create buffer B");
      exit(1);
   };
   c_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY,
         sizeof(c_mat), NULL, &err);
   if(err < 0) {
      perror("Couldn't create buffer C");
      exit(1);
   };

    /* Create a command queue */
   queue = clCreateCommandQueue(context, device, 0, &err);
   if(err < 0) {
      perror("Couldn't create a command queue");
      exit(1);
   };

   /* Create arguments for multiplication kernel */
   err = clSetKernelArg(add_kernel, 0, sizeof(a_buffer), &a_buffer);
   err |= clSetKernelArg(add_kernel, 1, sizeof(b_buffer), &b_buffer);
   err |= clSetKernelArg(add_kernel, 2, sizeof(c_buffer), &c_buffer);
   global_size = MATRIX_DIM * MATRIX_DIM;

   //printf("%lu\n", global_size);

   err = clEnqueueNDRangeKernel(queue, add_kernel, 1, NULL, &global_size,
         NULL, 0, NULL, NULL);
   if(err < 0) {
      perror("Couldn't enqueue the addition kernel");
      exit(1);
   }

   /* Read output buffer */
   err = clEnqueueReadBuffer(queue, c_buffer, CL_TRUE, 0,
      sizeof(c_mat), c_mat, 0, NULL, NULL);
   if(err < 0) {
      perror("Couldn't read the buffer");
      exit(1);
   }

   /* Check result */
   check = 1;
   for(i=0; i<MATRIX_DIM; i++) {
      for(j=0; j<MATRIX_DIM; j++) {
         if(c_mat[i][j] != check_mat[i][j]){
            check = 0;
            break;
         }
      }
   }

   if(check)
      printf("Addition check succeeded.\n");
   else
      printf("Addition check failed.\n");

/* Deallocate resources */
   clReleaseMemObject(a_buffer);
   clReleaseMemObject(b_buffer);
   clReleaseMemObject(c_buffer);
   clReleaseKernel(add_kernel);
   clReleaseCommandQueue(queue);
   clReleaseProgram(program);
   clReleaseContext(context);
    return 0;
}

The kernel code is the following:
__kernel void add_matrix(__global float* matrix_a,
                          __global float* matrix_b,
                          __global float* result) {

   int i = get_global_id(0);
   result[i] = matrix_a[i] + matrix_b[i];
}

Now, it works great for dimensions up to 358x358, but as soon as I put 359 in the MATRIX_DIM it crashes. It shows the usual "foo.exe has stopped working". I know it has to do something with the clCreateBuffer() command because if I remove the code from the first clCreateBuffer() and below, it runs and terminates fine, but as soon as I add even one it crashes.
The CL_DEVICE_MAX_MEM_ALLOC_SIZE option shows a number of 512MB of available memory and the data I am trying to pass is much less than that.
Is there anything I can do to increase the ammount of data I can process?
My GPU is a Radeon Sapphire HD5770
EDIT: After a suggestion in the comments I ran the debugger which yielded the following message:
Program received signal SIGSEGV, Segmentation fault.
In amdocl!_aclHsaLoader () (C:\WINDOWS\SysWOW64\amdocl.dll)
#15 0x00401355 in create_device () at C:\test\testcl.c:26
C:\test\testcl.c:26:503:beg:0x401355

I am really not sure what this means though. Any ideas?

A: The main problem is, that you allocate to much memory on the stack at these code lines, so that, you got a stack overflow:
float a_mat[MATRIX_DIM][MATRIX_DIM], b_mat[MATRIX_DIM][MATRIX_DIM],
      c_mat[MATRIX_DIM][MATRIX_DIM], check_mat[MATRIX_DIM][MATRIX_DIM];

In my test here, the execution didn't even entered the main method. You have to allocate these matrices on the heap with:
float *a_mat = calloc(MATRIX_DIM*MATRIX_DIM, sizeof(*a_mat));
float *b_mat = calloc(MATRIX_DIM*MATRIX_DIM, sizeof(*b_mat));
float *c_mat = calloc(MATRIX_DIM*MATRIX_DIM, sizeof(*c_mat));
float *check_mat = calloc(MATRIX_DIM*MATRIX_DIM, sizeof(*check_mat));

But now, you have only a 1-dimensional (1D) data-buffer for each matrix, so that, you have to change every 2D index [i][j] into the corresponding 1D index [i*MATRIX_DIM][j], e.g.:
a_mat[i*MATRIX_DIM+j] = (float)rand()/RAND_MAX;

EDIT: You have to also update the calls to clCreateBuffer und clEnqueueReadBuffer. The matrix size cannot be determined with sizeof(matrix_name) anymore (where matrix_name is one of a_mat, b_mat, ...). You have to replace every such sizeof (there are 4 of some) with MATRIX_DIM*MATRIX_DIM*sizeof(*matrix_name). Don't forget the derefence before the matrix_name, e.g.:
a_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
      MATRIX_DIM*MATRIX_DIM*sizeof(*a_mat), a_mat, &err);

(End of Edit).
Don't forget to release the data-buffers at the end:
free(a_mat);
free(b_mat);
free(c_mat);
free(check_mat);

To get even the kernel to run, I had even to fix the reading of the kernel program. The return value of ftell was always a little bit too large. The actual number of bytes is instead returned by fread. Thus, change these lines
program_buffer[program_size] = '\0';
fread(program_buffer, sizeof(char), program_size, program_handle);

to
program_size  = fread(program_buffer, sizeof(char), program_size, program_handle); // changed
program_buffer[program_size] = '\0'; // moved here


text:
Q: Super weird HTML mess up I have a comment system, it works by adding a row to a SQL database. Anyway That works, but then when I echo out the comment div gets all messed up.. Anyway here is the page it is on: http://learntc.net/index.php.
PHP:
while($row = mysql_fetch_array($result))
{
    if ($count==1)
    {
      $bg == "33383C" ;
      $count = 0;
    }
    echo "
";
    echo "
";
        echo "";
        echo "
" . $row["username"] . "
";
    echo "
";
    echo "
";
        echo "
" . $row["comment"] . "
";
        echo "
" . $row["date"] . "
";
    echo "
";
    echo "
";

    $bg = "#282C2F";
    $count = $count + 1;
}

CSS:
.comments{
    float: right;
    padding: 10px;
    width: 50%;
    border: 1px solid #454D53;
}
.cPic{
    width: 60px;
    height: 60px;
}
.imageAndName{
    width: 30%;
    overflow: hidden;
    float: left
}
.imageAndName a{
    display: block;
}
.textStuff{
    width: 70%;
    float: right;

}
.post{
    overflow: hidden;
    width: 100%;
}
.comment{
    padding-bottom: 5px;
}

A: Add clear: both to your .comment style.

A: Problem one:
$bg == "33383C" ;

should be
$bg = "#33383C";

I don't see anything else. The div is probably screwed up for this reason.


text:
Q: R: Extracting information from Google Places within the Tidyverse I've a data frame with locations and I want to append phone numbers and websites to them from Google Places in a pipeable solution.
The closest I've gotten to doing this was using googleway, unlisting the JSON and using regexes to extract the place id, and doing the same again for the phone numbers and email addresses. Is there a more targeted way of doing this?
library(googleway)
library(tidyverse)

set_key("api")

index_no <- c(1,2,3,4)
landmark<- c("Sydney Opera House","Eiffel Tower","Empire State Building","Big Ben")
df <- data.frame(index_no,landmark, stringsAsFactors = F)

df %>%
  rowwise() %>%
  # Place IDs are required for the function beneath
  do(data.frame(., place_id  = unlist(google_places(search_string = .$landmark)))) %>%
  # Place IDs are 27 chars
  filter(grepl("^\\S{27}$", place_id )) %>%
  do(data.frame(., details = unlist(google_place_details(place_id  = .$place_id )))) %>%
  unique() %>%
  # Gets non-Google URls and Phone Numbers
  filter(grepl("(?!.*(google|maps))(^https?.*|^\\+\\d)", details, perl = T )) %>%
  group_by(landmark) %>%
  mutate(seq = 1:n()) %>%
  spread(seq, details) %>%
  rename(phone_number = `1`, website = `2`) %>%
  select(-place_id) %>%
  ungroup()

A: I doubt there is. It is a two step process at the side of Google API (see the documentation: https://developers.google.com/places/web-service/details):
You need to :

*

*get the unique placeid (via Place Search call)

*get the contact details for your placeid (via Place Details call)

You might have more control over the process if you pasted your url yourself and executed it via httr (the Google API is known for breaking changes, and hard for R packages to keep pace with) and you can wrap the ugly piece of code in your own function, making the call tidy - but ultimately it will have to be 2 API calls.


text:
Q: Bind button click to set Icollection view source When my aapp launched i read a pricing file method attached to the soource using viewm-model approach then display it to the datagrid.
I'm trying to read the pricing file when i click on a button then attach the method to the view source.
I tried to set the view source on button click but nothing is displayed in the datagrid?  thanks for your help.
case "ReadPricing": //to read local pricing file
cvs.Source = GetProductsPriceListXML(); // method to read the xml file
cvs.View.Filter = Filter;
View = cvs.View;
return;

Button:
  <Button x:Name="breadxml"  HorizontalAlignment="Center" Margin="62,10" Width="76"  Command="{Binding MyCommand}" CommandParameter="ReadPricing" Height="43" >
                <TextBlock Text="Read Pricing File" TextWrapping="Wrap" TextAlignment="Center"/>
            </Button>

Datagrid:
        <DataGrid VerticalAlignment="Top" HorizontalAlignment="Left"
          SelectedItem="{Binding SelectedProduct}"
          ItemsSource="{Binding View}" AutoGenerateColumns="False"
          CanUserAddRows="False" ScrollViewer.VerticalScrollBarVisibility="Visible"
          Margin="0,2,0,0"
          Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type DockPanel}}, Path=ActualHeight}"  >
            <DataGrid.Columns>
                <DataGridTextColumn Header="MianProduct" Binding="{Binding Mainproduct}" Width="*" IsReadOnly="True"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*" IsReadOnly="True"/>
                <DataGridTextColumn Header="Price" Binding="{Binding Price}" Width="*" />
                <!--<DataGridTextColumn Header="Visible" Binding="{Binding Visible}" Width="*" />-->
                <DataGridTemplateColumn Header="Visible"  Width="100" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding Visible, UpdateSourceTrigger=PropertyChanged}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="NameIcon" Binding="{Binding NameIcon}" Width="*" />
            </DataGrid.Columns>
        </DataGrid>

Datacontext/convertor:
 <Window.DataContext>
        <local:ProductPriceViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <local:MediaConverter x:Key="mconv" />
    </Window.Resources>

Class-ViewModel:
class ProductPriceViewModel : INotifyPropertyChanged
    {

        public ProductPriceViewModel() { }

        public event PropertyChangedEventHandler PropertyChanged;
        public event EventHandler? CanExecuteChanged;

        public void OnPropertyChanged([CallerMemberName] String info = "") =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));

        private bool Filter(object item)
        {
            Product p = item as Product;
            if (p == null) return true;
            var ret = true;
            if (!String.IsNullOrEmpty(MainProductSearch))
                ret = ret && p.Mainproduct.IndexOf(MainProductSearch, StringComparison.OrdinalIgnoreCase) >= 0 ||
                p.Name.IndexOf(MainProductSearch, StringComparison.OrdinalIgnoreCase) >= 0;

            return ret;
        }

        private CollectionViewSource cvs = new CollectionViewSource();
        public ICollectionView View { get; set; }

        public ICommand MyCommand { get => new RelayCommand(executemethod, canexecutemethod); }

        string pricinglocalfile = @"C:\xmltest\Prices.txt";
        private void executemethod(object parameter)
        {
            switch (parameter.ToString())
            {

                case "ReadPricing": //to read local pricing file
                    cvs.Source = GetProductsPriceListXML();
                    return;

                case "SaveFile":
                    data.Save("xxx.txt");
                    return;

                default:
                    MediaType = parameter.ToString();
                    break;
            }
            View.Refresh();
        }

        private static bool canexecutemethod(object obj) => true;

        XElement data;

        private List<Product> GetProductsPriceListXML()
        {
            var mylist = new List<Product>();

            data = XElement.Load(pricinglocalfile);
            foreach (XElement xe1 in data.Elements())
                if (xe1.Name == "Products")
                    foreach (var xe2 in xe1.Elements()) mylist.Add(new Product(xe2));
            return mylist;
        }

    }

A: Although I've not used it myself, reading through Microsoft documentation leads me to believe that CollectionView is actually a control that you can extend that allows you to manipulate a data collection within the UI without actually changing the data itself. It also doesn't appear to be used with DataGrid types but instead replaces them, specifically it expands upon or replaces ListView.
In this regard you need to bind your ItemSource to an actual data list e.g., ObservableCollection<Product>, whether you use a DataGrid type or a CollectionView type within your UI.
Thus I would recommend that you change the following:
    private CollectionViewSource cvs = new CollectionViewSource();
    public ICollectionView View { get; set; }

to
public ObservableCollection<Product> ProductList {get;set;}

This will automatically trigger a NotifyCollectionChanged when updated.
Then change :
case "ReadPricing": //to read local pricing file
    cvs.Source = GetProductsPriceListXML();
    return;

to
case "ReadPricing": //to read local pricing file
    ProductList.Clear();
    var list = GetProductsPriceListXML();
    foreach(var p in list)
    {
        ProductList.Add(p);
    }
    return;

or
case "ReadPricing": //to read local pricing file
    ProductList = new ObservableCollection<Product>(GetProductsPriceListXML());
    NotifyPropertyChanged("ProductList");
    return;

Then in your View
    ItemsSource="{Binding View}" AutoGenerateColumns="False"

becomes
    ItemsSource="{Binding ProductList}" AutoGenerateColumns="False"

I believe that if you then wished to manipulate the layout or content of your ProductList at run time you would need to replace your DataGrid with a CollectionView, bind it's ItemSource to ProductList, finally creating a ControlView that presents a CollectionView type property and manipulates the presentation of the data - examples to be found here


text:
Q: Can fusion see through newtype wrappers? Given:
newtype MyVec = MyVec { unVec :: Data.Vector }
  deriving (Functor, etc)

This will create (something like) this:
instance Functor MyVec where
  fmap f = MyVec . Data.Vector.fmap f . unVec

Will Vectors fusion rules fire and rewrite fmap f . fmap g $ myVec into fmap (f . g) myVec?
Are there any pitfalls I should be aware of? Afaik the problem where you "pay" for new types in containers was solved in GHC 7.8, was it?

A: Fusion rules operate on functions, not on types. Your functions on MyVec won't have fusion rules, unless you write them to reuse the underlying ones.
E.g.
map :: (a -> b) -> MyVec a -> MyVec b
map f = MyVec . Vector.map f . unVec
{-# INLINE map #-}

Then we'd have uses:
map f . map g

which will inline to:
MyVec . Vector.map f . unVec . MyVec . Vector.map g . unVec

GHC should then erase the newtype constructor, yielding a regular stream, suitable for fusion:
MyVec . Vector.map f . Vector.map g . unVec

You can confirm this by running GHC and looking at the rewrite rules firing.
Alternatively, you can add your own "MyVec.  unVec" rewrite rule, but GHC should already cover that.


text:
Q: How to list all possible string arguments of a specific function? For example, to learn the function Alphabet, we can read its document. But it's rather ambiguous, like "Some languages have extra properties". How to find all the languages that can be used in Alphabet ?
And how to find all the extra properties of those languages, like "index characters" of "spanish" Alphabet["Spanish", "IndexCharacters"]?
Which means how to find all possible strings that can be passed into Alphabet[#]&  ,or  can be passed into Alphabet["Spanish",#]& ?
For more examples, how to find all possible strings that can be used in Entity[#]& , or in Entity["PlaneCurve",#]&, or in Entity["PlaneCurve","Cardiod",#]&?.
How to find all possible strings that can be used in SystemModel["Modelica.Electrical.Analog.Basic", #]&?
This question is not specified in those three functions. Is there a more general way to find all those strings which can be used as arguments or options in any functions?

A: My first attempt involved trying Alphabet on every language from EntityList@"Language", all 9211 of them.  I also dug around with GeneralUtilities`PrintDefinitions@Alphabet and found a few more.
b3m2a1's comment gets most or all of those languages with his one-liner:
EntityValue[EntityClass["Alphabet",All],"FullCharacters","Association"]

It's hard to compare his code to my results, since the alphabets given don't match with the results of Alphabet in every case.  Consider StringJoin@Alphabet@"Korean" (no different with the Entity vs "Korean")
ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ

vs what is returned by EntityValue
Entity["Alphabet","Korean::2v535"] ->
"ㄱᄀ-ᄒ伽佳假價加可...廊朗浪狼來ㅁㅂㅅㅇ樂ㅈㅊ車ㅋㅌㅍㅎ滑ᅡ-ᅵᆨ-ᇂ郎"

(I've added the ellipsis and stringjoin)

Are you more interested in which language/curve/other entities exist, or are you interested in what are all the valid inputs and outputs of functions like Alphabet?  They're not the same thing.


text:
Q: git reflog references pruned commits, but does not show the reflog for the branch git gc shows:
warning: reflog of 'refs/remotes/origin/abc_branch' references pruned commits

But, when I try to see the reflog, I get nothing:
$ git reflog show origin/abc_branch@{0}

fatal: ambiguous argument 'origin/abc_branch@{0}': unknown revision or path not in the working tree.

I know the syntax is right, because that happened to another branch and I was able to see the reflog - and remove it.
The abc_branch has been deleted on the remote without being merged - commits deleted. I don't want to recover it, I just want to get rid of the warning.

A: If you just want to get rid of the abc_branch ref, you could try:
git update-ref -d refs/remotes/origin/abc_branch


text:
Q: How can I make user-entered messages with color codes specified with '&' display colored in-game? I am unsure on how to allow users of my plugin to enter color codes with & and have them display properly.  I know that I can use the constants in ChatColor to put various colors in messages sent by the plugin, but I don't know how to allow users to enter their own colored messages.
Here is my code:
package me.avy.simplemotd;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;

public class motd extends JavaPlugin implements Listener {

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent e) {
            Player p = e.getPlayer();
            p.sendMessage(ChatColor.AQUA + getConfig().getString("message"));
    }

    public void onEnable()
    {
      Bukkit.getServer().getLogger().info(" SimpleMotd enabled correctly!");
      saveDefaultConfig();
      Bukkit.getServer().getPluginManager().registerEvents(this, this);
    }

    public void onDisable()
    {
      Bukkit.getServer().getLogger().info(" SimpleMotd disabled correctly!");
    }

    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
            if (cmd.getName().equalsIgnoreCase("motd")) {
                    sender.sendMessage(ChatColor.AQUA + "MOTD: " + getConfig().getString("message"));
                    return true;
            }
            if (cmd.getName().equalsIgnoreCase("setmotd")) {
                    if (!sender.hasPermission("motd.set")) {
                            sender.sendMessage(ChatColor.RED + "You are not permitted to do this!");
                            return true;
                    }
                    if (args.length == 0) {
                            sender.sendMessage(ChatColor.RED + "Please specify a message!");
                            return true;
                    }
                    StringBuilder str = new StringBuilder();
                    for (int i = 0; i < args.length; i++) {
                            str.append(args[i] + " ");
                    }
                    String motd = str.toString();
                    getConfig().set("message", motd);
                    saveConfig();
                    sender.sendMessage(ChatColor.GREEN + "MOTD set to: " + motd);
                    return true;
            }
            return true;
    }
}

I want players to be able to use /setmotd &cRed &aGreen &9Blue and have the MOTD be displayed to them with the appropriate colors, using the Minecraft color code format.  There are several other plugins that are capable of displaying messages set that way, so it must be possible.
How can I convert a message like &cRed &aGreen &9Blue into one that displays correctly in-game?

A: You can use ChatColor.translateAlternateColorCodes to convert color codes using & to the format used by ChatColor.  (Internally, that's §).
translateAlternateColorCodes takes a replacement character and then the text to replace in.  For the replacement character, you would want to use '&' (note the single quotes and not the double quotes).  translateAlternateColorCodes has special logic to only replace valid codes, so &eWelcome becomes §eWelcome (which, in-game, is "Welcome" in yellow text), but I like cats & dogs does not get converted and displays in-game as I like cats & dogs.
You probably will want to do the replacement in all cases where the message is displayed, but not when it is set.  That way, if someone edits the config manually, & can also be used there.  As such, you'll want to edit your code to replace each of the following lines:
p.sendMessage(ChatColor.AQUA + getConfig().getString("message"));

sender.sendMessage(ChatColor.AQUA + "MOTD: " + getConfig().getString("message"));

sender.sendMessage(ChatColor.GREEN + "MOTD set to: " + motd);

With these:
p.sendMessage(ChatColor.AQUA + ChatColor.translateAlternateColorCodes('&', getConfig().getString("message")));

sender.sendMessage(ChatColor.AQUA + "MOTD: " + ChatColor.translateAlternateColorCodes('&', getConfig().getString("message")));

sender.sendMessage(ChatColor.GREEN + "MOTD set to: " + ChatColor.translateAlternateColorCodes('&', motd));

Better yet, you could write a getMotd method that retrieves the MOTD from the configuration with correct formatting, and use that instead:
/**
 * Gets the MOTD from the configuration with formatting that can be used in chat.
 */
private String getMotd()
{
    String rawMessage = getConfig().getString("message");
    return ChatColor.translateAlternateColorCodes('&', rawMessage);
}

You'd use getMotd() in all places you'd want to display your MOTD, rather than directly retrieving it from the configuration.


text:
Q: About transpose matrix transformation problem. I have this problem that I don't understand so I can't solve. I wish someone could explain me it or solve it.

Let $M_2(\mathbb{R})$ the vector space generated by all the square
  matrices of $2\times 2$. Consider the linear transformation $T\colon
 M_2(\mathbb{R})\longrightarrow M_2(\mathbb{R})$ given by $T(A)=A^T$
  (where $A^T$ is the transpose of $A$). Calculate a basis for
  $M_2(\mathbb{R})$ such that the transformation $T$ is represented by a
  diagonal matrix. Which are the possible values for the diagonal?

A: Let me just explain what the problem is asking you to do since this seems to be what you are wanting to know.
The point is that all linear transformations can be represented by a matrix. So you want to find a matrix $A$ such that $T(v) = Av$. Now, this is not hard, you just need to determine what $T$ does to basis elements of $M_2(\mathbb{R})$. Now you need to actually pick a basis such that $A$ is a diagonal matrix.
Let's just try. Let
$$
A = \pmatrix{1 & 0 \\ 0 & 0}, B = \pmatrix{0 & 1 \\ 0 & 0}, C = \pmatrix{0 & 0 \\ 1 & 0}, D = \pmatrix{0 & 0 \\ 0 & 1}.
$$
Then you have a basis for the 4 dimensional vector space. So a matrix for $T$ will be a $4\times 4$ matrix.
Now
$$
T(A) = 1A + 0B + 0C + 0D \\
T(B) = 0A + 0B + 1C + 0 D \\
$$
and so on. So a matrix for $T$ relative to this basis would look something like this
$$
\pmatrix{
1 & 0 & ? & ? \\
0 & 0 & ? & ? \\
0 & 1 & ? & ? \\
0 & 0 & ? & ?
}
$$
So that is the point. Now try to find another basis so that you get a diagonal matrix here.


text:
Q: I was trying to find the sum and average of 3 inputs and use call by reference to do it #code to find sum and average#
#include <stdio.h>
#include <stdlib.h>

//function prototype

void sum_n_avg(double n1,double n2, double n3,double *sum, double *average);
int main()
{
    double s, avg, one, two,three; // declare my values

    printf("enter 3 numbers---> ");

    scanf("%lf%lf%lf",&one,&two,&three);

  sum_n_avg(&s,&avg);

       printf("the sum of the numbers is %lf\n the average of the numbers is ",s, avg);

return 0;
}

void sum_n_avg(double n1,double n2, double n3, double *sum, double *average)
{

  *sum = n1 + n2 + n3;

  *average= (*sum)/3;

}

#I get error messages and I do not know what it means or how to fix it #
 error: incompatible type for argument 1 of 'sum_n_avg'

#error occurs when I call my function#

A: You've declared sum_n_avg to take three floats followed by two pointers to float.
You're calling it with two pointers to floats — the incompatible type for argument 1 (a pointer to float rather than an actual float) should be just one of the errors you receive.
You probably wanted:
sum_n_avg(one, two, three, &s, &avg);

A: This code can help you :
void somme(double n1,double n2, double n3,double *k,double *l)
{
    *k=n1+n2+n3;
    *l=*k/3;
}

int main()
{
    double s1=0, s2=0, one=0, two=0,three=0;

    printf("enter 3 numbers---> ");

    scanf("%lf%lf%lf",&one,&two,&three);

    somme(one,two,three,&s1,&s2);
    //s1=one+two+three;
    //s2=s1/3;

    printf("\nthe sum of the numbers is %f and the average of the numbers is %f\n",s1, s2);
return 0;
}


text:
Q: How do fix height of row in SPGridview?(do't wrap row) I have a Spgridview. I created columns in page-load .
When bind it, the height of row is different. Its height varies based on the content within it.
How do fix it?

A: I find :)
   e.Row.Height = new Unit(25);
            if (grid.Columns.Count > 1)
                for (int i = 1; i < grid.Columns.Count; i++)
                    e.Row.Cells[i].Wrap = false;


text:
Q: Chrome and Firefox/IE behaving differently when using negative margins I'm having an issue when using a negative top margin. Firefox and IE are rendering it differently from Chrome.
I have a layout similar to the following.
Here is the basic structure of my html

Column

Column

Column

Column

Column

Column

And here is an example image of what I'm trying to do.

The blue div is a row of columns with a 1px right border. The red div has the slanted image for the background image (transparent png). I'm using a negative margin on the red div to pull it up and cover the very bottom edge of the blue div so that the borders in the blue div touch the slanted area in the red div. (purple area)
My issue is that in Firefox and IE the position of the content in the red div is being pushed down by the amount of negative top margin that I apply to it. In Chrome this issue doesn't exist. For example. If I apply margin-top: -70px to the red div it will push the content down 70px in IE/FF as well.
I'm not sure what is going on here. Any help would be appreciated.

A: I'm not sure what it could be because you didn't post your CSS but maybe you could some Reset CSS to reset the default CSS settings. Sometimes you need this because all browsers have different default CSS settings.

A: Different browsers do support different code. Try writing code that is only called if it is in  that browser. Example:
    /* Configure the animation for Firefox */
-moz-animation-duration:6s;
-moz-animation-name:spin;
-moz-animation-timing-function:linear;

/* Configure it for Chrome and Safari */
-webkit-animation-duration:6s;
-webkit-animation-name:spin;
-webkit-animation-timing-function:linear;

This is detecting different browsers and saying different things for each. I used this example because it shows that different code can be used for different browsers and sometimes it is needed. This is on one of my own web apps.


text:
Q: How to set a default month in an input element? Say I have an input element like this:
<input type="month">

How can I set the default value of this input element to the current month?

A: You may use some javascript:

const monthControl = document.querySelector('input[type="month"]');
const date= new Date()
const month=("0" + (date.getMonth() + 1)).slice(-2)
const year=date.getFullYear()
monthControl.value = `${year}-${month}`;
<input type="month">

A: To set the value for the month input (input[type="month"]) use only the year and month in the value (yyyy-MM), for example:
<input type="month" id="txtMonth" value="2018-11" />

will display the month as Novermber (in browsers that support month input type, support is patchy).
To populate the field using javascript could do something like:

var txtMonth = document.getElementById('txtMonth');
var date = new Date();
var month = "0" + (date.getMonth() + 1);
txtMonth.value = (date.getFullYear() + "-" + (month.slice(-2)));
<input type="month" id="txtMonth" value="2018-11" />

A: You have to construct new Date and query your input, then do something like:

let date = new Date();
let month = `${date.getMonth() + 1}`.padStart(0, 2);
let year = date.getFullYear();
document.getElementById("month").value = `${year}-${month}`
<input id="month" type="month" value="2012-3-23">