text:
Q: Making a Text View bulleted in Xcode with Objective C I am trying to make a text view that is strictly bulleted.  So when you start typing it makes a bullet.  When you hit enter it will make a bullet. I found some code that will make a bulleted list but it only writes some text into the text view initially:
myTextView.text = @"\u2022";

And this is a text view not a text field (dont think that makes a difference) and it is for ios but does anybody know how you would do this?

A: This textView delegate is your friend:

*

*(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

So what happens is as people enter text, you get this delegate method, and you can see the text that WILL be added if you return YES. Now you cannot change the replacement text, but what you can do is ask the UITextView for all the current text, modify it as you wish, then return NO.


text:
Q: Is it possible to use the openlayers where we dont have internet connectivity? Since most of the example available in Internet is working based on Internet.
I would like to download and use. I don't want to use either CDN or openlayer.org in my code.

A: Is it possible to use openlayers without a CDN?
Yes. Like any library, you can download locally. This page has some download links to get the CSS and JS files: https://openlayers.org/download/
You download and unzip those into a folder that is accessible from your web server. Usually this is a scripts subfolder
Then you simply reference them as explained here:
https://www.w3schools.com/css/css_howto.asp
https://www.w3schools.com/tags/att_script_src.asp
(note these are very basic W3C references. You should really know this)
So if you downloaded those .js and .css files into a scripts subdirectory you do this:
<script src="scripts/theopenlayersscriptfile.js"></script>
<link rel="stylesheet" type="text/css" href="scripts/theopenlayerscssfile.css">

Edit:
After some experimenting and investigation, you mention that it is trying to access https://c.tile.openstreetmap.org/4/6/6.png
I googled and found this link
https://wiki.openstreetmap.org/wiki/OpenLayers_Local_Tiles_Example
Which says

With this example you can browse your tiles stored localy without any webserver. I use this to check my tiles I downloaded to use in Osmtracker. But you can also browse Tiles rendered by any other techniques.

The instructions at this link appear to explain exactly what you want to do - it has references to all of the files you are trying to use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MobileFirst: running a timer job on client side - best option I am developing an app in which I have to keep a timer job running in order to periodically( 2 min) make a call to adapter (backend) to fetch updated records.
What could be the best option present in MobileFirst?
Currently I use JavaScript Timeout function to call adapters periodically but am reluctant.
Remember I do not have need of using JSONStore so I am not sure about implementing that JSON synch feature which periodically synch JSONStore via adapter calls.

A: Why are you reluctant to use JavaScript to time your adapter requests?
I see no issue with implementing that approach and am not aware of any other recommended approaches to do so in Worklight/MobileFirst Platform.
This answer almost sounds like a comment, but given the nature of the question (no code...), there is nothing else to say.


text:
Q: Filter most read pages with Google Analytics API v4 I'm currently trying to obtain a list of the three most read articles on my site, using the Google Analytics Reporting API v4.
Currently, I have been able to request a list of all pages with the number of pageviews each one got in the past 30 days, and filter them by pageview.
But now I'm stuck (after browsing for answers for multiple hours) to filter so only pagepaths that include /artikels/ are shown, and limit the list to 3 results.
My current code:
function getReport($analytics) {

// Replace with your view ID, for example XXXX.
  $VIEW_ID = "XXXXXXX";

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("30daysAgo");
  $dateRange->setEndDate("today");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:pageviews");
  $sessions->setAlias("sessions");

  //Create the Dimensions object.
  $pagepath = new Google_Service_AnalyticsReporting_Dimension();
  $pagepath->setName("ga:pagePath");

  $ordering = new Google_Service_AnalyticsReporting_OrderBy();
  $ordering->setOrderType("VALUE");
  $ordering->setFieldName("ga:pageviews");
  $ordering->setSortOrder("DESCENDING");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges($dateRange);
  $request->setDimensions(array($pagepath));
  $request->setOrderBys($ordering);
  $request->setMetrics(array($sessions));

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );
}

Could anyone please help? There is a ton of information about v3, but can't seem to find enough information about v4.
Thank you!


text:
Q: actionbar dropdown not working when in fragment I have a navigation menu bar and a drop-down in the action bar.The UI looks like this:

For navigation to a different UI I'm using Fragments.When I click on top of the drop-down it should list out all the added items but instead im getting this exception:
    06-04 18:12:39.651  22359-22359/com.poliveira.apps.materialtests W/dalvikvm﹕ method Landroid/support/v7/internal/widget/ListViewCompat;.lookForSelectablePosition incorrectly overrides package-private method with same name in Landroid/widget/ListView;
06-04 18:12:39.671  22359-22359/com.poliveira.apps.materialtests D/AndroidRuntime﹕ Shutting down VM
06-04 18:12:39.671  22359-22359/com.poliveira.apps.materialtests W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40ce5930)
06-04 18:12:39.671  22359-22359/com.poliveira.apps.materialtests E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:529)
            at android.view.View.measure(View.java:15535)
            at android.support.v7.internal.widget.ListViewCompat.measureHeightOfChildrenCompat(ListViewCompat.java:294)
            at android.support.v7.widget.ListPopupWindow.buildDropDown(ListPopupWindow.java:1200)
            at android.support.v7.widget.ListPopupWindow.show(ListPopupWindow.java:584)
            at android.support.v7.internal.widget.SpinnerCompat.performClick(SpinnerCompat.java:603)
            at android.view.View$PerformClick.run(View.java:17372)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)

In MainActivity.java on-create I'm doing this:
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
actionBar=getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);

// Enabling Spinner dropdown navigation
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setDisplayShowHomeEnabled(true);

// Spinner title navigation data
navSpinner = new ArrayList<SpinnerNavItem>();
navSpinner.add(new SpinnerNavItem("Local", R.drawable.deviceonline));
navSpinner.add(new SpinnerNavItem("My Places", R.drawable.deviceonline));
navSpinner.add(new SpinnerNavItem("Checkins", R.drawable.deviceonline));
navSpinner.add(new SpinnerNavItem("Latitude", R.drawable.deviceonline));

// title drop down adapter
adapter = new TitleNavigationAdapter(getApplicationContext(), navSpinner);
// assigning the spinner navigation
actionBar.setListNavigationCallbacks(adapter, this);

I'm now having a Fragment class called "ReFragment.java". This the code I'm using:
   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView;
        Display d =getActivity().getWindowManager().getDefaultDisplay();
        // set display size
        ThumbSize.setScreenSize(d.getWidth(), d.getHeight());
        final int w = d.getWidth();
        final int h = d.getHeight();
        final double ar = w > h ? (double) w / (double) h : (double) h / (double) w;

        if (ar > 1.6) {
            Log.i(TAG, "AR = " + ar + ", using extended layout.");
            rootView= inflater.inflate(R.layout.rbox_extended, container, false);

        } else {
            Log.i(TAG, "AR = " + ar + ", normal layout.");
            rootView= inflater.inflate(R.layout.rbox, container, false);

        }
       if (mViewFlipper != null) {
            mRemoteView = mViewFlipper.getChildAt(0);
            mMousePadView = mViewFlipper.getChildAt(1);
            mGestureView = mViewFlipper.getChildAt(2);
            mViewFlipper.setDisplayedChild(0); // mRemoteView
        }
        rootView.findViewById(android.R.id.content);
        mRemoteController = new      RemoteController(getActivity().getApplicationContext());
        mConfigurationManager = ConfigurationManager.getInstance(getActivity());
        setupButtons(rootView);
        setUpSlider(ar,rootView,mMainactivitiycontext);

       return rootView;
}


text:
Q: extract_features sentence embedding BERT I'm using this code to get the embeddings of sentences that are in my dataset(I'm using my pretrained model).
`python extract_features.py \
  --input_file=/tmp/input.txt \
  --output_file=/tmp/output.jsonl \
  --vocab_file=$BERT_BASE_DIR/vocab.txt \
  --bert_config_file=$BERT_BASE_DIR/bert_config.json \
  --init_checkpoint=$BERT_BASE_DIR/bert_model.ckpt \
  --layers=-1,-2,-3,-4 \
  --max_seq_length=128 \
  --batch_size=32`

But, there is a problem: there is a way to get embeddings faster? Because for 2000 sentences it took 6 hours. My dataset contains 20000 sentences; 60 hours would be too long for Colab.
Thanks.

A: I resolved it.
I wrote all of sentences in input.txt and after that I used this code:
import jsonlines
df_emb=pd.DataFrame()
with jsonlines.open('/content/tmp/output.jsonl') as f:
    for line in f.iter():
        s=line['features'][0]['layers'][0]['values']
        df_tmp=pd.DataFrame(s).T
        df_emb=df_emb.append(df_tmp,ignore_index=True)

After that I saved the dataframe in csv file


text:
Q: MongoError: E11000 duplicate key error collection: orders.events index: _id_ dup key: { _id: ObjectId('608e6a80931b45001aa7f910') } So actually I,m getting this error.
I have 2 models: one for event and the other for orders where i"m first storing the event instance in database from one routes and on other routes when i find it and refer it in order and try to save it then following error is coming
MongoError: E11000 duplicate key error collection: orders.events index: _id_ dup key: { _id: ObjectId('608e6bde6ae9e80019f01dfe') }
[orders]     at Function.create (/app/node_modules/mongodb/lib/core/error.js:57:12)
[orders]     at toError (/app/node_modules/mongodb/lib/utils.js:123:22)
[orders]     at /app/node_modules/mongodb/lib/operations/common_functions.js:258:39
[orders]     at handler (/app/node_modules/mongodb/lib/core/sdam/topology.js:944:24)
[orders]     at /app/node_modules/mongodb/lib/cmap/connection_pool.js:350:13
[orders]     at handleOperationResult (/app/node_modules/mongodb/lib/core/sdam/server.js:558:5)
[orders]     at MessageStream.messageHandler (/app/node_modules/mongodb/lib/cmap/connection.js:277:5)
[orders]     at MessageStream.emit (node:events:369:20)
[orders]     at processIncomingData (/app/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
[orders]     at MessageStream._write (/app/node_modules/mongodb/lib/cmap/message_stream.js:42:5)
[orders]     at writeOrBuffer (node:internal/streams/writable:395:12)
[orders]     at MessageStream.Writable.write (node:internal/streams/writable:340:10)
[orders]     at Socket.ondata (node:internal/streams/readable:750:22)
[orders]     at Socket.emit (node:events:369:20)
[orders]     at addChunk (node:internal/streams/readable:313:12)
[orders]     at readableAddChunk (node:internal/streams/readable:288:9)
[orders] [ERROR] 09:09:09 MongoError: E11000 duplicate key error collection: orders.events index: _id_ dup key: { _id: ObjectId('608e6bde6ae9e80019f01dfe') }

My event and order schema are as follows:
event:
const eventSchema = new mongoose.Schema({
    date: {
        type: mongoose.Schema.Types.Date,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    creatorId: {
        type: String,
        required: true
    }
});

order:
const orderSchema = new mongoose.Schema({
    userId: {
        type: String,
        required: true
    },
    event: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Event'
    }
});

And my code is as below:
const event = await Event.findById(eventId);

if (!event) {
        throw new NotFoundError();
    }

const order = Order.build({
        userId: req.currentUser!.id,
        event
})

order.save();

I already have stored event document in database which i can refer by just finding it.

A: please try removing the database once and try adding new documents.
As you've referred to the event key from the order collection.


text:
Q: Как запускать программу при открытии файла Хочу чтобы запускалась программа для декодирования информации из файла с моим расширением.
Если имеет значение, то прогаю на C#, сжимаю с помощью LZW алгоритма.


text:
Q: How to click on an element which contains text with seleniumbase? I have the following very short code where I expect to be able to click on a button which contains the text Click Me:
from seleniumbase import BaseCase

class MyTestClass(BaseCase):
    def test_basics(self):
        url = "https://seleniumbase.io/demo_page"
        self.open(url)
        self.click_partial_link("Click Me")

But it does not work. I get an error NoSuchElementException.
Documentation is HERE.
So how to click on that button using SeleniumBase (https://seleniumbase.io/)?

A: The selector you're looking for is 'button:contains("Click Me")':
self.click('button:contains("Click Me")')

There are more examples of the SeleniumBase :contains() selector here: https://github.com/seleniumbase/SeleniumBase/blob/master/examples/test_contains_selector.py
It's not a standard CSS Selector, as it's specific to SeleniumBase, jQuery, and a few other places, but not everywhere.

A: try xpath : //*[text()='your text']


text:
Q: JSESSIONID is changing when coming back from another application(ex- salesforce) I am performing SP Initiated flow but it is considering it as a new request not picking the active session variables.
While checking the jsessionid, found that it is different for both the request(ie already logged in web app and the redirected url).
This is coming only with tomcat version 9+.


text:
Q: Python - Create Counter() from mapping, non-integer values Consider a basic counter initialized from a mapping:
dict_1 = {'a': 1, 'b': 2, 'c': 3}
count_1 = Counter(dict_1)
print count_1

>>> Counter({'c': 3, 'b': 2, 'a': 1})

Everything makes sense. But Counter also allows me to initialize from a dictionary that has non-integers as both keys and values. For example,
dict_2 = {'a': 'apple', 'b': 'banana', 'c': 'cheese'}
count_2 = Counter(dict_2)
print count_2

>>> Counter({'c': 'cheese', 'b': 'banana', 'a': 'apple'})

The code written above is Python 2.7, but I also tested it on Python 3.5 and got the same result. This seems to violate the most basic rule of the counter, where "elements are stored as dictionary keys and their counts are stored as dictionary values." Is counter supposed to allow values that aren't integers? Shouldn't it thrown an error or something? What explains this behavior?

A: There are no restrictions on the values of a counter object and this is clearly stated in the documentation:

The Counter class itself is a dictionary subclass with no restrictions
  on its keys and values. The values are intended to be numbers
  representing counts, but you could store anything in the value field.

[Emphasis mine]
The behavior of some of the Counter methods is also described in a general case e.g.:

The most_common() method requires only that the values be orderable.

>>> count_2.most_common()
[('c', 'cheese'), ('b', 'banana'), ('a', 'apple')]
>>> count_2.most_common(2)
[('c', 'cheese'), ('b', 'banana')]

So one could easily run into problems in Python 3 if you have unorderable types as values in the counter object:
>>> count_2['d'] = 2
>>> count_2
Counter({'c': 'cheese', 'a': 'apple', 'b': 'banana', 'd': 2})
>>> count_2.most_common()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\Python34\lib\collections\__init__.py", line 492, in most_common
    return sorted(self.items(), key=_itemgetter(1), reverse=True)
TypeError: unorderable types: str() < int()

Hence, you'll generally want to keep the values as the actual count of objects and use a vanilla dictionary when values are intended to be non numeric types or more strictly non integers.


text:
Q: Airflow - generate DAG from custom object I'm using airflow 1.10.3. I am trying to create a class that I can instantiate multiple times to generate DAGs for me. Here is a simplified example:
from airflow import DAG
from airflow.operators.python_operator import PythonOperator

class DagClass:

    def __init__(self, dag_id):
        self.dag_id = dag_id

    def test_function():
        print("test 1")

    def test_function2():
        print("test 2")

    def generate_dag(self):
        dag = DAG(self.dag_id)

        task1 = PythonOperator(
                  task_id="test",
                  python_callable=self.test_function,
                  provide_context=True,
                  dag=dag
                )

        task2 = PythonOperator(
                task_id="test2",
                python_callable=self.test_function2,
                provide_context=True,
                dag=dag
                )

        task1.set_downstream(task2)

        return dag

Then, I try to use that class to create a DAG in another file here:
from airflow import DAG
from dynamic_dag_test.dag_class import DagClass

dag_class = DagClass('test_dynamic_dag')

dag = dag_class.generate_dag()

globals()['test_dynamic_dag'] = dag

However if I do that, I won't get any errors, but my DAG will never show up in the web UI. BUT, if I instead get rid of the class and just directly import the function from another file, it works fine.
Does anyone know why this is and how I can get it to work with the class? Thanks!

A: I can confirm the comment of David Schuler as well with Airflow 1.10.1. We had to put the import statement (from airflow import DAG) at the top of the Python file.


text:
Q: MySQL procedure performance issue because of NAME_CONST I am executing the below procedure on two version of MySQL on the same data and I see significant different in performance.
When i run "show full processlist".
The only difference I see is that MySQL version 5.5.15 generates NAME_CONST and COLLATE for every SELECT like the below.
The character set on both the DBs are latin1.
DECLARE PROCEDURE Sample()
    BEGIN
    DECLARE A_Val int;
    DECLARE B_Val varchar(50);
DECLARE ApplCursor CURSOR FOR
    SELECT A, CONVERT(B, CHAR(50))
    FROM SampleTable;

OPEN ApplCursor;

Cursor_Loop: LOOP
    FETCH ApplCursor INTO A_Val, B_Val;

    SELECT B_Val, X_Val FROM SomeTableX;

END LOOP Cursor_Loop;

CLOSE ApplCursor;

END;
MySQL version = 5.5.15
For every select MySQL generates a NAME_CONST and COLLATE, as seen below
select NAME_CONST('B_Val',_latin1'A12345' COLLATE 'latin1_swedish_ci'), X_Val
from SomeTableX;
MySQL version = 5.7.16
The same SQL is generated with out NAME_CONST and COLLATE and execues much much faster
select B_Val, X_Val  from SomeTableX;
Can someone suggest as to how to disable the NAME_CONST and COLLATE generation.
Is there a way to tell MySQL to stop generating these extra NAME_CONST and COLLATE???

A: So SHOW CREATE PROCEDURE on both servers.  You will probably see that they were built with different CHARACTER SET and/or COLLATION.

A: Try this:
 DECLARE ApplCursor CURSOR FOR
       SELECT A, CONVERT(B, CHAR(50)) FROM SampleTable;

 OPEN ApplCursor;
 Cursor_Loop: LOOP

     FETCH ApplCursor INTO A_Val, B_Val;
     set ins_query=CONCAT(" SELECT ",B_Val,",",X_Val," FROM SomeTableX");
     set @ins_query=ins_query;
     PREPARE ins_query from @ins_query;
     EXECUTE ins_query;

END LOOP Cursor_Loop;
CLOSE ApplCursor;


text:
Q: Redux saga router. How to run specific route saga on every match? lets say i have such routes:
const routes = {
    '/:tab': switchTabGenerator,
    '/users/:id': anotherGenerator
}

Now if i navigate to /users/:id route /:tab will not be called. But i need this to change selected tab model.
How can i do this ?

A: takeLatest API provided by redux-saga can take an array of actions to listen.
takeLatest([action.route1, action.route2, action.route3], switchTabGenerator),

Pass all the route actions for which you want to trigger the saga.


text:
Q: How do I Create Custom ETCD Metrics for Prometheus I have set up a 3 node ETCD cluster and am using the default metrics via prometheus. I would like to create some more specific metrics for prometheus to scrape and report on.
I'm not sure if this is possible, the only answer I have seen is to use etcdctl to get info from ETCD and put it into a file that Prometheus scrapes.
Is there any way to add to or alter the existing metrics that ETCD exposes?

A: If I were you I would try following (in this order):

*

*Specify --metrics extensive flag to get additional metrics. Maybe what you need is already there! code for this flag

*Add your metric in etcd source code. If you know how to code, it should not be that hard. Example metric registration, and usage. If you plan to go this way, it would be cool, to create Pull Request with your code later on!

*If you can't code, then you may file feature request on the github and hope for someone to implement it for you.


text:
Q: How to use and access web sharing with Mac OS X Lion? I am new to Mac OS X, and I have a MacBook Pro. I am developing a web application with PHP and MySQL. I already installed XAMPP on my Mac. I discovered the option for hosting in System Preferences > Sharing > Web Sharing, but I don't know how to use it or how to tell my friend to view my web application remotely. Can someone help me?

A: Web Sharing opens port 80 (http) on your machine and points any incoming requests to ~/Sites. You'll want to put your PHP app there for it to work through Web Sharing. I'm not sure if there is any further configuration you have to do on the PHP/MySQL side since I don't know anything about either of those languages. That's probably a question for SuperUser.
As far as accessing it remotely, you'll need to open port 80 on your router and point it to your computer's internal IP address. Then you'll want to give your friend either your domain name or your current IP address from your ISP and have them type it in their web browser.

A: You just tick the box, an then anyone who doesn't get blocked by your firewall can view the site, either by domain name or IP address.
PHP is installed but disabled by default, you need to enable it i httpd.conf (not sure what the exact path is). Just search for PHP and uncomment anything relevant. Any change needs a restart of Apache (untick web sharing, wait, and tick it again).
MySQL isn't installed by default, but mysql.com has a pkg installer for it, and apple has already configured PHP to connect to it (via root@localhost with no password).


text:
Q: Подскажите. Возникает ошибка "Call to a member function getOneTask() on null при передаче данных по AJAX в symfony Всем доброго дня. Делаю первые шаги в symfonу .Прошу помощи по вопросу
Контроллер
 /**
     * @Route("/profile/task/update", name="user_task_update")
     * @param Request $request
     * @return RedirectResponse
     */
    public function update(Request $request)
    {
            $taskId = $request->get('Edit_id');

            $task = $this->taskRepository->getOneTask($taskId);    //здесь ошибка
            $task->setDraft();
            $this->taskRepository->setUpdateTask($task);

            return $this->redirectToRoute('user_task');
    }

JS
function edit_task(){
    $(document).on('click','#btn_edit',function()
    {
        var Edit_id = $(this).attr('data-id');
        $('#update').modal('show');
        $(document).on('click','#btn_update', function(){
            $.ajax(
                {
                    url: 'profile/task/update',
                    method: 'POST',
                    data: {Edit_id:Edit_id},
                })
        })
    })
}

В консоли Edit_id есть, то есть данные передаются. Но в контроллере возникает ошибка.


text:
Q: How do I update the timezone on a travelling Windows laptop? I want to automatically update the timezone on my Windows 7 laptop after traveling to a new locale.
Is there any method of doing this, perhaps by using an Internet location service?

A: Check out GeoSense for Windows which claims to be able to provide a semi-accurate geo-location device for your computer.  This will require some kind of internet connection (WiFi preferred) to be able to get your location.
I would hope that once Windows 7 has a vague idea of where you are, by using this service, then it will update your timezone accordingly.  But I cannot say for sure that it will.
Also see Windows Sensor and Location Platform
If you look in your Control Panel you will see a "Location and Other Sensors" panel.
About Location Sensors:

By using sensors, programs on your computer can customize information and services for you based on your computer's current location, surroundings, and more. For example, with a location sensor and your computer, you may be able to find a nearby restaurant, get directions to that restaurant, send the directions to a friend, and then follow the directions on a map as you travel to your destination.

A-HA!
Coding 4 Fun Timezone Changer - will require the GeoSense platform unless your have another sensor installed.

This is an extension for my MEF Utility Runner to change your system time zone based on your current location. Uses Windows 7 location feature.
It subscribes to location change events (new to Windows 7) to be aware of current location. When the location changes it determines the base UTC offset from a web service, then searches the system for time zones with that same offset.

A: We use TimeTraveller (http://www.godotandco.com) - it's a small utility that finds your location from your network connection and automatically updates the time zone in your laptop when travelling.


text:
Q: Alternative to RecyclerView for older Sdk I have created an App with RecyclerView but it's crash in the devices with 4.1 Android OS.
There is an alternative to RecyclerView or i can risolve the problem?
Thanks.
UPDATE
Activity
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Dashboard extends AppCompatActivity {

    private Activity activity;

    private SharedPreferences pref;
    SharedPreferences shared;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getPreferences(0);

        Fragment fragment;
        fragment = new DashboardFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_frame, fragment);
        ft.commit();

    }//fine OnCreate

}// FINE CLASS

Fragment
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.xxx.parser.JSONParser;
import com.xxx.utils.InternetConnection;
import com.xxx.utils.Keys;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class  FragmentCards extends android.app.Fragment {

    View v;
    private RecyclerView myrecyclerview;
    private List<Cards> lstCards;
    //

    private SharedPreferences pref;
    SharedPreferences shared;
    String unique_id;

    // Getting application context
    Context context = getActivity();

    //JSON
    private ListView listView;
    RecyclerViewAdapter recyclerAdapter;

    public FragmentCards() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.cards_fragment, container, false);
        myrecyclerview = (RecyclerView) v.findViewById(R.id.card_rv);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            recyclerAdapter = new RecyclerViewAdapter(getContext(),lstCards);
        }
        myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        myrecyclerview.setAdapter(recyclerAdapter);
        return v;
//        return null;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //per visualizzare codice
        pref = getActivity().getPreferences(0);
        shared = getActivity().getSharedPreferences("A", Context.MODE_PRIVATE);   // get the sharedpreference set named "A"
        unique_id= shared.getString("unique_id","");
//
//
        lstCards = new ArrayList<>();
//
        goToList();

    } // fine ON CREATE

    public void check_connectivity(){
        View view = getActivity().findViewById(android.R.id.content);
        // Initialize a new Snackbar
        Snackbar snackbar = Snackbar.make(view, "Connessione assente ... riprovo fra 5 secondi", Snackbar.LENGTH_INDEFINITE);
        // Change the Snackbar default background color
        View snackbarView = snackbar.getView();
        snackbarView.setBackgroundColor(Color.parseColor("#FF0000"));
        snackbar.show();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                View view = getActivity().findViewById(android.R.id.content);
                Snackbar snackbar = Snackbar.make(view, "Connessione in corso ...", Snackbar.LENGTH_SHORT);
                // Change the Snackbar default background color
                View snackbarView = snackbar.getView();
                snackbarView.setBackgroundColor(Color.parseColor("#F9A603"));
                snackbar.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        goToList();

                    }
                }, 1500);

            }
        }, 5000);
    }

    public void goToList() {
        if (InternetConnection.checkConnection(getActivity().getApplicationContext())) {

            new GetDataTask().execute();
            View view = getActivity().findViewById(android.R.id.content);
            Snackbar snackbar = Snackbar.make(view, "Connesso", Snackbar.LENGTH_SHORT);
            // Change the Snackbar default background color
            View snackbarView = snackbar.getView();
            snackbarView.setBackgroundColor(Color.parseColor("#258039"));
            snackbar.show();

        } else {
            check_connectivity();

        }
    }

    class GetDataTask extends AsyncTask<Void, Void, Void> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(getActivity());
            dialog.setTitle("Un attimo di pazienza...");
            dialog.setMessage("Carico le tue card");
            dialog.show();
        }

        @Nullable
        @Override
        protected Void doInBackground(Void... params) {

            JSONObject jsonObject = JSONParser.getDataById(unique_id);

            try {

                        JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);

                        int lenArray = array.length();
                        if(lenArray > 0) {
                            for(int jIndex = 0; jIndex < lenArray; jIndex++) {

                                JSONObject innerObject = array.getJSONObject(jIndex);
                                String desc_dist = innerObject.getString(Keys.KEY_DIST);
                                String numero_card = innerObject.getString(Keys.KEY_NUM_CARD);
                                String totpunti_card = innerObject.getString(Keys.KEY_TOT_PUNTI);
                                String id_cd = innerObject.getString(Keys.KEY_ID_CD);

                                /**
                                 * Adding name and phone concatenation in List...
                                 */
                                lstCards.add(new Cards( numero_card,desc_dist,totpunti_card,id_cd) );
                            } //fine FOR

                        }
                    }
                } else {

                }
            } catch (JSONException je) {
                Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
            }
            return null;
        } // FINE doBackground

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.dismiss();
            /**
             * Checking if List size if more than zero then
             * Update ListView
             */
            if(lstCards.size() > 0) {
                recyclerAdapter.notifyDataSetChanged();
            } else {
                View view = getActivity().findViewById(android.R.id.content);
                Snackbar snackbar = Snackbar.make(view, "No Data Found", Snackbar.LENGTH_SHORT);
            }
        }
    } // fine GetDataTask
}

RecyclerView
    import android.app.Activity;
    import android.app.Dialog;
    import android.app.Fragment;
    import android.content.Context;
    import android.support.annotation.NonNull;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.util.List;

    public class RecycleTransCardAdapter extends RecyclerView.Adapter<RecycleTransCardAdapter.MyViewHolder> {

        Context mContext;
        List<InfoCard> mData;
        Dialog myDialog;

        public RecycleTransCardAdapter(Context mContext, List<InfoCard> mData) {
            this.mContext = mContext;
            this.mData = mData;
        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View v;
            v = LayoutInflater.from(mContext).inflate(R.layout.item_trans_card, parent, false);
            final MyViewHolder vHolder = new MyViewHolder(v);

            return vHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

// some code
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        public static class MyViewHolder extends RecyclerView.ViewHolder {

// some code

            public MyViewHolder(View itemView) {
                super(itemView) ;
// some code

            }
        }

    }

The error is in Fragment at this line:
recyclerAdapter.notifyDataSetChanged();
I have this error only on old OS Android
Example: 4.1 version

A: recyclerview is backwards-compatible, assuming you include the support library for RecyclerView v7 in your application's build.gradle file:
compile "com.android.support:recyclerview-v7:21.0.0.+"

That one will work down as low as Android 2.1 (API level 7)
So you can use recyclerview in device running lower as on Android 2.1 (API level 7), hence the name v7
try adding above library and run app again if still crash happen
update the question with error log of app.

A: RecyclerView is part of Support Library which you can use it on older devices too. Try to use AndroidX package androidx.recyclerview.widget.RecyclerView
instead of support library.
implementation 'androidx.recyclerview:recyclerview:1.0.0'

For more detail about AndroidX explore this address:
https://developer.android.com/jetpack/androidx/


text:
Q: Is return after for loop same as continue in python? I know this might be a duplicate but I couldn't find it by searching. I was wondering if the following case is true:
def foo(A):
    for i in range(10):
        if A[i] < 10:
            return
        A[i] = A[i] - 10

what happens when the above return? I know it doesn't end the function because it after the for loop. Is it same as having continue?

A: It doesn't matter where you are within a function, return will exit it. The only exception to this is for nested functions (a def inside a def).
So what will happen is that when A[i] < 10 is True, it will exit.

A: No, return jumps out of the function foo(). If you replace it by a continue the execution will continue with the next value for i in the for loop.

A: No matter if its inside or outside of any loop type, return has the same functionality, ending and returning a value (if given) of the surrounding function. If there is a return statement within a loop, assuming the condition for it to be executed is true, the entire function will be ended.
With a continue statement, if the condition for its execution is true, the remainder of the iteration code is skipped and it moves to the next iteration of the loop, not exiting or ending the function.
And just in case you need this information too, the break statement is the intermediate between the functionality of the continue and return statements. If executed within any loop, it will end the entire loop and move on with the remainder of the code for the given function/operation.


text:
Q: How to get hostname from one container to another using docker compose? I have two docker containers. One backend, and the other db (postgres). They both are linked. How do I utilise the backend environment HOST variable in the golang docker container?
From my understanding, both containers have their own IP addresses. I cannot use 'localhost' in the golang container because postgres isn't on localhost, but in an isolated container.
version: "3.7"

services:

backend:
  image: golang:1.16
  build: ./
  working_dir: /app
  volumes:
    - ./backend/:/app
  environment:
    HOST: db
  command: go run main.go
  ports:
    - 8080:8080
  depends_on:
    - db

db:
  image: postgres
  restart: always
  environment:
    POSTGRES_USER: gorm
    POSTGRES_PASSWORD: gorm
    POSTGRES_DB: gorm
  ports:
    - 9920:9920

I've tried researching how to access this variable as well as check Docker tutorials/documentation, but haven't found a solution.

A: Docker compose does DNS resolution. You should be able to access your database by name.
Remove:
environment:
  HOST: db

Correct the postgres port to 5432:
db:
  ...
  ports:
    - 5432:5432

You must be able to connect like so:
db := pg.Connect(&pg.Options{
    Addr:     "db:5432",
    User:     "gorm",
    Database: "gorm",
    Password: "gorm",
})

As for environment variables, you can declare and access them like this:
backend:
  environment:
    POSTGRES_USER: gorm
    ...

os.Getenv("POSTGRES_USER")

A: Docker compose will create a network for your containers where they can communicate and reach each other.
You can make a simple change to your docker compose file by adding a name to your services which will make sure they get the same name each time.
version: "3.7"

services:

  backend:
    image: golang:1.16
    build: ./
    container_name: backend
    working_dir: /app
    volumes:
      - ./backend/:/app
    command: go run main.go
    ports:
      - "8080:8080"
    depends_on:
      - db

  db:
    image: postgres
    restart: always
    container_name: db
    environment:
      POSTGRES_USER: gorm
      POSTGRES_PASSWORD: gorm
      POSTGRES_DB: gorm
    ports:
      - "9920:5432"

The default port for Postgres is 5432, so I mapped it to your 9920. Then, you can access the db container from the backend container by specifying:
db:9920


text:
Q: MySQL: select multiple rows which has specific field value I'm having a users_conversations table contains a conversation_id and a user_id to tell which users are in the same conversation. I want to find any conversation_id which has user_id 76 and user_id 146 (which are ids 28, 31 and 32. These ids are not unknown to me. I just have both users ids) I tried
select * from users_conversations where user_id = 146 or user_id = 76 GROUP BY conversation_id

but I get
#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column
'forums.users_conversations.user_id' which is not functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by

How can I do that?

A: select * from users_conversations
where conversations_id in (select conversations_id from user_conversations where user_id=76)
AND conversations_id in (select conversations_id from user_conversations where user_id=146)

A: You can filter the table for these users, group by conversation_id and set the condition in the having clause:
select conversation_id
from users_conversations
where user_id in (76, 146)
group by conversation_id
having count(distinct user_id) = 2

You may omit distinct if there is no case of duplicate users for each conversation_id.

A: Did you mean instead:
select * from users_conversations where user_id = 146 or user_id = 76

Why do you want to use group?


text:
Q: How to disable a dropdown list item when dropdown list is bound dynamically Dropdown list is bound dynamically as:
<asp:DropDownList ID="ddlSource" class="ddl" runat="server" DataSourceID="FROM1" DataTextField="CompanyName" DataValueField="CompanyName">
                </asp:DropDownList>
                <asp:SqlDataSource ID="FROM1" runat="server" ConnectionString="<%$ ConnectionStrings:PIMSConnectionString2 %>" SelectCommand="SELECT [CompanyName] FROM Company ORDER BY [CompanyName]"></asp:SqlDataSource>

The CompanyName table has a value that is equal to "Select" and I want this value to be shown in the dropdown list but should be grayed out (disabled) so users can't select or set it.
Any idea how to do it in ASP.NET (not HTML)?

A: There is complete answer based on other questions from comments.
Make ListItems disabled and put them on the top of ddlSource based on condition CompanyName="Select" :
aspx :
<asp:DropDownList ID="ddlSource" class="ddl" runat="server" > </asp:DropDownList>
<asp:SqlDataSource ID="FROM1" runat="server" ConnectionString="<%$ ConnectionStrings:PIMSConnectionString2 %>" SelectCommand=""></asp:SqlDataSource>

code behind :
public void PopDDL()
{
    FORM1.SelectCommand = "SELECT CompanyName FROM Company ORDER BY CASE WHEN CompanyName='Select' THEN 0 ELSE 1 END;"
    ddlSource.DataSourceID = "FORM1";
    ddlSource.DataTextField = "CompanyName";
    ddlSource.DataValueField = "CompanyName";
    ddlSource.DataBind();
    foreach (ListItem itm in ddlSource.Items) {
        if (itm.Value == "Select") {
            itm.Attributes.Add("disabled", "disabled");
        }
    }
}

protected void Page_Load(object sender, System.EventArgs e)
{
    PopDDL();
}

A: Try this, but populating ddlSource will be from code behind (it's in vb.net, sorry) :
     Public Sub PopDDL()
        FORM1.SelectCommand = "SELECT CompanyName FROM Company ORDER BY CompanyName;"
        ddlSource.DataSourceID = "FORM1"
        ddlSource.DataTextField = "CompanyName"
        ddlSource.DataValueField = "CompanyName"
        ddlSource.DataBind()
        For Each itm As ListItem In ddlSource.Items
            If itm.Value = *your_condition* Then  'condition why this item must be disabled
                itm.Attributes.Add("disabled", "disabled")
            End If
        Next
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        PopDDL()
    End Sub

Item will be displayed but disabled (gray).
Update :
I use conversion tool (vb.net to c#) and I think this is c# code :
foreach (ListItem itm in ddlSource.Items) {
    if (itm.Value == *your_contidion*) { 'condition why this item must be disabled
        itm.Attributes.Add("disabled", "disabled");
    }
}

If You use itm.Enabled = False, item will not be showed.
UPDATE #2 (converted to c# code by online converter) :
aspx page :
    <asp:DropDownList ID="ddlSource" class="ddl" runat="server" > </asp:DropDownList>
   <asp:SqlDataSource ID="FROM1" runat="server" ConnectionString="<%$ ConnectionStrings:PIMSConnectionString2 %>" SelectCommand=""></asp:SqlDataSource>

code behind :
public void PopDDL()
{
    FORM1.SelectCommand = "SELECT CompanyName FROM Company ORDER BY CompanyName;";
    ddlSource.DataSourceID = "FORM1";
    ddlSource.DataTextField = "CompanyName";
    ddlSource.DataValueField = "CompanyName";
    ddlSource.DataBind();
    foreach (ListItem itm in ddlSource.Items) {
        if (itm.Value == *your_condition*) {
            itm.Attributes.Add("disabled", "disabled");
        }
    }
}

protected void Page_Load(object sender, System.EventArgs e)
{
    PopDDL();
}


text:
Q: Scroll based on URL fragment (Angular + NGRX + ElementRef) I have a main page with couple of sections.
Each section can be reached by typing its fragment name on the url (Ex. www.website.com/#introduction - will open the homepage and scroll to the introduction section automatically).
In order to do that, I need to fetch the section's container element and run .scrollIntoView() function on it.
What I have done:

*

*List item I have created a store (ngrx) which stores the ElementRef(s) of the sections.

*In each section component (located in HomeComponent - parent of the sections), I put a @ViewChild() pointing on the element.
@ViewChild('container', { static: true }) private container: ElementRef;

*Then on ngAfterViewInit() of this section component, I put
Store.dispatch() which stores my ElementRef on the store.

this.store.dispatch(new HomeActions.SetElementRef({
  linkName: COMP_LINK_NAME,
  elementRef: this.container
}));

Then, in HomeComponent, I listen to the sectionsRef store this.store.select('sectionRefs').
Filtered it if its undefined (as it is the default of the store = default statement is empty).
this.sectionRefs$ = this.store.select('sectionRefs').pipe(
    map((data: { sectionRefs: SectionReference[] }) => data.sectionRefs), // transform to a more convenient object
    tap((sectionRefs: SectionReference[]) => this.sectionRefs = sectionRefs), // Updates the sectionRefs array regardless the completion of it (filter below)
    filter((sectionRefs: SectionReference[]) => { // No emission until sectionRefs Element Refs are completed
      return sectionRefs.find((sectionRef: SectionReference) => {
        return (
          sectionRef.element === undefined ||
          sectionRef.element === null ||
          sectionRef.element.nativeElement.offsetHeight === 0 && sectionRef.element.nativeElement.offsetWidth === 0
        );
      }) === undefined // Means that no incompleted sectionRef was found
    }),
    distinctUntilChanged(
      (prev: SectionReference[], next: SectionReference[]) => JSON.stringify(prev) === JSON.stringify(next)
    ),
    first()
);

*HomeCompoent: And eventually I listened to the ActivatedRoute.fragment, to check which ElementRef is relevant for the scrolling.

*HomeComponent: Activate .scrollIntoView() on the relevant
ElementRef.

The issue is that I do it when the page is loaded so the ElementRef.nativeElement.scrollIntoView() is scrolling to incorrect place.
I checked to see the offsetHeight retrieved (ElementRef.nativeElement.offsetHeight) and it was also incorrect.
So In each section Component I wrapped the Store.dispatch() action with setTimeout()
setTimeout(() => {
  this.store.dispatch(new HomeActions.SetElementRef({
  linkName: COMP_LINK_NAME,
  elementRef: this.container
  }));
}, 150);

And it works!
But it is looking like a very bad practice to do this work around.
Is there any other solution?


text:
Q: Database is read-only error in Secondary Replica of Alwayson Groups I tried many things and analyzed lots of documents but I haven't found a solution yet.
I have three virtual machines in VmWare called (DC,SQLServer01,SQLServer02). All of SQL Servers are member of a domain.(DC) I installed failover cluster for SQLServer01 and SQLServer02. I did necessary configurations in SQLServer01. Then I installed SQL Server 2014 for both servers. Now, I created an alwaysOn group. SQLServer01 is a primary and other is secondary. When I cut the connection of SQLServer01, everything is fine (Secondary becomes primary). It is acceptable for other condition.
However, when all servers are online, I can not do any operation (insert,update,delete,alter ,etc) except read operations in my secondary replica. I see always "database is read only" error. In properties of Alwayson group, both primary and secondary replica have all connections and secondary readable is "YES".
I want to make CRUD operations even if all servers are online. (I mean, do everything also for secondary replica. )
So, do you have any suggestion or idea?
Thank your time and consideration.

A: The error occurs because writing to secondary replicas in sql server is not possible. Only primary replica can host read-write databases, and an availability group can only have one single primary replica. Secondary replicas can host read-only databases only. When both replicas are available, only one of the two can be the primary and therefore support read-write. When only a single replica is available, that replica becomes primary replica because there are no other replicas, and read-write operations against that replica is possible.
What you need to configure instead is replication.
In SQL Server, merge replication allows you to write at multiple nodes, with periodic synchronization that resolves conflicts and pushes changes to all replicas.
Peer to Peer replication is another solution. Application layer must not allow conflicts (update of same row at more than one node), but is much faster.


text:
Q: IE8 overflow:auto with max-height I have an element which may contain very big amounts of data, but I don't want it to ruin the page layout, so I set max-height: 100px and overflow:auto, hoping for scrollbars to appear when the content does not fit.
It all works fine in Firefox and IE7, but IE8 behaves as if overflow:hidden was present instead of overflow:auto.
I tried overflow:scroll, still does not help, IE8 simply truncates the content without showing scrollbars. Changing max-height declaration to height makes overflow work OK, it's the combination of max-height and overflow:auto that breaks things.
This is also logged as an official bug in the final, release version of IE8
Is there a workaround? For now I resorted to using height instead of max-height, but it leaves plenty of empty space in case there isn't much data.

A: This is a really nasty bug as it affects us heavily on Stack Overflow with
 code blocks, which have max-height:600 and width:auto.
It is logged as a bug in the final version of IE8 with no fix.
http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759
There is a really, really hacky CSS workaround:
http://my.opera.com/dbloom/blog/2009/03/11/css-hack-for-ie8-standards-mode
/*
SUPER nasty IE8 hack to deal with this bug
*/
pre
{
    max-height: none\9
}

and of course conditional CSS as others have mentioned, but I dislike that because it means you're serving up extra HTML cruft in every page request.

A: {
overflow:auto
}

Try div overflow:auto

A: I saw this logged as a fixed bug in RC1.  But I've found a variation that seems to cause a hard assert render failure.  Involves these two styles in a nested table.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Test</title>

            This is a cell in the outer table.

                    This is a cell in the inner table.

A: {max-height:200px, Overflow:auto}

Thanks to Srinivas Tamada, The above code did work for me.

A: To reproduce:
(This crashes the whole page.)

    <META content="IE=8" http-equiv="X-UA-Compatible"/>

    look:

                                X

(Whereas this works fine...)

    <META content="IE=8" http-equiv="X-UA-Compatible"/>

    look:

                                The quick brown fox

(And, madly, so does this. [No content in the div at all.])

    <META content="IE=8" http-equiv="X-UA-Compatible"/>

    look:

A: Similar situation, a pre element with maxHeight set by js to fit in allotted space, width 100%, overflow auto. If the content is shorter than maxHeight and also fits horizontally, we're good. If you resize the window so the content no longer fits horizontally, a horizontal scrollbar appears, but the height of element immediately jumps to the full maxHeight, regardless of the height of the content.
Tried various forms of the css hack mentioned by Jeff, but didn't find anything like it that wasn't a js bad-parameter error.
Best I could find was to pick your poison for ie8: Either drop the maxHeight limit, so the element can be any height (best for my case), or set height rather than maxHeight, so it's always that tall even if the content itself is much shorter. Very not ideal. Wacked behavior is gone in ie9.

A: Set max-height only and don't set the overflow. This way it will show scroll bar if content is more than max-height and shrinks if content is less than the max-height.

A: I found this :
https://perishablepress.com/maximum-and-minimum-height-and-width-in-internet-explorer/

This method has been verified in IE6 and should also work in IE5. Simply change the values to suit your needs (code commented with explanatory notes). In this example, we are setting the max-height at 333px 1 for IE and all standards-compliant browsers:
* html div#division {
     height: expression( this.scrollHeight > 332 ? "333px" : "auto" ); /* sets max-height for IE */
  }

and this works for me perfectly so I decided to share this.


text:
Q: Passing structs to functions I am having trouble understanding how to pass in a struct (by reference) to a function so that the struct's member functions can be populated. So far I have written:
bool data(struct *sampleData)
{

}

int main(int argc, char *argv[]) {

      struct sampleData {

        int N;
        int M;
        string sample_name;
        string speaker;
     };
         data(sampleData);

}

The error I get is:

C++ requires a type specifier for all declarations
bool data(const &testStruct)

I have tried some examples explained here: Simple way to pass temporary struct by value in C++?
Hope someone can Help me.

A: Passing structs to functions by reference: simply :)
#define maxn 1000

struct solotion
{
    int sol[maxn];
    int arry_h[maxn];
    int cat[maxn];
    int scor[maxn];

};

void inser(solotion &come){
    come.sol[0]=2;
}

void initial(solotion &come){
    for(int i=0;i<maxn;i++)
        come.sol[i]=0;
}

int main()
{
    solotion sol1;
    inser(sol1);
    solotion sol2;
    initial(sol2);
}

A: First, the signature of your data() function:
bool data(struct *sampleData)

cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:
bool data(struct sampleData *samples)

But in C++, you don't need to use struct at all actually. So this can simply become:
bool data(sampleData *samples)

Second, the sampleData struct is not known to data() at that point. So you should declare it before that:
struct sampleData {
    int N;
    int M;
    string sample_name;
    string speaker;
};

bool data(sampleData *samples)
{
    samples->N = 10;
    samples->M = 20;
    // etc.
}

And finally, you need to create a variable of type sampleData. For example, in your main() function:
int main(int argc, char *argv[]) {
    sampleData samples;
    data(&samples);
}

Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.
However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:
// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
    samples.N = 10;
    samples.M = 20;
    // etc.
}

int main(int argc, char *argv[]) {
    sampleData samples;

    // No need to pass a pointer here, since data() takes the
    // passed argument by reference.
    data(samples);
}

A: bool data(sampleData *data)
{
}

You need to tell the method which type of struct you are using. In this case, sampleData.
Note: In this case, you will need to define the struct prior to the method for it to be recognized.
Example:
struct sampleData
{
   int N;
   int M;
   // ...
};

bool data(struct *sampleData)
{

}

int main(int argc, char *argv[]) {

      sampleData sd;
      data(&sd);

}

Note 2: I'm a C guy. There may be a more c++ish way to do this.

A: It is possible to construct a struct inside the function arguments:
function({ .variable = PUT_DATA_HERE });


text:
Q: Kannada language: some characters not rendering properly(Displaying different character) in iOS Does iOS support Kannada language? I have browse around a couple of hours to find some tips but couldn't get through.
Here is the most annoying character that is displayed differently in iOS
ರ್. Due to some reason, its displaying properly here but in iOS app, its displaying like ɛ.


text:
Q: RegEx to allow anything except blanks or all spaces? I want to allow anything and everything..
except blank entries (NULL, zero characters, whatever you want to call it) and also blank spaces of any length should not be allowed.
This is essentially what I would do with a TRIM() function if I were coding in a language, but I have a need to do this with only regex.
Thank you!

A: Mr. Bob, I would like to know what language you are working in? I know if you are using C# there are plenty of great utilities for matching regular expressions or handling user input. However, without that knowledge the best I could offer is this:
[\S]+
This will match any non-whitespace character. Then you could stitch each match together. If you provide the language you are working with, I can give you a better answer.

A: As others have mentioned, to match all non-white space characters you would use:
[^\s]+

However, if you are looking for an equivalent to trim(), you can match white space before and after a string with:
^[ \t]+|[ \t]+$

and then replace it with an empty string.
If you would like to remove any white space character anywhere in the string, then you could use the below as your match:
[\s\n\r]+

A: How about this regex:
(?!^ +$)^.+$

This will make sure that:

*

*Input is not empty or null

*Input doesn't only have 1 or more spaces

*Spaces in between non-space characters are allowed

Live Demo: http://www.rubular.com/r/x2MU1fbAhE

A: Contrary to the other answers, I get the impression that you're looking to merely discard blank entries.
To that end, if the following regex matches, then the entry is invalid and should be discarded:
/^[\s\n\r]*$/


text:
Q: Postgres index timestamp with timezone column I'm running PostgreSQL 9.6, and I have a table named decks with an expiration column of type timestamp with time zone (for storing decks of cards where each card can expire independently).
I'd like to create a nightly cron job that finds all cards which expired at any point during the previous day—i.e. between 0:00 and 23:59 inclusive.
This seems to gives me the time range I want...
SELECT id
  FROM decks
 WHERE expiration >= (now()::date - 1)::timestamptz
   AND expiration < (now()::date)::timestamptz;

...but I'm wondering two things:

*

*What's the best way to index the expiration column for my scenario?

*Is there a better/cleaner way to specify the start and end times?

A: Question 1: For that query, a standard index is the best option. However, see below.
Question 2: Lots of options, here. A quick change to your query:
SELECT id
  FROM decks
WHERE expiration::date = (now()::date - 1);

... allows you to create a functional index on expiration::date which should be smaller, and a bit more efficient.
Personally, I'd go a bit further and use current_date instead of now():
SELECT id
  FROM decks
WHERE expiration::date = (current_date - 1);

As always, I recommend use of EXPLAIN and EXPLAIN ANALYZE when evaluating indexes.


text:
Q: Help identifying 3-pin open-collector photo-transistor-like component Can someone help identify the 3 pin photo device (not the entire module) on this "Icstation 5V Light Sensor Module"? (may be same as this one
It seems to act as a photo-transistor, but yet has 3 pins instead of 2. Its nets are labeled (on PCB module) as "GND", "OUT", and "VCC". OUT has a 10k pull-up to VCC --- so seems to be open-collector. But it's a 3-pin device, so is it some kind of photo-transistor + op-amp/comparator + NPN?
Does anyone have a Manufacturer + Manufacturer Part Number and/or can anyone point me to a datasheet?

A:
so is it some kind of photo-transistor + op-amp/comparator + NPN?

Yes, exactly.
According to this article by T.K. Hareendran, the sensor is all of these things, like the following:

I could not find a datasheet.
Often, mass-produced, economy items from China do not have datasheets and are unlikely to have one.  Fine for experimentation only.  If looking for production (or even guaranteed characteristics), will have to find a different device with a datasheet, or incorporate your own [regulator, transimpedance amplifier, and open-collector output transistor].

A: It appears to have evolved from some other similar product. There's also an 0103 that has different sensitivity inverted output. The datasheet below is Japanese so maybe it was an original Japanese product or it was just the Japanese-language datasheet of some other product.
Here is more information but the manufacturer is not shown that I can see. Thanks to @ocrdu for the lead.

P.S. the watermark is the blog site, not the manufacturer.

Edit:
Okay, it certainly appears to be a clone of a part made by Kodenshi of Kyoto, Japan. The datasheet for the very similar PIC0103SL is here.


text:
Q: Get Actor with Movie and Role played I'm new in Neo4j and I'm facing a little problem:
I'm using move/actors example database, and I'd like to have the actor with the movies that the actor has acted and the role (for each movie)
Actually I'm doing like this:
MATCH (a:Person)-[r:ACTED_IN]-(m:Movie)
WHERE ALL (role in r.roles WHERE NOT role IS NULL)
WITH DISTINCT(a), collect(r.roles) as roles, collect(m) as movies
RETURN a{.*, roles, movies} as result

I'm getting the movies and the roles separated, I'd like to include the role inside movies node, the structure that I want is:
{
name:"the actor's name"
movies:[
  {
     title:"the movie title",
     roles:[{role:"the role of the actor"}] /// there could be more than one role for the actor
  }
]

}```

Thanks

A: This is very straightforward (assuming actors have unique names):
MATCH (a:Person)-[r:ACTED_IN]->(m:Movie)
WHERE EXISTS(r.roles)
RETURN {name: a.name, movies: COLLECT({title: m.title, roles: r.roles})} AS result

If multiple actors might have the same name, you can use the aggregating function COLLECT to collect the data for each distinct Person node:
MATCH (a:Person)-[r:ACTED_IN]->(m:Movie)
WHERE EXISTS(r.roles)
WITH a, COLLECT({title: m.title, roles: r.roles}) AS movies
RETURN {name: a.name, movies: movies} AS result

A: You should try using map projections: https://neo4j.com/docs/cypher-manual/current/syntax/maps/
Something like this should work:
 MATCH (a:Person)-[r:ACTED_IN]-(m:Movie)
 WHERE ALL (role in r.roles WHERE NOT role IS NULL)
 WITH DISTINCT(a)
 RETURN { a.name, movies: collect( { m.title, roles: r.roles } ) }


text:
Q: Angular CLI 7: Sass failed to compile few moments ago I installed Angular Cli 7 and started clean project by
ng new my-app

I selected precompiler SASS for css, but when I'm editing file styles.sass then is not working, my styles.sass looks like this
h1 { color: red }

but ng serve show this message

Failed to compile.
./src/styles.sass
  (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/styles.sass)
  Module build failed (from ./node_modules/sass-loader/lib/loader.js):
h1 {    ^
        Invalid CSS after "h1 {": expected "}", was "{"
        in /Users/a/Documents/angular-projects/my-app/src/styles.sass
  (line 1, column 5)

how to fix it? and why that's happen?

A: *

*The CLI offers a command line flag to change your style when creating a new project with ng new my-app --style=scss

*As you can see, the extension is .scss, not .sass (at least for the syntax you're using, which is LESS)

*You are missing a semicolon h1 { color: red; }

*Remember to update your angular.json and component files accordingly if you don't reecreate a new project to resolve that

A: Could be because you upgraded your node.
Try installing node-sass
npm install node-sass
More details about node-sass on
https://www.npmjs.com/package/node-sass

A: dude ... I think your sintaxe maybe be wrong, look at https://sass-lang.com/guide
you shoulding use
h1
   color: red,
   align: center
   ...

A: Had the same problem, tried everything including reinstalling all the packages and node itself and none of them helped.

Finally the project was cloned to D:\somefolder instead of the Desktop where I was cloning before. Then it compiled without any issues and worked fine.


text:
Q: How to make scatter plot in spherical coordinates theta, phi, r (w/ or w/o plotly)? my question refers mostly to plotly, but plotting alternatives with other packages are welcome!
I have successfully made a light cone plot (kind of a wedge plot) in polar coordinates with this code:
import plotly.express as px
fig = px.scatter_polar(df_rdwz, r='z', theta='ra',
                       range_theta=[-6,6], range_r=[0.8,3.2], start_angle=0, direction="counterclockwise")
fig.show()

The result looks like this:

But I have as data also a phi angle for the depth. I would like to use it to make this plot 3d. Is there something like px.scatter_spherical or px.scatter_3d_spherical that would allow me this? Alternatively, I know I can use go.Scatter3d with cartesian coordinates (x,y,z) - can I plot the dots in cartesian coordinates and afterwards just make the AXIS of go.Scatter3d to be drawn spherically (theta, phi, r)?
Any other suggestions of how to make this plot in 3d with spherical axis labels are welcome! tnx


text:
Q: how to parse and identify header from JSON Data in WCf Service at server side I've done a project in ASP.NET with C#. Now I need to write a WCF service for this. On the server-side, how can I parse JSON data, and how can I identify the header, body, footer, etc.?

A: You would normally define a data contract which maps to your JSON structure. You'd then write a service contract which would accept the data contract type in your operation, and WCF does the parsing of the JSON data into the type.
I've written a small tool that helps you do that, you can find a link to it in the blog post at http://blogs.msdn.com/b/carlosfigueira/archive/2011/01/11/inferring-schemas-for-json.aspx.

A: An easy way to parse and/or generate JSON data is JSON.NET. It's a great library and much better than the built-in JSON serializer.
You can find it at http://json.codeplex.com/.


text:
Q: Protractor expected condition for element containing any text Is there a way how to check whether an element has any text in it? I already found textToBePresentInElement but this function checks for specified value and does not return a proper error if it fails.
I'm population the element via API and it's loaded bit later, so I want the browser to wait till any information appears in the element and then check for correct value.
Alternatively it would be also very helpful to manage to get a specific error message when EC fails:
browser.wait(EC.textToBePresentInElement(element(by.binding('myvar')), "expected"), 5000);

A: The third argument to browser.wait() is a custom error message:
browser.wait(EC.textToBePresentInElement(element(by.binding('myvar')), "expected"), 5000, "Text is not something I've expected");

See also:

*

*Custom message on wait timeout error

To wait for an element to contain any text, you can write a custom expected condition:
var EC = protractor.ExpectedConditions;

var anyTextToBePresentInElement = function(elementFinder) {
  var hasText = function() {
    return elementFinder.getText().then(function(actualText) {
      return actualText;
    });
  };
  return EC.and(EC.presenceOf(elementFinder), hasText);
};

And here is the usage:
browser.wait(anyTextToBePresentInElement(element(by.binding('myvar'))), 5000);

A: The previous code snippet works form but with a small update: return actualText; should be boolean. So the whole code will be:
var anyTextToBePresentInElement = function(elementFinder) {
  var EC = protractor.ExpectedConditions;
  var hasText = function() {
    return elementFinder.getText().then(function(actualText) {
      return !!actualText;
    });
  };
  return EC.and(EC.presenceOf(elementFinder), hasText);
};

Usage example:
var el = element(by.binding('myvar'));
browser.wait(anyTextToBePresentInElement(el, 5000, 'Element still has no text');

A: You can check this one
        export function titleType(textReference, expectedText)
        {
            textReference.then(function(name)
            {
                if (name == expectedText)
                {
                    expect(textReference).toContain(expectedText);
                    expect(name).toEqual(expectedText);
                }
                else
                {
                    throw new TypeError("Wrong " + expectedText + "  name " + name);
                }
            });
        }


text:
Q: Tile/Greographic Map in Kibana not working I am trying to create a geographical map of my data in Kibana 5.01, and it does not work. The fact is that I do not even have the geoip.field that is required in the menu.
I am sending data from IntelMQ, that is processed by logstash to get into elastic search. In the fields received I only have source_ip
What to do?

A: For passing geographical data to elasticsearch, there is a need to create a logstash filter to process the field referencing the IP address, and creating new field(s) with geographical data.
Based on this article How To Map User Location with GeoIP and ELK?
My new /etc/logstash/conf.d is:
filter {
  geoip {
    source => "source_ip"
    target => "geoip"
    database => "/etc/logstash/GeoLiteCity.dat"
    add_field => [ "[geoip][coordinates]", "%{[geoip][longitude]}" ]
    add_field => [ "[geoip][coordinates]", "%{[geoip][latitude]}"  ]
  }
  mutate {
    convert => [ "[geoip][coordinates]", "float"]
  }
}

After applying this log, there is a need to restart logstash and double check the logs at /var/log/logstash.
So the end result is:


text:
Q: array of vectors c++ add edit remove search I want to write a program for a bunch of users (not specific number of them) that each have contact details which contains username, phone number and email(all strings) , so I need three columns(const);
vector<string>info[3];

So my question is how can I add and remove rows(each user is one row) to this or search and edit them?
search[I want each row to have a number and search them by that number]

A: It would be better if you created class that is designed to manage single user info.
Nonetheless you can still store either vectorinfo[3] or objects of the class mentioned before in standard containers like:

*

*std::map or

*std::list or

*std::array or even

*std::vector
Which one of them?
It depends strictly on what you are going to do with those
   information. You can read about every of standard containers in
   documentation.

A: Assuming that the email is unique, use a std::map where each key is an email and value is a std::vector or array storing the username and phone number
Maps are typically implemented as binary search trees. So, time complexity of searching for an element (key) is Log(N)
#include <map>
#include <vector>
#include <string>
...

std::map<std::string /* email */, std::vector<std::string>> users;


text:
Q: How to use OR operator in filter data with **kwargs? I have this:
excl = dict()

kwargs['field1__isnull'] = False
kwargs['field2__isnull'] = False
kwargs['field3__isnull'] = False

items = MyModel.objects.filter(**kwargs).exclude(**excl)

And it generates this SQL:
SELECT ... FROM `mytable` WHERE (`field1` IS NULL  AND `field2` IS NULL AND `field2` IS NULL)

But I want this:
SELECT ... FROM `mytable` WHERE (`field1` IS NULL  AND `field2` IS NULL OR `field2` IS NULL)

How to do it (I must use kwargs dictionary, unless it can be combined with Q)?

A: Assuming danihp is correct with his question, I think you'd want something like this:
excl = dict()

f = Q(field1__isnull=False) | Q(field2__isnull=False) | Q(field3__isnull=False)

items = MyModel.objects.filter(f).exclude(**excl)


text:
Q: Either neither or none In the following sentence whether neither or none should be used?

On account of shortage of time none of them can finish their work.

On account of shortage of time neither of them can finish his work.

What is the difference in the above two sentences?

A: Neither means 'not one or the other of two', and a singular verb must follow.
None means 'not one of an unspecified number' and can be followed by a singular or plural verb. In either case, it may be desired to use a non-gender pronoun ('their') unless it is definitely known that all possible persons being considered are of the same gender.
If there are two people, neither can finish his or her work. If more than two, or if number is unknown, none can finish their work.


text:
Q: Using special characters when building a text string in google script I am trying to build a complex string to insert a new formulae on the fly in google script.  In VBA you use chr(34), is there a similar work around in google script?
Thanks

A: From this thread "Some common VBA functions translated to Google Apps Script" you will find here in Slide 6 that the function Chr(n) in VBA is translated in the javascript:
 function Chr(n) {
  return String.fromCharCode(n);
}

You can also find it in this Github.
For the sample code on how to use this function in AppsScript, check this link.
var map = Maps.newStaticMap();
 for (var i = 0; i < route.legs.length; i++) {
   var leg = route.legs[i];
   if (i == 0) {
     // Add a marker for the start location of the first leg only.
     map.setMarkerStyle(markerSize, markerColor, String.fromCharCode(markerLetterCode));
     map.addMarker(leg.start_location.lat, leg.start_location.lng);
     markerLetterCode++;
   }
   map.setMarkerStyle(markerSize, markerColor, String.fromCharCode(markerLetterCode));
   map.addMarker(leg.end_location.lat, leg.end_location.lng);
   markerLetterCode++;
 }


text:
Q: Anything else beside prepared statements before inserting user input into the database? From my understanding so far the risks of inserting user input into the database are sql injections, witch prepared statements take care of, and from what i have read the data should not be altered before saving it into the database with functions like htmlspecialchars() this should be always used when echoing user input from the database on the page.
So if i have a query like this for example:
$var1 = $_POST['userInput1'];
$var1 = $_POST['userInput2'];

$stmt = $db->prepare("INSERT INTO tableName (Column1, Column2) VALUES (?, ?)");
$stmt->bindParam(1, $var1);
$stmt->bindParam(2, $var2);
$stmt->execute();

Leaving validation aside is there anything else that needs to be done to this variables? Or from this point on, anything that the user enters in secure and can be stored?
And on a side note should i use named placeholders instead of positional placeholders or this is just a preferential thing?

A: You don't need to do anything to the variables before using them as parameters for a prepared statment.
In fact, you must not do any escape_string or quoting or anything, because the backslashes or whatever will be inserted literally into your database.
You may also like the simpler usage of PDO. You don't need to use bindParam(), you can just pass an array of values to execute():
$stmt = $db->prepare("INSERT INTO tableName (Column1, Column2) VALUES (?, ?)");
$stmt->execute([$var1, $var2]);

Regarding your question about named parameter placeholders:
It makes no difference, it's only a handy thing to help you write more readable code. You can still use the short form of passing an array of values:
$stmt = $db->prepare("INSERT INTO tableName (Column1, Column2) VALUES (:col1, :col2)");
$stmt->execute(['col1'=>$var1, 'col2'=>$var2]);

It can be especially handy if you already have a hash array with the right key/value pairs—like your $_POST array. It's tempting to do the following:
$stmt = $db->prepare("INSERT INTO tableName (Column1, Column2) VALUES (:userInput1, :userInput2)");
$stmt->execute($_POST);

But be careful about this, because you can't assume $_POST has only the fields you need. PDO will throw errors if you pass it an array with too many fields, or fields whose key names don't match your parameter placeholders. Anyone can therefore make a request that will cause your app to have errors.

A: As i see you take Two input from user and put it in database,
in my opinion your data must pass at least this Two proccess .

*

*Sanitize Data

*Validate Data

As you see i write sanitize before validate this most important why?
//If You Want The Output after Validation and Sanitize "Hello" as string and 5 length chars.
$userInput = "Hel<script></script>";

if you validate this first as string it will be valid string
and then sanitize it will return back
$santize_data = "Hel";

My Mean Is You Must first sanitize Your Data Then Check It for Validation
Php Have Great built-in Function for Sanitize with php
and for validation Validate with php
And You Have Some other tools like casts specific variable to specific type of data.
i hope this help !


text:
Q: I want to add only integer values in a given string <?php

$str = "1,2,3,4,b,6,c,7,8,f,9";

?>

I want to add only integer values in the above string... Can anyone suggest me an answer ? I tried explode function which will explode the character and return the integer values... But I failed to do so...

A: You need to split them up, filter anything that's not numeric out, then add them:
$chars = explode(',', $str);
$chars = array_filter($chars, 'is_numeric');
echo array_sum($chars); // 40


text:
Q: What are the pros and cons of Base64 file upload through JSON, as opposed to AJAX or jQuery upload? I was tasked to write image upload to remote server and save those images locally. It was quite easy to do it with Base64 transfer through JSON and storing with Node.js. However, is there a reason to not use this type of file upload, to use AJAX or other ways? (Other than the 30% bandwidth increase, which I know of. You can still include that in your answer in order for it to be full).

A: The idea of base64 encoding is to avoid binary data for protocols based on text. Outside this situation, it's I think always a bad idea.
Pros

*

*Avoidance of binary data for protocols based on text, and independance from external files.

*Avoidance of delimiter collision.

Cons

*

*Time and space increased complexity; for space it's 33–36% (33% by the encoding itself, up to 3% more by the inserted line breaks).

*API response payloads are larger/too large.

*User Experience is negatively impacted, unless one invoke some lazy loading.

By including all image data together in one API response, the app
must receive all data before drawing anything on screen. This means
users will see on-screen loading states for longer and the app will
appear sluggish as users wait.

This is however mitigated with Axios and some lazy loader such as react-lazyload or lazyload or so.

*

*CDN caching is harder. Contrary to image files, the Base64 strings inside an API response cannot be delivered via a CDN cache. The whole API response must be delivered by CDN. (cf., Don't use Base64 encoded images on mobile and Why "optimizing" your images with Base64 is almost always a bad idea)

*Image caching on the device is no longer possible.

*Content management becomes harder on server side. Most content management tools handle images as binary files. But then when managing in binary, there is the time overhead of encoding/decoding.

*No security gain and overhead in engineering to mitigate (Sanitizing, Input Validation, Escaping). Example of XSS attack: Preventing XSS with Base64 encoding: The False sense of web application security

The developers of that site might have opted to make the website appear more secure by having cryptic URLs and whatnot. However, that
doesn't mean this is security by obscurity.

If their website is vulnerable to SQL injection and they try to hide that by encoding the URLs, then it's security by obscurity. If their website is well secured against SQL injection; XSS; CSRF; etc., and they deiced to encode the URLs like that, then it's just plain stupidity.

*

*It does not help with text encoded images such as svg (Probably Don't Base64 SVG)

*Data URIs aren't supported on IE6 or IE7, nor on Opera before 7.2 (Which browsers support data URIs and since which version?)
References
https://en.wikipedia.org/wiki/Base64
https://en.wikipedia.org/wiki/Delimiter#Delimiter_collision
SO: What is base 64 encoding used for?
https://medium.com/snapp-mobile/dont-use-base64-encoded-images-on-mobile-13ddeac89d7c
https://css-tricks.com/probably-dont-base64-svg/
https://security.stackexchange.com/questions/46362/purpose-of-using-base64-encoded-urls
https://bunnycdn.com/blog/why-optimizing-your-images-with-base64-is-almost-always-a-bad-idea/
https://www.davidbcalhoun.com/2011/when-to-base64-encode-images-and-when-not-to/

A: Data Encoding
Every data Encoding and Decoding can be used duo various reasons, which came up with benefits and downsides.
like:

*

*Error-detection encodings : which can detect errors but increase data usage.

*Encryption encodings: turns data to cipher which intruder wont decipher.

There are a lot of Encoding Algorithms which Alter Data in
Which has some usefullness to do that.

but with
Base64 Encoding, its encode every 6-bit data into one character (8-bit) .
3 Byte to 4 Byte but it only includes alphanumeric(62 distinc) and 2 signs.

its benefits is it Dose not have special chars and signs

Base64 Purpose
it make possible to transfer Any Data with Channels Which Prohibits us to have:

*

*special chars like ' " / \  ...

*non-printable Ascii like \0 \n \r \t \a

*8-bit Ascii codes (ascii with 1 MSB )

binary files usually includes any data which if turns in ascii can be any 8-bit character.
in some protocols and application there are I/O Interfaces Which Does only accepts a handful of chars (alphanumeric with a few of signs).
duo to:

*

*prevent to code injection (ex: SQL injection or any prgramming-language-syntax-like characters ; )

*or just some character has already has a meaning in their protocol (ex: in URI QueryString character & has a meaning and cannot be in any QueryString Value)

*or maybe the input is not intended to accept non-alphanumerical values. (ex: it should accept only Human Names)

but with base64 encoding you can encode anything and transfer it with
any channel you want.

Example:

*

*you can encode an image or application and save it in DBMS with SQL

*you can include some binary data in URI

*you can send binary files in a protocol which has been designed to accepts only human chats as alphanumerical like IRC Channel

A: Base64 is a just a converting format that HTTP server cannot accept binary data in the contents except the HTTP Header type is binary or acceptable format defined by web-server.
As you might know, JSON can contain various formats and information; thus, you can contain such as
{
     IMG_FILENAME="HELLO",
     IMG_TYPE="IMG/JPEG",
     DATA="~~~BASE64 ENCODED IMAGE~~~~"
}

You can send JSON file through AJAX or other method. But, as I told you, HTTP server have various limitation because it should keep RFC2616 (https://www.rfc-editor.org/rfc/rfc2616).
In short, Sending Through JSON can contain various data.
AJAX is just a type of sending as other ways does.

A: I used same solution in one of my project.
The only concern is the request body size. If all your images are small, like a few M, then you should be fine.
My server is asp.net core, its maxAllowedContentLength value is 30000000, which is approximately 28.6MB. When the image size is over this, the request failed with error "request body too large".
I think node.js should have similar setting, make sure to adjust it to meet your need.
Please note that when the request size is too big, the possibility of request timeout increases accordingly due to the network traffic. This will be an issue especially for the requests from phones.

A: I think the use of base64 is valid.
The only doubt is the size of the request, but this can be circumvented if you divide this base64 in the frontend, if a 30mb file you could divide each request into 5mb and in the backend put the parts together, this is useful even to do the "keep downloading" "when you have a problem with the network and corrupt some part.
Hugs

A: Base64 converts your data to an ASCII representation of the binary data. It allows you to embed your data in text streams such as JSON for example. Base64 increases the size of the data transferred by 33%.
multipart/form-data is the standard way of transferring binary data in HTTP requests. It allows you to use specific encodings / content types for each part you'd like to transfer. In my opinion, you should stick to multipart uploads unless you have specific requirements or device/SDK capabilities.
Checkout these links
What is difference Between Base64 and Multipart?
Base64 image upload VS Binary image upload?


text:
Q: Formatting Excel file to display currency code and amount in the same cell using 'react-data-export' npm package I am using 'react-data-export' npm package for download excel data from the server. There is a requirement for me to put currency code and amount in the same cell. when we do calculations on the cell, it should work.
I have checked the same thing in the excel, Option is there,

But, I need to know how it can be done via coding using this npm package.
package link: https://www.npmjs.com/package/react-data-export


text:
Q: Finite Groups: $a \in G \implies a \in H$ Let $G$ be a finite group and let $H$ be a normal subgroup. Let $a$ be an element
of G and suppose that $\gcd(|a|,[G : H]) = 1$. Show that $a$ is in $H$.

A: Consider the factor group $G/H$. Since $a\in G$, $aH$ is an element of $G/H$.
Recalling and applying Lagrange's Theorem, we have that $|aH|$ must divide $|G/H|$.
Now, that $\gcd(a, |G:H|)=1$ implies what about the order of $aH$ in $G/H$?

A: Here's my attempt on this question, I believe it's correct. Are there some suggestions that the community could send my way?
The quotient $G/H$ is a group as $H$ is normal in $G$. $G$ and $H$ are finite groups so $[G:H]=|G/H$|. Let $[G:H]=m$ and say $|a|=n$. For $aH\in G/H$,  $\langle aH \rangle \leq G/H$. By definition the order of $a$ is the least integer $n$ such that $a^n = e$. Now $(aH)^n = a^nH = eH
= H$, thus $|\langle aH\rangle|=n$. Using Lagrange's Theorem $[G:H]/|\langle aH\rangle| = m/n$, but $gcd(n,m)=1$. This forces $|a|=1$ hence $a=e$ and $a\in H$. Moreover, $aH$ is the identity element in $G/H$.


text:
Q: Laravel Voyager server-side pagination links not showing I am developing with Laravel 8.4 ("laravel/framework": "^8.40") and Voyager 1.4 ("tcg/voyager": "^1.4").
I am facing an unusual bug with Laravel Voyager. When I am activating Server-Side pagination for any BREAD, the pagination-links section is breaking as below:

However, they are working when I am turning off Server-Side pagination as below:

I am not getting any error messages on the browser console or elsewhere.
The "<< Previous" and "Next >>" buttons are working as expected though, but there's no styling on them.
I have inspected the HTML of the specific part. The Links are present there, but are not being properly presented in browsers for some reason. The HTML of the section is as below:

                    « Previous

                    Next »

                    Showing
                    16
                    to
                    30
                    of
                    67
                    results

                            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd"></path>
                            </svg>

                                        1

                                        2

                                        3

                                        4

                                        5

                            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path>
                            </svg>

I need server-side pagination, because there will be a lot of data coming from the backend that is to be rendered. Only client-side DataTable is getting fairly slow when the number of rows getting more than 1K.
Otherwise, I will need to consider creating custom CRUDs for many of my models that need such data handling.

A: Simple, In your AppServiceProvider file insert both lines:
use Illuminate\Pagination\Paginator;

public function boot(){
    Paginator::useBootstrap();
}


text:
Q: ASP.NET MVC: Why can't I set ShowForEdit model metadata with an attribute? Why can't I set ShowForEdit model metadata with an attribute?
It seems that the only attribute provided to alter this is [ScaffoldColumn], which sets both ShowForEdit and ShowForDisplay, which is not what I want to do.  I want to be able to annotate the two separately from on my model.

A: What is the type of property you are applying it to?  If we use Reflector, we can discover that the ShowForEdit and ShowForDisplay properties are used in the following functions:
ShowForEdit: System.Web.Mvc.Html.DefaultEditorTemplates.ShouldShow(...)
ShowForDisplay: System.Web.Mvc.Html.DefaultDisplayTemplates.ShouldShow(...)
The definition of these methods is:
private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
{
  return (((metadata.ShowForEdit && (metadata.ModelType != typeof(EntityState))) && !metadata.IsComplexType) && !templateInfo.Visited(metadata));
}

private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
{
  return (((metadata.ShowForDisplay && (metadata.ModelType != typeof(EntityState))) && !metadata.IsComplexType) && !templateInfo.Visited(metadata));
}

Ignoring the obvious property check (metadata.ShowForX), you can see that it is checking whether the model is an instance of EntityState (probably isn't), and then a check for metadata.IsComplexType.
We can look at the IsComplexType property here:
public virtual bool IsComplexType
{
  get
  {
    return !TypeDescriptor.GetConverter(this.ModelType).CanConvertFrom(typeof(string));
  }
}

What that is saying is that it will return true if the model cannot be converted from a string, and in the ShouldShow() methods, it will show if it is not a complex type, i.e., the value CAN be converted from a string.
What you will need to do, is create a TypeConverter that can convert a string, to the model, e.g:
A model:
[TypeConverter(typeof(ItemConverter))]
public class Item
{
  #region Properties
  public string Text { get; set; }
  #endregion
}

And a converter:
public class ItemConverter : TypeConverter
{
  #region Methods
  public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  {
    if (sourceType == typeof(string))
      return true;

    return base.CanConvertFrom(context, sourceType);
  }

  public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
  {
    if (value.GetType() == typeof(string))
    {
      return new Item { Text = (string)value };
    }

    return base.ConvertFrom(context, culture, value);
  }
  #endregion
}

With that in place, try it again and see if that helps.

A: Because it is not supported out of the box.  AFAIK the reason is because the dataannotations attribute that support this functionality are in .net 4.0 and in order to make MVC 3.5 and 4.0 compatible they had to be excluded.
The easiest way to fix this is to have to implement your own Edit/Show attribute as demonstrated in this Question/Answer:
Showing Different fields in EditorForModel vs. DisplayForModel modes in MVC2