text:
Q: не сохраняет SharedPreferences в fragment Подскажите пожалуйста в чем моя ошибка. В Activity работает но в fragment не сохраняет в SharedPreferences
public class ftab3 extends Fragment implements View.OnClickListener{

    private SharedPreferences sharedPrefskyr;
    private TextView Startink2;
    private TextView Period21;
    private TextView Period11;
    private TextView Period31;
    private TextView Vilup1;

    public static final String myPrefskyr = "myprefskyr";
    public static final String namevilupkyr = "nameKey1kyr";
    public static final String namestartkyr = "nameKey2kyr";
    public static final String nameper1kyr = "nameKey3kur";
    public static final String nameper2kyr = "nameKey4kyr";
    public static final String nameper3kyr = "nameKey5kyr";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_ftab3, container, false);

        Startink2 = (TextView) view.findViewById(R.id.data1per1);
        long date1 = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat ("dd MMM yyyy");
        String dateV = sdf.format(date1);
        Startink2.setText(dateV);

        Period11 = (TextView) view.findViewById(R.id.data2per1);
        long date2 = System.currentTimeMillis()+ (8 * 86400000);
        SimpleDateFormat p = new SimpleDateFormat ("dd MMM yyyy");
        String dateX = p.format(date2);
        Period11.setText(dateX);

        Period21 = (TextView) view.findViewById(R.id.data3per1);
        long date3 = System.currentTimeMillis()+ (15 * 86400000);
        SimpleDateFormat N = new SimpleDateFormat ("dd MMM yyyy, HH:mm");
        String dateY = N.format(date3);
        Period21.setText(dateY);

        Period31 = (TextView) view.findViewById(R.id.data4per1);
        long date4 = System.currentTimeMillis()+ (19 * 86400000);
        SimpleDateFormat Nc = new SimpleDateFormat ("dd MMM yyyy, HH:mm");
        String dateJ = Nc.format(date4);
        Period31.setText(dateJ);

        Vilup1 = (TextView) view.findViewById(R.id.data5per1);
        long date6 = System.currentTimeMillis()+ (21 * 86400000);
        SimpleDateFormat rdf = new SimpleDateFormat ("dd MMM yyyy, HH:mm");
        String dateS = rdf.format(date6);
        Vilup1.setText(dateS);

        sharedPrefskyr = getActivity ().getSharedPreferences(myPrefskyr, Context.MODE_PRIVATE);
        if (sharedPrefskyr.contains(namevilupkyr)) {
                     Vilup1.setText(dateS);
        }
        if (sharedPrefskyr.contains(namestartkyr)) {
            Startink2.setText(dateV);
        }
        if (sharedPrefskyr.contains(nameper1kyr)) {
            Period11.setText(dateX);
        }
        if (sharedPrefskyr.contains(nameper2kyr)) {
            Period21.setText(dateY);
        }
        if (sharedPrefskyr.contains(nameper3kyr)) {
            Period31.setText(dateJ);
        }
        return view;
    }

     public void saveText() {

        String editTextValue = Vilup1.getText().toString();
        String editTextValue2 = Startink2.getText().toString();
        String editTextValue3 = Period11.getText().toString();
        String editTextValue4 = Period21.getText().toString();
        String editTextValue5 = Period31.getText().toString();

        SharedPreferences.Editor editor = sharedPrefskyr.edit();
        editor.putString(namevilupkyr, editTextValue);
        editor.putString(namestartkyr, editTextValue2);
        editor.putString(nameper1kyr, editTextValue3);
        editor.putString(nameper2kyr, editTextValue4);
        editor.putString(nameper3kyr, editTextValue5);

        editor.apply();
    }

      public void getText() {
        sharedPrefskyr = getActivity ().getSharedPreferences(myPrefskyr, Context.MODE_PRIVATE);
        if (sharedPrefskyr.contains(namevilupkyr)) {
            Vilup1.setText(sharedPrefskyr.getString(namevilupkyr, ""));
        }
        if (sharedPrefskyr.contains(namestartkyr)) {
            Startink2.setText(sharedPrefskyr.getString(namestartkyr, ""));
        }
        if (sharedPrefskyr.contains(nameper1kyr)) {
            Period11.setText(sharedPrefskyr.getString(nameper1kyr, ""));
        }
        if (sharedPrefskyr.contains(nameper2kyr)) {
            Period21.setText(sharedPrefskyr.getString(nameper2kyr, ""));
        }
        if (sharedPrefskyr.contains(nameper3kyr)) {
            Period31.setText(sharedPrefskyr.getString(nameper3kyr, ""));
        }

    }

       @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.saveBtn22:
                saveText();
             Toast.makeText(getActivity (), "Сохранить", Toast.LENGTH_LONG).show();
                break;

            case R.id.getBtn22:
                 Toast.makeText(getActivity (), "Получить", Toast.LENGTH_LONG).show();
                getText();
                break;

        }

    }

A: Может кому-то покажется смешным моя реализация, но работу с SharedPreferences я у себя реализовал так:

*

*static int, static boolean и т.д.

*при создании Activity делаю чтение настроек:
     mSettings = context.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);

*читаю настройки
 _koef_alt_2_main = _read_new_sett_boolean("_koef_alt_2_main", false);
 _volume_main_tank = _read_new_sett_float("_volume_main_tank", 55);
 _type_fuel_alt = _read_new_sett_string("_type_fuel_alt", "Пропан");

*Делаю дополнительные функции чтения / записи данных
 public static String _read_new_sett_string(String _label, String _def) {
 if (mSettings.contains(_label)) {
     return mSettings.getString(_label, _def);
 } else {
     return _def;
 }
 }

 public static float _read_new_sett_float(String _label, float _def) {
 if (mSettings.contains(_label)) {
     return mSettings.getFloat(_label, _def);
 } else {
     return _def;
 }
 }
 public static Boolean _read_new_sett_boolean(String _label, Boolean _def) {
 if (mSettings.contains(_label)) {
     return mSettings.getBoolean(_label, _def);
 } else {
     return _def;
 }
 }

 public static void _save_new_sett_string(String _label, String _input) {
    SharedPreferences.Editor editor = mSettings.edit();
    editor.putString(_label, _input);
    editor.apply();
 }
 public static void _save_new_sett_float(String _label, float _input) {
    SharedPreferences.Editor editor = mSettings.edit();
    editor.putFloat(_label, _input);
    editor.apply();
 }
 public static void _save_new_sett_boolean(String _label, Boolean _input) {
    SharedPreferences.Editor editor = mSettings.edit();
    editor.putBoolean(_label, _input);
    editor.apply();
 }

*В программе работаю с переменными, в любом месте. Если мне нужно изменить переменную и записать её, вызываю функцию
_save_new_sett_boolean("restart_on_lost", _restart_on_lost.isChecked());

Все примеры это вырезки из кода, между собой не связаны переменными

A: Создай отдельный Java Class и пропиши анологично этого:
import android.content.Context;
import android.content.SharedPreferences;

import static android.content.Context.MODE_PRIVATE;

    public class SharedPref {
        public static final String APP_PREFERENCES = "mysettings";
        public static final String NIGHT_MODE = "NightMode";
        public static final String APP_PREFERENCES_COUNTER = "counter";
        SharedPreferences mySharedPref ;
        public SharedPref(Context context) {
            mySharedPref = context.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);
        }
        // this method will save the nightMode State : True or False
        public void setNightModeState(Boolean value) {
            SharedPreferences.Editor editor = mySharedPref.edit();
            editor.putBoolean(NIGHT_MODE,value);
            editor.apply();
        }
        // this method will load the Night Mode State
        public Boolean loadNightModeState (){
            return mySharedPref.getBoolean(NIGHT_MODE,false);
        }

        public void setLanguageState(String lang){
            SharedPreferences.Editor editor = mySharedPref.edit();
            editor.putString("My_Lang", lang);
            editor.apply();
        }
        // Вызов метода с помошью SharedPreferences

        public String getString(String my_lang, String s) {
            return mySharedPref.getString("My_Lang","");
        }
    }

И потом начинай присваевать куда тебе надо.


text:
Q: Other solutions, instead of .htaccess for NGINX I'm working on a larger Web based Project, that probably will have to handle a couple of hundred requests per minute in a later stage (or more).
I never worked with NGINX, but reading the comparisions with apache, it seems that I probably should go the NGINX route. Reading about it, I always see that '.htaccess' files are a lazy solution. Now, I would like to avoid relying on .htaccess files, but my question is how?
What I mean is - if .htaccess are considered the lazy, hacky solution, what exactly is the clean solution for this issues:

*

*Redirecting all specific URL's (except for CSS / Images, and this stuff), to a single php file (by the way, does that have a performance impact, if a single file like index.php handles the URL's and includes the required templates? Should I avoid that, and split into dozens of files?)

*Reading PHP Tags inside of CSS Files ("AddHandler application/x-httpd-php .css ...")

*Another layer of login (.htaccess authentication, with that little popup window)
This are basically the three things I'm using .htaccess for. Especially the first one, basically makes the whole Application work at all.
But for this Project, I'm really trying to stay clean, and up-to-date, solution wise. What are my possibilities? Where could I increase my performance? And how can I solve the 3 mentioned problems, whitout using a .htaccess, to develop on NGINX?
Thank you very much for your time and effort.

A: In order to get the most out of nginx, you have to understand that it is not a web server (like Apache), but a proxy. In simple terms, it acts like a giant rule engine to pass stuff along to other applications based on pattern matching on requests.
So to run PHP with nginx, you need a separate server (or process) that runs PHP. This can be Apache, but PHP includes a FastCGI Process Manager (FPM).
Here is basic boilerplate to get you going:
server {
   listen 80;
   server_name www.example.com example.com;
   access_log /var/www/www.example.com/logs/access.log;
   error_log /var/www/www.example.com/logs/error.log;
   root /var/www/www.example.com/public_html;

   location / {
       index  index.html index.htm index.php;
       auth_basic            "Username Required";
       auth_basic_user_file  /etc/nginx/htpasswd;
   }

   location ~ (\.php|\.css)$ {
       try_files $uri =404;

       include /etc/nginx/fastcgi_params;
       fastcgi_index index.php;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_pass php;
   }
}

A: Question is offtopic, but to help you:

*

*http://nginx.org/en/docs/http/converting_rewrite_rules.html

*http://www.anilcetin.com/convert-apache-htaccess-to-nginx/

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the best way to access properties from the same class, via accessors or directly? This is something I'm not much consistent about and always curious about what other people do.
How do you access internal properties (private or public)?
For example you've got this property :
Private _Name As String

Public Property Name() As String
    Get
        Return _Name
    End Get
    Set(ByVal value As String)
        _Name = value
    End Set
End Property

In the same class within another function which one do you prefer? and why?
_Name = "Johnny"

or
Name = "Johnny"

Ignore the fact that I used Name instead of Me.Name.

A: I would say
Name = "Johnny"

The reason is that I might have some validation (or trigger, or lazy initialization, or...), or might later decide to insert some validation, when assigning Name and I want to be sure to trigger that code.

A: Personally I prefer to use the property where possible. This means you still get the validation, and you can easily put breakpoints on the property access. This doesn't work where you're trying to make a change to two properties which validate against each other - for instance, a "min and max" pair, where each has a validation constraint such that min <= max at all times. You might have (C#):
public void SetMinMax(int min, int max)
{
    if (max > min)
    {
        throw new ArgumentOutOfRangeException("max";
    }
    // We're okay now - no need to validate, so go straight to fields
    this.min = min;
    this.max = max;
}

At some point in the future, I'd like to see C# gain the ability to declare the backing field within the property, such that it's private to just the property:
public string Name
{
    string name;

    get { return name; }
    set
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }
        name = value;
    }
}

Outside the property, you wouldn't be able to get at name at all, only Name. We already have this for automatically implemented properties, but they can't contain any logic.

A: I prefer:
Name = "Johny"

For me, reason is quite simple, if something bad happens with _Name, you can always put some output in getter/setter and find out what is causing the trouble.

A: This is quite interesting, I think most of the people doing what I do
Me.Name = "Johnny"

or
Name = "Johnny"

However most of the projects that I've seen using
_Name = "Jonny"

style. Which I though was a bad idea, and thanks to answers you confirmed it. Even most of the auto-code generated code by several tools uses direct access.
Is there any particular performance hit? Or is compiler optimises it when there is no extra code in set or get.

A: Use property (Name). I believe a property should be sole "owner" of underlying field (_name).
Advantages of encapsulating field under a property:

*

*Readability: Only one region of code where _name is changed or processed before returned.

*Easy to set break-point, debug etc.

*DRY: No code repeated as far as validation and processing is concerned.

*Change resilience: Changing validation and processing will not affect code using
property.


text:
Q: How to use mock $httpBackend to test error branch I am following the AngularJS documentation from here
The problem is that the documentation describes only the "success/happy" branch of the code, and there is no example of how to test the "failure" branch.
What I want to do, is to set the precondition for triggering the $scope.status = 'ERROR!' code.
Here is a minimal example.
// controller
function MyController($scope, $http) {

  this.saveMessage = function(message) {
    $scope.status = 'Saving...';
    $http.post('/add-msg.py', message).success(function(response) {
      $scope.status = '';
    }).error(function() {
      $scope.status = 'ERROR!';
    });
  };
}

// testing controller
var $httpBackend;

beforeEach(inject(function($injector) {
  $httpBackend = $injector.get('$httpBackend');
}));

it('should send msg to server', function() {

  $httpBackend.expectPOST('/add-msg.py', 'message content').respond(500, '');

  var controller = scope.$new(MyController);
  $httpBackend.flush();
  controller.saveMessage('message content');
  $httpBackend.flush();

  // Here is the question: How to set $httpBackend.expectPOST to trigger
  // this condition.
  expect(scope.status).toBe('ERROR!');
});

});

A: You are checking a property of the controller while you are setting a property of the scope.
If you want to test for controller.status in your expect call, you should set this.status inside your controller instead of $scope.status.
On the other hand, if you set $scope.status in your controller, then you should use scope.status instead of controller.status in your expect call.

UPDATE: I created a working version for you on Plunker:
http://plnkr.co/edit/aaQ7JQV9WlXhou0PYHTn?p=preview
All tests are passing now...


text: Q: Hologram Breakdown Why does a hologram when divided still maintain the total image of the subject? And one would imagine at the atomic scale when the hologram is separated to such a small set of atoms the total image would no longer be present in that section. What is at work here and when would the total image stop being present?


text:
Q: How is the resistor value for boost conversion calculated? I'm looking at MCP1640 and in Section 5.2, an equation for calculating RTOP is presented. However, the two examples underneath have RBOT = 309kOhm. How did that come about? Is 309kOhm some standard value? Without fixing a value for RBOT, one could only derive a ratio between RBOT and RTOP.
The second circuit on page 2 uses RBOT = 562kOhm though. Is RBOT meant to be arbitrary?
Thanks

A: You are free to choose \$R_\mathrm{BOT}\$ such that
(a) you can find close-enough standard resistor values for both \$R_\mathrm{BOT}\$  and \$R_\mathrm{TOP}\$, and
(b) \$R_\mathrm{BOT}\$ and \$R_\mathrm{TOP}\$ are the right order of magnitude.
About the order of magnitude, cf. the explanation on section 5.2:

There are some potential issues with higher value resistors. For small surface mount resistors, environment contamination can create leakage paths that significantly change the resistor divider ratio and modify the output voltage tolerance.
Smaller feedback resistor values will increase the current drained from the battery by a few μA, but will result in good regulation over the entire temperature range and environment conditions.

So if you pick 1 K or 10 K resistors instead of 100 K resistors you will have a bit more current drain* but it will otherwise work fine. If you pick 1 M resistors or more, you may have issues with noise and stability.
They mention contaminants: moisture and dirt on the PCB can create parasitic resistors of some 10s or 100s of MOhms. You want your divider network to be lower than that so that it "wins" over these parasitic current paths.
* estimate it as \$I_\mathrm{drain}=\frac{V_\mathrm{out}}{R_\mathrm{BOT}+R_\mathrm{TOP}}\$

A: The value of the resistors is arbitrary within some limits, and you're right: their ratio is the important factor as that determines the output voltage.
Section 5.2 in the data sheet PDF tells you the points to observe:

There are some potential issues with higher value resistors. For small
  surface mount resistors, environment contamination can create leakage
  paths that significantly change the resistor divider ratio and modify
  the output voltage tolerance.
Smaller feedback resistor values will increase the current drained
  from the battery by a few μA, but will result in good regulation over
  the entire temperature range and environment conditions. The feedback
  input leakage current can also impact the divider and change the
  output voltage tolerance.

Using values within the range the data sheet shows as examples is usually the safe way to go.
309kohms is an E96 value, you may use a different value from the more common E24 series if that's a problem for you.


text:
Q: Best practice method to find execution time in Zend Framework I'm interested in the best/standard way to find the execution time of my Zend Framework app. Currently I'm starting the timer on the public/index.php then registering it in Zend_Registry, for a later call, which the layout then uses to calculate the total time.
Is there a better way to do this? I know this isn't even entirely accurate, as there is still (or at least, can be) some execution in the postDispatch() which will be ran after the view is rendered.

A: I ended up adding
$appStartTime = microtime();

before the bootstrapper got intsantiated, and put
global $appStartTime;
@list( $startMilli, $startSeconds, $endMilli, $endSeconds) = explode(' ',$appStartTime . ' ' . microtime());
$generateTime = ($endSeconds+$endMilli)-($startSeconds+$startMilli);
printf( '. Generated in %.3fs', $generateTime);
if ($generateTime > 1) // one second
{
    Zend_Registry::get( 'logger' )->warn( 'Long page load time of ' . $generateTime . ' on ' . Zend_Controller_Front::getInstance()->getRequest()->getRequestUri() );
}

at the end of my layout.phtml as the last thing before the closing body tag

A: I myself use webgrind and xdebug profiling. This gives info not only about total execution time, but also e.g. how many times a given method was executed, what was the time of this execution, etc.

A: You might want to look into enabling a real code profiler like XHProf.


text:
Q: using multiple conditions in sql loader I was trying to load records from a file to an oracle table based on conditions. Since OR operator and WHEN IN statements do not work in sql loader, I tried multiple insert to a table. However, only the records that match the first condition were loaded in the table and the records that matched the second condition were not loaded. My control file looks like below:
Options (BINDSIZE = 7340032)
Load Data
APPEND
INTO TABLE TEMP_GLOBAL_ONE_FEE_REBATE WHEN ACT_TYPE = 'SR'
FIELDS TERMINATED BY '|' TRAILING NULLCOLS
(
        RPT_YEAR,
        RPT_MONTH,
        ........
        ........
 )

INTO TABLE TEMP_GLOBAL_ONE_FEE_REBATE WHEN ACT_TYPE = 'SL'
FIELDS TERMINATED BY '|' TRAILING NULLCOLS
(
        RPT_YEAR,
        RPT_MONTH,
        ........
        ........
 )

** As mentioned, only those records with act_type = 'SR' were loaded and those records with act_type = 'SL' were not loaded.
Any idea how to go on this? Thank you.

A: Your problem is that the first INTO command reads the file from beginning to end, and then the second INTO command picks up where the first one finished - which is the end of the file in your case.
To achieve what you are trying to do, you're gonna have to use two seperate sql loader commands. See this post on AskTom for reference -
https://asktom.oracle.com/pls/apex/f?p=100:11:::YES:RP:P11_QUESTION_ID:3181887000346205200
A more elegant solution would be reading the data from the file using a pl/sql procedure and UTL_FILE package, but this is only worth the trouble if the import is something that happens a lot, and not a one time thing.

A: You should use POSITION(1) in the first column of each field list:

To force record scanning to start in a specific location, you use the POSITION parameter.

Control file
Options (BINDSIZE = 7340032)
Load Data
APPEND
INTO TABLE TEMP_GLOBAL_ONE_FEE_REBATE WHEN ACT_TYPE = 'SR'
FIELDS TERMINATED BY '|' TRAILING NULLCOLS
(
        RPT_YEAR POSITION(1),
        RPT_MONTH,
        ........
        ........
)

INTO TABLE TEMP_GLOBAL_ONE_FEE_REBATE WHEN ACT_TYPE = 'SL'
FIELDS TERMINATED BY '|' TRAILING NULLCOLS
(
        RPT_YEAR POSITION(1),
        RPT_MONTH,
        ........
        ........
)

Sample data
2015|01|SL
2015|02|SL
2015|03|SL
2015|03|SR
2015|04|SR
2015|04|XX

This will load 2 rows with 'SR', 3 rows with 'SL', and discard one row.
References

*

*SQL*Loader with multiple WHENs is rejecting all rows, the Ask Tom queston mentioned in the accepted answer

*Distinguishing Different Input Record Formats in SQL*Loader Control File

*Loading Data into Multiple Tables in SQL*Loader Control File Reference


text:
Q: window.phonegap is undefined after successful phonegap build This is my first time building something with phonegap, angularjs, ionic, yeoman and grunt. The app works great for web, but I'm trying to build it through phonegap. The steps I take are:
$sudo grunt build

This builds everything fine, and the response is:
Done, without errors.

Execution Time (2014-09-14 19:07:13 UTC)
concurrent:dist    3m 31.6s  _________________________________ 35%
autoprefixer:dist   2m 9.1s  ____________________ 22%
concat:generated   2m 26.4s  _______________________ 24%
ngmin:dist         1m 24.3s  _____________ 14%
cdnify:dist             14s  ___ 2%
uglify:generated       8.8s  __ 1%
Total 10m 0.4s

Next, I run:
$ phonegap remote build android

[phonegap] compressing the app...
[phonegap] uploading the app...
[phonegap] building the app...
[phonegap] Android build complete

From there i download the .apk and open it on my android phone.
The problem is that phonegap is not initialized somewhere, and the window.phonegapis undefined.
Here is the code for watching for window.phonegap in app.js:
var PhoneGapInit = function () {
  this.boot = function () {
    angular.bootstrap(document, ['mobileAppApp']);
  };
  if (window.phonegap !== undefined) {
    document.addEventListener('deviceready', function() {
     this.boot();
    });
  } else {
    alert('PhoneGap not found, booting Angular manually');
    this.boot();
  }
};

angular.element(document).ready(function() {
  new PhoneGapInit();
});

In index.html, I have it initialized so far as I know with
<!-- build:js(.) scripts/vendor.js -->
<script src="phonegap.js"></script>

What vital piece of info am I missing? I can include the corresponding config.xml and Gruntfile.js if asked. Thanks in advance!

A: I ran into a similar issue today. There were a two issues in my project.
1) First of all: I had to move the phonegap.js outside the <!-- build:js(.) scripts/vendor.js --> block, otherwise the grunt build task would concatenate all those files and replace it with a reference to vendor.js. But the phonegap.js will only be added during the Phonegap build process, but then there won't be any references in your HTML.
2) You are probably building against a recent (> 3.0) version of phonegap. The scope was renamed to cordova. Change your code to
if (window.cordova !== undefined) {
document.addEventListener('deviceready', function() {
 this.boot();
});

3) OPTIONAL: You could change the reference from phonegap.js to cordova.js. PhoneGap Build inserts to files (phonegap.js and cordova.js), while phonegap.js could be considered deprecated and might be removed in a future version, but both files contain the same code.
This solved the issue for me.


text:
Q: my window.onscroll event not working I am trying to make the opacity of an image transition to 0 after the user scroll a certain amount. Not sure why but the javascript function is not working. Any help would be greatly appreciated. Thanks in advance. Here is my code:

var bengalsedit = document.getElementsByClassName("bengals_edited");
console.log(bengalsedit);

window.onscroll = function() {
  addOpacity()
};

function addOpacity() {
  if (document.body.scrollTop > 200) {
    bengalsedit.style.opacity = 0;
  }
}
.bengals_edited {
  display: inline-block;
  width: 100%;
  position: absolute;
  z-index: 3;
  margin: 850px 0 0 0;
  height: auto;
  opacity: 1;
}

.bengals_edited img {
  display: inline-block;
  padding: 15px;
  background-color: #ffffff;
  width: 24%;
  float: left;
  margin-left: 15px;
  margin-top: -6px;
}

A: bengalsedit is a collection, not an element.

bengalsedit[0].style.opacity=0;

A: You're using getElementByClassName. This is returning an HTMLCollection in stead of a single element. This can be fixed in 2 ways:

*

*use getElementById and set an id on the element, or

*get the first element of the collection by using: bengalsedit[0]
If you have more then 1 element to set the opcity to you need to loop through the HTMLCollecion.
More info can be found here


text:
Q: SQL joining with the same table I have a table with EVENT_ID column its have multiple entries against this event_id and then have event_name column.
 so my requirement is I need to select couple event-name along  with the finalized event records if the one of the event_name is finalized_Event and in the passed event_ids, otherwise ignore that event_id,  is there any way I can combine all query in one SQL.
       Select * from EVENT where EVENT_ID in ('0cbe3a81-8102-4eee-b8ef-07485f58cf0a','42b47725-4cc3-4620-9051-652d5409e69a','6e1b73d1-2f20-410c-80d2-89b0ccfde473')
   and
    ( select * from EVENT where EVENT_NAME = 'FinalisedEvent' and (EVENT_NAME = 'CreatedEvent' or EVENT_NAME = 'DeletdEvent'))

A: Do you want something like:
SELECT e1.*
FROM EVENT e1
INNER JOIN EVENT e2
  ON e1.EVENT_ID = e2.EVENT_ID
  AND (e2.EVENT_NAME = 'CreatedEvent' OR e2.EVENT_NAME = 'DeletdEvent')
WHERE e1.EVENT_ID in ('0cbe3a81-8102-4eee-b8ef-07485f58cf0a','42b47725-4cc3-4620-9051-652d5409e69a','6e1b73d1-2f20-410c-80d2-89b0ccfde473')
AND e1.EVENT_NAME = 'FinalisedEvent'


text:
Q: Scope of an inside-parenthesis declared object If I declare an object like this:
void main()
{
    myclass objectA(anotherclass(true,true,0));
}

i.e. I create an objectA and another object "anotherclass" by directly calling the latter's constructor, what is "anotherclass"'s scope?
Does it get destructed only when main() finishes?

A: The temporary gets destructed at the end of the full expression that contains it, i.e. when the call to the constructor of myclass returns.
Per Paragraph 12.2/3 of the C++11 Standard:

Temporary objects are destroyed as the last step
  in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true
  even if that evaluation ends in throwing an exception. The value computations and side effects of destroying
  a temporary object are associated only with the full-expression, not with any specific subexpression.

For this reason, if myclass's constructor takes an argument of type anotherClass by reference (either lvalue reference to const or rvalue reference), it shall not store it for future use, because it will be dangling if a temporary is passed, and dereferencing it would be Undefined Behavior.
It is only objectA that goes out of scope and gets destroyed when returning from the main() function.

A: The anotherclass object doesn't have a scope. Scope is a property of names, not of objects, and this object is not named. It's just a temporary object and will be destroyed at the end of the full expression.
Here's the definition of scope (§3.3.1):

In general, each particular name is valid only within some possibly discontiguous
  portion of program text called its scope.


text:
Q: Adding tags created to child resources created by terraform Terraform v0.11.9
+ provider.aws v1.41.0
I want to know if there is a way to update a resource that is not directly created in the plan but by a resource in the plan.  The example is creating a managed Active Directory by using aws_directory_service_directory  This process creates a security group and I want to add tags to the security group.  Here is the snippet I'm using to create the resource
resource "aws_directory_service_directory" "NewDS" {
  name       = "${local.DSFQDN}"
  password   = "${var.ADPassword}"
  size       = "Large"
  type       = "MicrosoftAD"
  short_name = "${local.DSShortName}"

  vpc_settings {
    vpc_id = "${aws_vpc.this.id}"
    subnet_ids = ["${aws_subnet.private.0.id}",
      "${aws_subnet.private.1.id}",
    ]
  }
 tags = "${merge(var.tags, var.ds_tags, map("Name", format("%s", local.VPCname)))}"
}

I can reference the newly created security group using
"${aws_directory_service_directory.NewDS.security_group_id}"

I can't use that to update the resource.  I want to add all of the tags I have on the directory to the security, as well as updating the Name tag.  I've tried using a local-exec provisioner, but the results have not been consistent and getting the map of tags to the command without hard coding it has not worked.
Thanks

A: I moved the local provider out of the directory service resource and into a dummy resource.
resource "null_resource" "ManagedADTags"
{
provisioner "local-exec"
{
command = "aws --profile ${var.profile} --region ${var.region} ec2 create-tags --
resources ${aws_directory_service_directory.NewDS.security_group_id} --tags
Key=Name,Value=${format("${local.security_group_prefix}-%s","ManagedAD")}"
}
}

(The command = is a single line)
Using the format command allowed me to send the entire list of tags to the resource.  Terraform doesn't "manage" it, but it does allow me to update it as part of the plan.

A: You can then leverage the aws_ec2_tag resource, which works on non-ec2 resources as well, on conjunction with the provider attribute ignore_tags. Please refer to another answer I made on the topic for more detail.

A: aws already exposes api for that where you can tag resources not just a resource. not sure why terraform is not implementing that

A: Just hit this as well. Turns out the tags propagate from the directory service. So if you tag your directory appropriately, the name tag from your directory service will be applied to the security group.


text:
Q: Word and noun similarity Python NLTK I have a simple problem in Python using NLTK. I want to check similarities between words. After some research, I'm trying to use wordnet.synsets(). But I don't understang some results:
syns1 = wordnet.synsets('location')
syns2 = wordnet.synsets('located')

for s1, s2 in product(syns1, syns2):
    print("%s -- %s :" % (s1, s2))
    print(s1.wup_similarity(s2)

Synset('location.n.01') -- Synset('locate.v.01') :
None
Synset('location.n.01') -- Synset('situate.v.01') :
None
Synset('location.n.01') -- Synset('locate.v.03') :
None
Synset('location.n.01') -- Synset('settle.v.04') :
None
Synset('location.n.01') -- Synset('located.s.01') :
None
Synset('placement.n.03') -- Synset('locate.v.01') :
None
Synset('placement.n.03') -- Synset('situate.v.01') :
None
Synset('placement.n.03') -- Synset('locate.v.03') :
None
Synset('placement.n.03') -- Synset('settle.v.04') :
None
Synset('placement.n.03') -- Synset('located.s.01') :
None
Synset('localization.n.01') -- Synset('locate.v.01') :
None
Synset('localization.n.01') -- Synset('situate.v.01') :
None
Synset('localization.n.01') -- Synset('locate.v.03') :
None
Synset('localization.n.01') -- Synset('settle.v.04') :
None
Synset('localization.n.01') -- Synset('located.s.01') :
None
Synset('location.n.04') -- Synset('locate.v.01') :
None
Synset('location.n.04') -- Synset('situate.v.01') :
None
Synset('location.n.04') -- Synset('locate.v.03') :
None
Synset('location.n.04') -- Synset('settle.v.04') :
None
Synset('location.n.04') -- Synset('located.s.01') :
None

Can someone explain me why this happens and how to have a good result for word similarity ? I know one is a noun and the other is a verb/adj but hey common it's 99% the same !
Thank you.

A: There are different types of similarities often looked at,
the issue you seem to have is because it is a syntactic difference as well.
If you want to have only a character level match and a similarity based on it, then you can try :
from fuzzywuzzy import fuzz
word1 = "location"
word2 = "located"
similarity = fuzz.ratio(word1,word2)
print(similarity)

However if you do want to check with wordnet and relate to more than a character match. I would suggest you to first lemmatize your word and then run it through the check.
from pattern.en import lemma
word1 = "located"
lemma_word1 = lemma(word1)


text:
Q: Why does closing file descriptors after fork affect the child process? I want to run programs in linux by a button click an therefore I wrote a function execute:
void execute(const char* program_call, const char* param )
{
    pid_t child = vfork();

    if(child == 0) // child process
    {
        int child_pid = getpid();

        char *args[2]; // arguments for exec
        args[0] = (char*)program_call; // first argument is program_call
        args[1] = (char*)param;

        // close all opened file descriptors:
        const char* prefix = "/proc/";
        const char* suffix = "/fd/";
        char child_proc_dir[16];
        sprintf(child_proc_dir,"%s%d%s",prefix,child_pid, suffix);

        DIR *dir;
        struct dirent *ent;

        if ((dir = opendir (child_proc_dir)) != NULL) {
            // get files and directories within directory
            while ((ent = readdir (dir)) != NULL) {
                // convert file name to int
                char* end;
                int fd = strtol(ent->d_name, &end, 32);
                if (!*end) // valid file descriptor
                {
                    close(fd); // close file descriptor
                    // or set the flag FD_CLOEXEC
                    //fcntl( fd, F_SETFD, FD_CLOEXEC );
                }
            }
            closedir (dir);
        }
        else
        {
            cerr<< "can not open directory: " << child_proc_dir <<endl;
        }
        // replace the child process with exec*-function
            execv(program_call,args);
            _exit(2);
        }
    else if (child == -1) // fork error
    {
        if (errno == EAGAIN)
        {
            cerr<<"To much processes"<<endl;
        }
        else if (errno == ENOMEM)
        {
            cerr<<"Not enough space available."<<endl;
        }
    }
    else // parent process
    {
        usleep(50); // give some time
        if ( errno == EACCES)
        {
            cerr<<"Permission denied or process file not executable."<<endl;
        }
        else if ( errno == ENOENT)
        {
            cerr<<"\n Invalid path or file."<<endl;
        }
        int child_status;
        if ( waitpid(child, &child_status, WNOHANG | WUNTRACED) < 0) // waitpid failed
        {
            cerr<<"Error - Execution failed"<<endl;
        }
        else if ( WIFEXITED( child_status ) &&  WEXITSTATUS( child_status ) != 0)
        {
            cerr<<"Child process error - Execution failed"<<endl;
        }
    }
}

There are two problems:

*

*Closing the file descriptors causes some problems, for example Thunderbird crashes or VLC runs without sound. More exactly: closing of stdout(1) and stderr(2) causes these problems. As I understand, closing file descriptor before exec only prevents them from been duplicated (there is no need to send informations from child process to parent process). Why does this affect the child process? Replacing close() by setting the flag FD_CLOEXEC doesn't change anything. Also setting the FD_CLOEXEC flag before fork doesn't solve the problem. Is there a better way to prevent inheritance of file descriptors?

*The return value of waitpid is often 0, even if the program call fails, I think because there are two (asynchrone) processes. usleep(50) solves this problem for my needs, but I hope there are better solutions for this problem.
I'm using vfork, but the same problems occur by using fork.

A: First, in 2014, never use vfork but simply fork(2). (Since vfork(2) is obsolete since POSIX 2001 and removed in POSIX 2008).
Then, the simplest way to close most of file descriptors is just
for (int fd=3; fd<256; fd++) (void) close(fd);

(hint: if a fd is invalid, close(fd) would fail and we ignore the failure; and you start from 3 to keep open 0==stdin, 1==stdout, 2==stderr; so in principle all the  close above would fail).
However, well behaved and well-written programs should not need such a loop on closing (so it is a crude way to overcome previous bugs).
Of course, if you know that some file descriptor other than stdin, stdout, stderr is valid and needed to the child program_call (which is unlikely) you'll need to explicitly skip it.
and then use FD_CLOEXEC as much as possible.
It is unlikely that your program would have a lot of file descriptors without you knowing them.
Maybe you want daemon(3) or (as commented by vality) posix_spawn.
If you need to explicitly close STDIN_FILENO (i.e. 0), or STDOUT_FILENO (i.e. 1), or STDERR_FILENO (i.e. 2) you'll better open("/dev/null",... and dup2 them after - before calling exec, because most programs expect them to exist.

A: First problem: There is no way to prevent inheritance of file descriptors except you close them yourself or set FD_CLOEXEC, check this
Second problem: You got The return value of waitpid is often 0, because you sepecfied WNOHANG in waitpid.
waitpid(): on success, returns the process ID of the child whose state has changed;
if WNOHANG was specified  and  one  or  more  child(ren) specified by pid exist,
but have not yet changed state, then 0 is returned.  On error, -1 is returned.


text:
Q: Ladder operators and the Hermitian adjoint We define $$\hat{a}=\sqrt{\frac{m \omega}{2 \hbar}}\left(\hat{x}+i \frac{\hat{p}}{m w}\right)$$ $$\hat{a}^{\dagger}=\sqrt{\frac{m \omega}{2 \hbar}}\left(\hat{x}-i \frac{\hat{p}}{m w}\right)$$
Lowering and raising operators respectively. Clearly, these are conjugates in the regular complex scalar sense but we label them and treat them as Hermitian adjoints (complex transpose). Since the differential operator can be represented by an infinitely large matrix, why do we not need to take the transpose part of it into account?

A: Short answer: $x$ and $p$ in quantum mechanics are operators, not numbers. It means that, for example, $\hat{x}|\psi\rangle = |\phi\rangle$ where $|\psi\rangle$ and $|\phi\rangle$ vectors in our Hilbert space (up to normalization). As they are operators that correspond to physical observables, they must be Hermitian operators. The rules of how to take the Hermitian-conjugate of $a$ to get $a^{\dagger}$ follow immediately.
Longer answer: you are right that the usual definition of operators in terms of matrices in quantum mechanic is sometime problematic, especially at undergraduate level. The point is that $x$ and $p$ cannot be defined in terms of matrices of finite size. To see this, it is suffice to note that $\left[ x,p \right] = i\hbar$ is a requirement, yet for any two finite matrices $A$ and $B$, we have ${\rm Tr}\{\left[A, B\right]\} =0$ because the trace is cyclic.
There are ways to write $x$ and $p$ as matrices, but they must be either infinite, or violate this fundamental commutation relation. Now, there is no problem with infinite matrices. In fact, $a$ and $a^{\dagger}$, represented as matrices, must also be infinite (just because they also maintain a commutation relation of $[a,a^{\dagger}]=1$). This comes from the fact that our Hilbert space is infinite $|n\rangle$ with $n$ any non-negative integer.
One can define $x$ and $p$ as finite matrices, with some finite-lattice spacing, in a large box $L$, and then demand that $\langle \psi | [x,p] | \psi \rangle = i\hbar$ for almost the entire Hilbert space, with the states for which this is violated have their support only at the edges of the box, and we are never to use them for any physical observable. This is sometimes done when we want to write $x$ and $p$ on the computer and calculate stuff, and we are of course restricted only to finite matrices.

A: In the number basis of the harmonic oscillator (where the number operator energy is diagonal), your text  must (and certainly Wikipedia does) have
$$a^\dagger =\begin{pmatrix}
0 & 0 & 0 & \dots & 0 &\dots \\
\sqrt{1} & 0 & 0 & \dots & 0 & \dots\\
0 & \sqrt{2} & 0 & \dots & 0 & \dots\\
0 & 0 & \sqrt{3} & \dots & 0 & \dots\\
\vdots & \vdots & \vdots & \ddots  & \vdots  & \dots\\
0 & 0 & 0 & \dots & \sqrt{n} &\dots &  \\
\vdots & \vdots & \vdots & \vdots & \vdots  &\ddots \end{pmatrix}
$$
and
$$a =\begin{pmatrix}
0 & \sqrt{1} & 0 & 0 & \dots & 0 & \dots \\
0 & 0 & \sqrt{2} & 0 & \dots & 0 & \dots \\
0 & 0 & 0 & \sqrt{3} & \dots & 0 & \dots \\
0 & 0 & 0 & 0 & \ddots & \vdots & \dots \\
\vdots & \vdots & \vdots & \vdots & \ddots & \sqrt{n} & \dots \\
0 & 0 & 0 & 0 & \dots & 0 & \ddots \\
\vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \ddots \end{pmatrix}, $$
both infinite-dimensional matrices and adjoint (actually transpose) of each other.
Adding them together gives you the hermitian (actually symmetric)
$$
\hat x = \sqrt{\frac{\hbar}{2m\omega}} \begin{pmatrix}
0 & \sqrt{1} & 0 & 0 & \dots & 0 & \dots \\
 \sqrt{1} & 0 & \sqrt{2} & 0 & \dots & 0 & \dots \\
0 & \sqrt{2} & 0 & \sqrt{3} & \dots & 0 & \dots \\
0 & 0 & \sqrt{3} & 0 & \ddots & \vdots & \dots \\
\vdots & \vdots & \vdots & \vdots & \ddots & \sqrt{n} & \dots \\
0 & 0 & 0 & 0 & \sqrt{n} & 0 & \ddots \\
\vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \ddots \end{pmatrix},
$$
and it should be straightforward for you to construct the likewise hermitian (imaginary antisymmetric) $\hat p$.


text:
Q: Azure bus service queue messages processing We need to process Azure Bus queue messages receiving configuration.
We need to implement an application that listens for these messages and processes them when they are received.
We can create .Net core console application to listen the queue.
But we need to host this in Linux. And how to host this console application in linux as always running service ?
Thanks in advance.


text:
Q: Flex HBox with background color and rounded corner, wiered problem I am facing a wiered problem in Flex. I Have a canvas with a HBox and Label. Please find the code below.
   <mx:VBox verticalAlign="top" horizontalAlign="center"
        fontSize="12" fontWeight="normal" verticalGap="0">
        <mx:Label text="Cover" />
        <mx:Canvas width="120" styleName="pbcontainer">
            <mx:HBox id="pb" height="35" />
            <mx:Label id="dashboard_cover" fontWeight="normal"
                      fontSize="20" horizontalCenter="0" verticalCenter="0"/>
        </mx:Canvas>
    </mx:VBox>

.pbcontainer {
    cornerRadius: 15;
    backgroundColor: #FFFFFF;
    borderStyle: solid;
    borderThickness: 2;
    borderColor: #000000;
}

I am trying to implement a ProgressBar here.
Now, the problem is if the percentWidth of pb is less than 5, the haloBlue color is spilling out which is not desired. Please find the image below. Can anyone help me in solving this issue.

Thanks,
Anji

A: Just an idea, instead of using an HBox with a background, try using a ProgressBar and set its progress instead of percentWidth of the HBox.
Edit: Oh well, based on the discussion in the comments, it seems the above solution is not feasible. Did you try setting the cornerRadius on the inner HBox? It is the one with the blue background isn't it?


text:
Q: How does map difficulty work in Dungeon Defenders? Does it works like in Mass Effect 3 MP, where no matter how many players are in the party and their levels; or it works by changing enemies level according to the party number and party levels, like in Dead Island?

A: Boss' health and the number of enemies per wave scale with the number of characters actively being played. You can observe this by the number of enemies next wave changing when a new player joins during build phase.
Character levels have no effect on difficulty in the game. You get the exact same enemy health and number of enemies if you're playing the same map/difficulty with a level 10 character or a level 70 character.


text:
Q: Is there a way to post a message with a code snippet? The new way to upload images as hosted content through the Send Message endpoint is great! However, is there a way to upload text/plain as hosted content in order to post a Code Snippet Card in a message?
I have tried uploading text but the response gives me an error that says that the only content types allowed are 'image/jpg,image/jpeg,image/png'.
Example request:
{
    "body": {
        "contentType": "html",
        "content": "<attachment id=\"4d92eb51ab9c48ebb5b364794a2fa569\"></attachment>"
    },
    "attachments": [
        {
            "id": "4d92eb51ab9c48ebb5b364794a2fa569",
            "contentType": "application/vnd.microsoft.card.codesnippet",
            "contentUrl": null,
            "content": "{\"name\":\"\",\"language\":\"CSharp\",\"lines\":1,\"wrap\":false,\"codeSnippetUrl\":\"../hostedContents/1/$value\"}",
            "name": null,
            "thumbnailUrl": null
        }
    ],
    "hostedContents":[
        {
          "@microsoft.graph.temporaryId": "1",
          "contentBytes": "VGVzdA==",
            "contentType": "text/plain"
        }
    ]
}

Response:
{
    "error": {
        "code": "BadRequest",
        "message": "Unsupported content type in hostedContent with Id '1'. Allowed values are 'image/jpg,image/jpeg,image/png'",
        "innerError": {
            "date": "2020-10-07T12:17:15",
            "request-id": "ed24f5df-3e1f-4871-b430-e4c1c9f30348",
            "client-request-id": "ed24f5df-3e1f-4871-b430-e4c1c9f30348"
        }
    }
}

A: I received an answer in the Documentation GitHub: https://github.com/microsoftgraph/microsoft-graph-docs/issues/10210#issuecomment-705050649

Code snippets are not supported at the moment. They are on list of things to support, but there is no timeline to share yet.


text:
Q: How to convert SQL to Arel? Is there a way to convert the MATCH and AGAINST parts to Arel?
I could not find anything about it in the Arel source code.
I'm using Rails 3.
SELECT gigs.time, gigs.channel_id, gigs.song_id, gigs.id,
  MATCH (songs.title) AGAINST (?) AS song_score,
  MATCH (artists.name) AGAINST (?) AS artist_score
  FROM songs
  INNER JOIN artists ON artists.id = songs.artist_id
  INNER JOIN gigs ON gigs.song_id = songs.id
  WHERE MATCH (artists.name) AGAINST (?) OR
  MATCH (songs.title) AGAINST (?)
  HAVING (artist_score + song_score) > 0

A: AFAIK there is no Arel MATCH AGAINST implementation. My guess is because it is not pure SQL, but specific to MySQL.


text:
Q: Правильно составить регулярное выражение для строки, содержащей скобки есть строка
"128728581": {"vehicleType": "vehicleType", "isAlive": true, "name": "name", "clanAbbrev": "", "team": 1, "events": {}, "isTeamKiller": false},

пытался сделать так
@"""\d+""[^}]+"

но проблема в том что в "events" есть закрывающая скобка.
как вариант ,сделал так
@"""\d+""[^}]+[^}]+events[^,]+[^}]+"

но просто измениться строка и event не будет то не будет работать, как правильнее сделать?
И еще один вопрос :
нужно из той же строки достать набор цифр в начале, сделал так
string[] arr = reg.Match(parse).ToString().Split('"');

reg = new Regex(@"\d+");

foreach (string val in arr)
{
    if (reg.IsMatch(val)) {
        id = int.Parse(val);
        break;
    }
}

но как то не самый оптимальный вариант (мне кажется).
То что это JSON, я знаю и то что есть спец либы для разбора, но мне нужно из большого документа вытащить строки с нужным мне id, а потом их парсить.
П.с почему не работает тэг code, не могу понять как код подсвечивать?
A: Используйте подходящий инструментарий для задачи. Если вы хотите распарсить JSON, пользуйтесь JSON-парсером. Например, JSON.NET.
Хотя современные регулярные выражения и являются Тьюринг-полными, известно, что правильно (то есть с учётом всех возможных подводных камней) парсить рекурсивные грамматики на них неоправданно сложно. Делайте правильно, сэкономьте геморрой и время на более приятные дела.

Если вам посчастливилось работать с .NET 4.5, там есть встроенный JSON-парсер.


text:
Q: I cant get my logo to appear on the navbar This is what I'm getting right now For some reason when I try to get my navbar logo to appear, instead of the logo, I get some type of picture icon. Here is my code:
`

    Imito

            Hot

            New

            Top

`

A: This happens when your program is unable to locate the picture in the specified path or it cannot access the specified path. My advice is to place the logo in the same folder as the html code and just use
It should definitely work then.

A: Can't comment so had to use an answer, have you checked the console to see if it returns a 404 for the image. It sounds like the file you specified cannot be found?


text:
Q: Can not rewrite to file using .htaccess in CodeIgniter? My structure like this :
- application
  - controllers
  - log
    - login
- mysite

I want to redirect http://mysite/index.php/log/login => mysite/login.html
I turned on Rewrite Mode; In my .htaccess:
Options +FollowSymLinks All -Indexes
RewriteEngine On
RewriteRule ^login.html$ ./index.php/log/login

but I met 404 error. I tested by make one file test.php and place it in mysite folder
=> It is OK!
Please help me config that URL.

A: Try this
Options -Indexes
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php/log/$1 [L]


text:
Q: how to get start time and end time after resizing the events in calender and also its respective event name?

Channel List

My Event 1

My Event 2

My Event 3

My Event 4

My Event 5

after dragging and dropping the events into the calender,
how to get start time and end time after resizing the events in calender and also its respective event name?
Working demo and complete code here in js fiddle

A: You can use eventResize
I have made a fiddle for this
https://jsfiddle.net/athulnair/0g7k27na/18/
eventResize: function(event,jsEvent,ui,view) {
   console.log("event",event);
}


text:
Q: Windows RODC/DMZ connection to trusted AD issue I have a really strange scenario...We have a server within a DMZ, which uses an  RODC (Read-Only Domain Controller) for user authentication.   The users are in a trusted 3rd domain, something like this:
DMZserver -> RODC -> InternalDC -> TrustedDC -> User
This is all to allow us to RDP/login to the DMZserver.  It works currently for an older Windows 2008R2 server, but when we attempt to use these new servers (setup basically identically (same network subnet, same firewall rules, validated communication with the RODC, etc) it WILL NOT authenticate or communicate with the InternalDC's through the RODC.
I've looked at the replication and joined/rejoined the DMZServer to the internal domain several different times and ways.  However I continue to get a netlogin issue, it won't connect to the RODC for DNS, Time Settings, login authentication, etc...
Its maddening, and I'm at a loss, so I'm hoping someone can give me some guidance or pointers on how I can gather some more information on this.
I have reviewed the question at
Windows Server 2012 R2 Standard located in our DMZ has problems with connection to RoDC
However the solution presented there with the sitename does not solve my issue and has been tested multiple times.
Any help would be appreciated!

A: So we seem to have discovered a workaround for the issue at hand.  So we pre-populated and replicated the account details and passwords from the Internal Read/Write domain controller to our ReadOnlyDomainController (RODC) within the DMZ sites.   Once we had replicated/cached the computer details over to the RODC, this allowed the computer account (windows 2012 R2) servers to communicate properly.
We are still investigating with Microsoft, but hopefully this will help others that maybe having similar odd behaviours with RODC systems in DMZ designs.
Please let me know if you have further questions around this issue, and I'll be happy to provide additional information.


text:
Q: How to insert the residual distribution of a linear regression, where the x axis is perpendicular to the fitted line? I have seen some papers that deal (not completely) with residuals in a regression analysis in a smart way, they plot the residual distribution perpendicular to the fitted line.
Example image from Figure 2 or 5 (linear regression) in: https://www.nature.com/articles/nn.4538#results
My R example:
The data example it has been taken from: https://www.r-bloggers.com/simple-linear-regression-2/
Data example:
alligator = data.frame(
  lnLength = c(3.87, 3.61, 4.33, 3.43, 3.81, 3.83, 3.46, 3.76,
               3.50, 3.58, 4.19, 3.78, 3.71, 3.73, 3.78),
  lnWeight = c(4.87, 3.93, 6.46, 3.33, 4.38, 4.70, 3.50, 4.50,
               3.58, 3.64, 5.90, 4.43, 4.38, 4.42, 4.25)
)

Linear regression model:
reg <- lm(alligator$lnWeight ~ alligator$lnLength)

Scatter plot:
plot(alligator,
   xlab = "Snout vent length (inches) on log scale",
   ylab = "Weight (pounds) on log scale",
   main = "Alligators in Central Florida"
)

Fitted line:
abline(reg,col = "black", lwd = 1)

Residual distribution (histogram):
hist(reg$residuals, 10, xaxt='n', yaxt='n', ann=FALSE)

I would like to insert the histogram at the topright of the linear regression plot as the example image from Figure 2 or 5 (linear regression) in: https://www.nature.com/articles/nn.4538#results
Thanks for the help.

A: This will work to get the residual histogram overlaid on the main plot. You'll have to do a bit of work to get it to be angled perpendicular, as in the examples you cite.
library("ggplot2")
theme_set(theme_minimal())

alligator = data.frame(
  lnLength = c(3.87, 3.61, 4.33, 3.43, 3.81, 3.83, 3.46, 3.76,
               3.50, 3.58, 4.19, 3.78, 3.71, 3.73, 3.78),
  lnWeight = c(4.87, 3.93, 6.46, 3.33, 4.38, 4.70, 3.50, 4.50,
               3.58, 3.64, 5.90, 4.43, 4.38, 4.42, 4.25)
)

reg <- lm(alligator$lnWeight ~ alligator$lnLength)

# make main plot, with best fit line (set se=TRUE to get error ribbon)
main_plot <- ggplot(alligator, aes(x=lnLength, y=lnWeight)) +
  geom_point() + geom_smooth(method="lm", se=FALSE) +
  scale_y_continuous(limits=c(0,7))

# create another plot, histogram of the residuals
added_plot <- ggplot(data.frame(resid=reg$residuals), aes(x=resid)) +
  geom_histogram(bins=5) +
  theme(panel.grid=element_blank(),
        axis.text.y=element_blank(),
        axis.text.x=element_text(),
        axis.title.x=element_blank(),
        axis.title.y=element_blank(),
        axis.ticks.y=element_blank(),
        axis.line.y=element_blank())

# turn the residual plot into a ggplotGrob() object
added_plot_grob <- ggplot2::ggplotGrob(added_plot)

# then add the residual plot to the main one as a custom annotation
main_plot + annotation_custom(grob=added_plot_grob,
                              xmin=4.0, xmax=4.35, ymin=1, ymax=5)

Then check out the docs for ggplot2:: and gridExtra:: to figure out the rotation. Hope this helps!


text:
Q: Using parent id in child query? SELECT li_1.carrier, li_1.product_id, li_1.quantity, products_description.products_name, sites.sites_id, sites.sites_name, counted_table.counted
FROM inventory li_1
INNER JOIN products_description ON li_1.product_id = products_description.products_id
INNER JOIN sites ON products_description.data = sites.data
INNER JOIN (
   SELECT SUM( li_2.quantity ) AS counted
   FROM inventory li_2
   WHERE li_1.product_id = li_2.product_id
) counted_table
GROUP BY li_1.product_id
ORDER BY li_1.id DESC

I'm attempting to use the parent id (product_id) to count the total amount of quantity for each product in the subquery - But I only get the standard mysql error message.
So something like
   id   |   quantity    |   total
---------------------------------
0001    |       2       |   6
        |               |
0001    |       4       |   6

What could be wrong?

A: if you change sub-query, it could be fixed
SELECT li_1.carrier, li_1.product_id, li_1.quantity, products_description.products_name, sites.sites_id, sites.sites_name, counted_table.counted
FROM inventory li_1
INNER JOIN products_description ON li_1.product_id = products_description.products_id
INNER JOIN sites ON products_description.data = sites.data
INNER JOIN (
   SELECT product_id,SUM( li_2.quantity ) AS counted
   FROM inventory li_2
   GROUP BY li_2.product_id
) counted_table ON li_1.product_id = counted_table.product_id
ORDER BY li_1.id DESC


text:
Q: xcode 6 ios 8 recompile from 7.1 all container views have disappeared My app running in xcode 5 ios 7.1 has been recompiled in xcode 6 for ios 8.1 on new yosemite OS.
It's still running but all my container views have just disappeared from the storyboard. The definitions to the left of the storyboard are still present as are all the links.
When run in simulator there are also not showing
See below:

Defitions are still there:

And to clarify my actual question is how do I get these back without having to rebuild everything?

A: turns out this is related to the container view having 0 width and 0 height. for some reason the migration process to xcode 6 thinks it's a good idea to make the container invisible.
Once you set to w/h the detail views will magically appear.
Other option that works but not ideal is to delete the segue between the container and the subview. Not ideal as it will disappear when you reconnect.
I'm assuming because the subview has inferred size that the 0/0 size of the container makes it also 0/0.


text:
Q: WPF: How to get SelectedItem after applying value converter? I have control where I bind the images. The code in my view model looks as following:
public List<IDocument> SelectedEventPhotoList
{
    get { return _selectedEventPhotoList; }
    set
    {
        if (Equals(value, _selectedEventPhotoList))
            return;

        _selectedEventPhotoList = value;
        RaisePropertyChanged(() => SelectedEventPhotoList);
    }
}

public IDocument SelectedEventPhoto
{
    get { return _selectedEventPhoto; }
    set
    {
        if (Equals(value, _selectedEventPhoto))
            return;

        _selectedEventPhoto = value;
        RaisePropertyChanged(() => SelectedEventPhoto);
    }
}

The binding looks as following:
<ListView Grid.Row="0"
            ItemsSource="{Binding SelectedEventPhotoList, Converter={StaticResource PathToFileConverter}}"
            SelectedItem="{Binding SelectedEventPhoto}"

As you can see I have a list of IDocument types to bind to ItemsSource and SelectedItem is of IDocument type. But, images have Source property that is of type string and I've used PathToFileConverter value converter to convert IDocument types to strings.
The issue is in fact that after using converter, SelectedItem is null.
How can I achieve the SelectedItem keeps IDocument type, which is not null?

A: You should apply the converter to the Source property binding of the Image and not to the ItemsSource of the ListView
The type of the property that is bound to the SelectedItem property of a ListView should always be T if the ItemsSource property is bound or set to an IEnumerable<T>.

A: You should remove the converter from the ItemSource binding, and add DisplayMemberPath="PathOfFileProperty", which 'PathOfFileProperty' is the string property on IDocument which indicate the file path


text:
Q: Make synclient settings permanent Lubuntu 18.04 I wish to set
synclient HorizTwoFingerScroll=0
synclient VertTwoFingerScroll=0
synclient MaxTapTime=0
synclient CoastingSpeed=0
synclient VertEdgeScroll=1

syndaemon -d -t

I am using Lubuntu 18.04 HP-255-G1-Notepad
What is the easiest & safest way to make these settings permanent please?

A: In Lubuntu 18.04 LTS it is different from and easier than in the other Ubuntu flavours.
Edit your commands into the autostart file.

*

*Use your favourite editor, leafpad or nano, for example
nano ~/.config/lxsession/Lubuntu/autostart

*Save the file.
The next time you log in to the LXDE desktop environment of Lubuntu 18.04 LTS, your commands will be run automatically.


text:
Q: How do I make my instagram bot move through pictures and like each one? For my first  project on automation, I am working on a bot that can go to a hashtag on instagram and like each pictures as it iterates through them. The bot can do what is mentioned above except like each pictures as it iterates. I need help figuring this out.
i
import pyautogui,time
pyautogui.FAILSAFE = False

pyautogui.moveTo(608, 431,duration=0.1) #Goes moves cursor to search bar
pyautogui.click(608, 43) # clicks on search bar
pyautogui.typewrite("http://instagram.com") #types in web address
pyautogui.typewrite(["enter"]) #activates enter key

pyautogui.moveTo(641, 96,duration=0.1) #moves cursor to instagram search bar
pyautogui.click(641, 96) #clicks on search bar
pyautogui.typewrite("#cats")# types in hashtag
pyautogui.moveTo(652, 225,duration=0.1) #moves cursor to hashtag suggestion
time.sleep(1);pyautogui.click(652, 225)#clicks on hashtag suggestion

#Clicks on picture
pyautogui.moveTo(348, 564,duration=0.1) #moves cursor on picture
time.sleep(1);pyautogui.click() #Clicks on picture
time.sleep(1);pyautogui.moveTo(1170, 451) #moves cursor to the right arrow on picture
for i in range(4): #clicks on pictures by iterating a certain number of times
    pyautogui.click(1170, 451)

A: Try adding the following
for i in range(4):

    time.sleep(5)
    pyautogui.moveTo(xRes/2, yRes/2, duration=0.5)
    pyautogui.doubleClick()

xRes and yRes refers to the monitor resolution, and like the image by double clicking. Hope it helps


text:
Q: How does for(i=0; i<5; x=(i++,a++)) work I can't understand how this works and why it produces
the following output.
int main()
{
    int i=0;
    int a=5;
    int x=0;

    for(i=0; i<5; x=(i++,a++))
    {
        printf("i=%d a=%d x=%d\n",i,a,x);
    }
}

this give as output:
i=0 a=5 x=0
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8

A: Forget about the ++ for the moment, they're just a distraction.
int a = 5;
int i = 0;
int x = (i, a);

Sets the value of x to 5. The i is evaluated and discarded, then the a is evaluated and assigned to x.
In your loop, the post-increment a++ does what it always does; returns the current value and then increments the variable. So x takes the value of a before it is incremented, then a's value is increased by 1. Because i++ was also evaluated, its value increases as well.

A: I suppose you understand a for loop like this:
for(i=0; i<5; i++)

you might as well want to increment two variables; if you separate them with a comma; like this:
for(i=0; i<5; i++,a++)

at the start of each loop, both i and a will be incremented. Now only the expression x=(i++,a++) needs to be explained:
x gets the last of both values assigned. It is the same as writing:
x=i++;
x=a++;

of course a is post-incremented so first its value is assigned to x; and only then a is incremented.

A: It is simple both the operators that you have used are 'Post Increment', this means that assignment will happen first then the increment in variable will happen.
Let us understand with an example,
Suppose,
i=5
x=i++;
printf("%d", x)

The above code will give output as 5
and
i=5
x=++i;
printf("%d", x)

and this will give output as 6.
Hope you understand the logic.

A: The comma operator means: execute all, and return the last value;
Example:
A = (b+=1,c+2,d+1);

This sentence will add 1 to b, sum 2 to c (but will not modify it) and sum 1 to d. Hence d+1 is the last expression A will be set to its value.
The post and pre operator ++ are tricky.
A++ means: return the value of A and after that, you increment it.
++A means: increment A and then return the value of it.
so if A=2
b=A++; // set b to 2 and increments A one unity
b=++A; // increments A to 4 and sets b to 4

A: Consider your example and the output (except I made the initial value of x to be 22):
int i=0;
int a=5;
int x=22;

for(i=0; i<5; x=(i++,a++))
{
    printf("i=%d a=%d x=%d\n",i,a,x);
}

Prints:
i=0 a=5 x=22
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8

Notice that x has either the initial value of x prior to the loop or the previous value from the last trip through the loop.
Recall that any for loop can be expressed as an equivelent while loop.
The for loop of:
for(exp 1; exp 2; exp 3){
    expressions
}

Is equivalent to:
exp 1;
while(exp 2){
   expressions
   exp 3;
}

So your for loop can be written as:
int i=0;              // exp 1 from the for loop
int a=5;
int x=22;

while(i<5){           // exp 2
    // loop body
    printf("i=%d a=%d x=%d\n",i,a,x);

    x=(i++,a++);      // exp 3 from the for loop
}

Prints same output.
The fact that exp 3 is evaluated at the end of the loop (whether it is a for or while loop) is why x has the previous value of x in the body of the loop.
The final thing to consider is the comma operator. The expression:
i=(a+=2, a+b)
   ^^^               evaluate a then add 2
       ^             comma operator in this case
          ^^         add b to a

 ^                   store the final expression -- the RH of the comma operator --
                     into i


text:
Q: What are these numbers that come after the three digit http status code? [13/Jun/2021 10:15:21] "GET /admin/r/18/2/ HTTP/1.1" 500 **112909**
[13/Jun/2021 10:21:47] "GET /__debug__/render_panel/?
store_id=390e09a41aa149b6bed1c05d0451e555&panel_id=RequestPanel HTTP/1.1" 200 **2080**
[13/Jun/2021 10:24:22] "GET /__debug__/render_panel/?
store_id=390e09a41aa149b6bed1c05d0451e555&panel_id=SQLPanel HTTP/1.1" 200 **35097**
[13/Jun/2021 10:25:01] "POST /__debug__/sql_explain/ HTTP/1.1" 200 **2008**

What are these double starred (by me) numbers after the three digit status code? I can't find an explanation. I don't even know what they are called, so I don't know how to look them up. Thanks.

A: This appears to be a Common Log Format file as used by many web servers.  You can find documentation of this format on Apache's website, among other places:

The last entry indicates the size of the object returned to the client, not including the response headers. If no content was returned to the client, this value will be "-".

So generally, this is the number of bytes that the server sent in response to the request.


text:
Q: How can I center my div in the @media query after applying flex-direction? So I tried putting the banner-content-container in the center after using flex-direction:column; in the media query, but it doesn't work. It centers normally but when it gets to the 776px max-width, It doesn't center the div.
Here's my code:

.banner-content-container {
  display: flex;
  justify-content: space-evenly;
  padding-top: 200px;
}

@media screen and (max-width:776px) {
  .banner-content-container {
    display: flex;
    justify-content: center;
    flex-direction: column;
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

01. Mobile conductive

Smart optimization of RWD design.

02. User Interface

Brilliant UI/UX creative designs.

03. Affordable

Our offers dont break the bank.

A: Changing the flex-direction flips your main axis.
When in row mode, horizontal alignment is achieved via flex-direction and vertical alignment with align-items. In your breakpoint, the opposite is now true.

.banner-content-container {
  display: flex;
  justify-content: space-evenly;
  padding-top: 200px;
}

@media screen and (max-width:776px) {
  .banner-content-container {
    align-items: center;
    flex-direction: column;
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

01. Mobile conductive

Smart optimization of RWD design.

02. User Interface

Brilliant UI/UX creative designs.

03. Affordable

Our offers dont break the bank.

Note also that you don't need display: flex within your media query; it's already set in the statement above, media queries don't reset properties.


text:
Q: Class 'Carbon\Laravel\ServiceProvider' not found when composer update When I try composer update in my Laravel project I have this error on the terminal
In ProviderRepository.php line 208:

Class 'Carbon\Laravel\ServiceProvider' not found

Any suggestions appreciated.

A: Try deleting the cache in laravel project folder, you navigate to bootstrap folder, then delete items in cache.

A: run this command on your project. all require class will be download
composer dump-autoload

A: Ok I solved the problem.
First delete the bootstrap/cache/packages.php then
rm -rf vendor

composer install --no-dev


text:
Q: Border for  not working properly in IE7 I want to put border for input type but this is not working properly in IE7
<input type="submit" value="Login" style="border : 1px solid #C7D1D4;">

In other browser this is working along with IE8 but for IE7 it puts an extra black color border. Can this be resolved or the browser's default activity?

A: Try this:
  <!--[if IE]>
    <style type="text/css">
    input {
    filter:chroma(color=#000000);
    border : 1px solid #C7D1D4;
    }
    </style>
    <![endif]-->


text:
Q: Best way to monitor health of a spring app set up as a lambda function I have a spring batch application that is hosted on AWS and runs as a lambda function. This lambda function is triggered when a file is dropped in the corresponding S3 bucket.
My question is: What would be the best way to perform health checks in this scenario? If this were a regular service running in EC2 (i.e. constantly running), I'd just schedule a health check to run after a fixed time interval, but since this lambda only runs for a couple of minutes at most, I'm not sure how I should proceed. I was thinking of just simply setting the health check status based on the individual reader and writer steps somehow. For instance, if the job was able to read successfully, return status UP, else, return some other status.
I do also want to note that the health of this app will need to be documented in splunk via logs.
Please let me know if there is a better solution. I'm new to health checks so my implementation might be incorrect.


text:
Q: Cannot insert explicit value for identity column in table  when IDENTITY_INSERT is set to OFF. I've read every article that stack overflow recommended to me and have not yet solved my problem. This is my first post and I apologize if it is an easy fix, but no matter what I save first (AfterCooler, F1046, or BasicInfo, I get the exception for explicitly inserting AfterCooler's identity. BasicInfo saves fine on it's own, but when adding F1046, saving it, or adding AfterCooler and saving it, I get this exception. AfterCooler and F1046 should have a 1 to 1, and F1046 and BasicInfo should have a one to many relationship.
Entities:
[MetadataType(typeof(F1046MetaDataSource))]
public partial class F1046
{
    public int F1046Id { get; set; }
    public virtual AfterCooler AfterCooler { get; set; }

    public int BasicInfoId { get; set; }
    public virtual BasicInfo BasicInfo { get; set; }
}

class F1046MetaDataSource
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int F1046Id { get; set; }

    [ForeignKey("BasicInfo")]
    public int BasicInfoId { get; set; }
}

[MetadataType(typeof(AfterCoolerMetaDataSource))]
public partial class AfterCooler : IComparer<AfterCooler>
{

    public string AfCoolReasonChange { get; set; }
    public string VendorAF { get; set; }

    public int F1046Id { get; set; }
    public virtual F1046 F1046 { get; set; }
}

class AfterCoolerMetaDataSource
{
    [Key,ForeignKey("F1046")]
    public int F1046Id { get; set; }
}

[MetadataType(typeof(BasicInfoMetaDataSource))]
public partial class BasicInfo
{
    public int BasicInfoId { get; set; }
    public DateTime? DateBasicInfo { get; set; }
    ...
    public virtual ICollection<F1046> F1046 { get; set; }

    public BasicInfo()
    {
        F1046 = new List<F1046>();
    }

}

class BasicInfoMetaDataSource
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int BasicInfoId { get; set; }
}

Repository methods:
public void SaveAfterCooler(AfterCooler afterCooler)
    {
        if (afterCooler.F1046Id == 0)
        {
            context.AfterCooler_.Add(afterCooler);
        }
        else
        {
            context.Entry(afterCooler).State = EntityState.Modified;
        }

        context.SaveChanges();
    }

(this looks the same for essentially every entity, just swapping the contexts/id's..)
I have a view which has elements of the BasicInfo (but not the id's) and of the F1046 (but not the id's), the members of the F1046 (AfterCooler, its properties, etc..) like this:
<div class="form-group">
                    @Html.Label("After Cooler Reason")
                    @Html.EditorFor(x => Model.F1046.AfterCooler.AfCoolReasonChange, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => Model.F1046.AfterCooler.AfCoolReasonChange, "", new { @class = "text-danger" })
  </div>

and it gets submitted to a controller method which I shortened to something like this..
[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult CreateF1046(F1046_CreateViewModel fm)
    {
        if (ModelState.IsValid)
        {
            BasicInfo bi = fm.BasicInfo;
            F1046 f1 = fm.F1046;
            _f1046Repository.SaveF10461(f1);
            bi.F1046.Add(f1);

            return RedirectToAction("Summary", bi);

        }

I've tried everything in every order or at least it feels that way.. I'm sorry if this doesn't make much sense, the program takes a lot of fields in and I tried to leave out the irrelevant ones. The ViewModel mentioned above for the controller method contains a BasicInfo object and an F1046 object for relevance.
 Thank you.


text:
Q: Bandwidth throttling while copying files between computers I've been trying to make a program to transfer a file with bandwidth throttling (after zipping it) to another computer on the same network.
I need to get its bandwidth throttled in order to avoid saturation (Kind of the way Robocopy does).
Recently, I found the ThrottledStream class, but It doesn't seem to be working, since I can send a 9MB with a limitation of 1 byte throttling and it still arrives almost instantly, so I need to know if there's some misapplication of the class.
Here's the code:
using (FileStream originStream = inFile.OpenRead())
using (MemoryStream compressedFile = new MemoryStream())
using (GZipStream zippingStream = new GZipStream(compressedFile, CompressionMode.Compress))
{
    originStream.CopyTo(zippingStream);
    using (FileStream finalDestination = File.Create(destination.FullName + "\\" + inFile.Name + ".gz"))
    {
        ThrottledStream destinationStream = new ThrottledStream(finalDestination, bpsLimit);
        byte[] buffer = new byte[bufferSize];
        int readCount = compressedFile.Read(buffer,0,bufferSize);
        while(readCount > 0)
        {
            destinationStream.Write(buffer, 0, bufferSize);
            readCount = compressedFile.Read(buffer, 0, bufferSize);
        }
    }
}

Any help would be appreciated.

A: The ThrottledStream class you linked to uses a delay calculation to determine how long to wait before perform the current write.  This delay is based on the amount of data sent before the current write, and how much time has elapsed.  Once the delay period has passed it writes the entire buffer in a single chunk.
The problem with this is that it doesn't do any checks on the size of the buffer being written in a particular write operation.  If you ask it to limit throughput to 1 byte per second, then call the Write method with a 20MB buffer, it will write the entire 20MB immediately.  If you then try to write another block of data that is 2 bytes long, it will wait for a very long time (20*2^20 seconds) before writing those two bytes.
In order to get the ThrottledStream class to work more smoothly, you have to call Write with very small blocks of data.  Each block will still be written immediately, but the delays between the write operations will be smaller and the throughput will be much more even.
In your code you use a variable named bufferSize to determine the number of bytes to process per read/write in the internal loop.  Try setting bufferSize to 256, which will result in many more reads and writes, but will give the ThrottledStream a chance to actually introduce some delays.
If you set bufferSize to be the same as bpsLimit you should see a single write operation complete every second.  The smaller you set bufferSize the more write operations you'll get per second, the smoother the bandwidth throttling will work.
Normally we like to process as much of a buffer as possible in each operation to decrease the overheads, but in this case you're explicitly trying to add overheads to slow things down :)


text:
Q: Deleting files in php directory if(unlink('./'.date('m-d-Y').'/'.$file))
{

    echo "file named $file has been deleted successfully";
}
else
{
echo "file is not deleted";
}

I have the code above to delete my files.
However, is it possible to only let it delete files that contain ".5010."
Can I do something like "%.5010.%" or something, also if its more than one file do I need to put it in a while or a foreach loop? Because now it deletes all my files.

A: You can use glob() to find the pathnames matching a pattern.
So your code would look something like this,
$path="./".date('m-d-Y')."/*".$file."*";
$files = glob($path); // this will return multiple files.
foreach ($files as $file) {
  unlink($file);
}

glob() returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

A: You can loop on file with glob and after use preg_match to select files who match a pattern
<?php
foreach(glob('path/to/dir/*.*') as $file) {
    if (preg_match('*.5010.*', $file)) {
        unlink($file)
    }
}


text:
Q: How to display image data using AngularJS? (weird response format) The image is stored in a directory on a php server.
Service:
.factory('PhotoService', function($q, $http) {
   return {
    getPhoto: function(photoName) {
    var url = dirInfo.template_directory + 'quoteCalc/images/Upload/' +      photoName;
    return $http.get(url).then(function(response) {
        return response.data;
    })
    .catch(function(error) {
        return "Photo not found: " + error;
    });
}
}
})

I call that factory in the controller using this function. The data is returned fine but the format is off and the image does not display.
function init() {
    let photo;
    PhotoService.getPhoto(imageName).then(function(result) {
        $scope.imgstr = result;
    });
};
init();

The image/response.data comes in this weird format. I dont know what to do with it. I have tried:
 var blob = new Blob([response.data], {type: 'application/octet-    binary'});
 return URL.createObjectURL(blob);

and
var reader = new FileReader();
return reader.readAsDataURL(response.data);

also
<img ng-src="data:image/png;base64,{{imgstr}}" />

Nothing works. Please help.
This is what is returned:

�����ExifMM*� ���(1�2��ï%HAppleiPhone

6HH9.2.12016:02:09 09:00:51
  ��R��Z�"�'��0221�b�v�� ���� ��
  ���   �
  ����|F���234��234�0100����    ��������2�3
  �4"&2016:02:09 09:00:512016:02:09 09:00:51���
  �JM@bSIs��Apple iOSMM .�h�        �   �
  .             bplist00OVz�2�����.��Vu����������iX�e����9
  ��o�z�f����l)���1����|��yg�g�wz����o�Xem'@D1\vW�S�w�8��~H(O�wboI�Tp\�"9".��)xNT�>G$O��R!i�3   �d��-�+20
  �ux7�Q%+# 3"#j�&dY". �7J<=�|�[T)
  LqL�vFEh:_*HR$hcl�Q?&C*zXJ�*hX_�.*3A;V-f2ubplist00�UflagsUvalueUepochYtimescale��:�;��#-/8:  ?���+0�B����-$SSAppleiPhone
  6 back camera 4.15mm f/2.2NW2:K
  RTZTbjv/$dz�d��2������2016:02:09A���http://ns.adobe.com/xap/1.0/<x:xmpmeta
  xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 5.4.0">    <rdf:RDF
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
        <rdf:Description rdf:about=""
              xmlns:mwg-rs="http://www.metadataworkinggroup.com/schemas/regions/"
              xmlns:stArea="http://ns.adobe.com/xmp/sType/Area#"
              xmlns:apple-fi="http://ns.apple.com/faceinfo/1.0/"
              xmlns:stDim="http://ns.adobe.com/xap/1.0/sType/Dimensions#">
           <mwg-rs:Regions rdf:parseType="Resource">
              <mwg-rs:RegionList>
                 <rdf:Seq>
                    <rdf:li rdf:parseType="Resource">
                       <mwg-rs:Area rdf:parseType="Resource">
                          <stArea:y>0.363000</stArea:y>
                          <stArea:w>0.042000</stArea:w>
                          <stArea:x>0.969000</stArea:x>
                          <stArea:h>0.056000</stArea:h>
                          <stArea:unit>normalized</stArea:unit>
                       </mwg-rs:Area>
                       <mwg-rs:Type>Face</mwg-rs:Type>
                       <mwg-rs:Extensions rdf:parseType="Resource">
                          <apple-fi:AngleInfoYaw>90</apple-fi:AngleInfoYaw>
                          <apple-fi:AngleInfoRoll>0</apple-fi:AngleInfoRoll>
                          <apple-fi:ConfidenceLevel>99</apple-fi:ConfidenceLevel>
                          <apple-fi:Timestamp>2147483647</apple-fi:Timestamp>
                          <apple-fi:FaceID>3</apple-fi:FaceID>
                       </mwg-rs:Extensions>
                    </rdf:li>
                 </rdf:Seq>
              </mwg-rs:RegionList>
              <mwg-rs:AppliedToDimensions rdf:parseType="Resource">
                 <stDim:h>2448</stDim:h>
                 <stDim:w>3264</stDim:w>
                 <stDim:unit>pixel</stDim:unit>
              </mwg-rs:AppliedToDimensions>
           </mwg-rs:Regions>
        </rdf:Description>    </rdf:RDF> </x:xmpmeta> ���                                                                                ��f���"���  }!1AQa"q2���#B��R��$3br�
  %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�������������������������������������������������������������������������
  w!1AQaq"2�B����   #3R�br�
  $4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������?�ʌ�>c�����E��rw(f���?��������tų�-���)��|1��I'�sԓֿ��$�E�VzrK���J���})�-�(T�����W��&�g�rX������O����,���8�=^}�:i�\�.�=,#7����F9Páǵ6�
  ��'�^��z�sڸ$�u$;Uq�   <��?Z�|O�7�d�S����{�J�%��'I��8#~���#P�w!olᏵr��m�X�w
  �?ʬ�.;��7�:u�U-F�e"�լW�
  W�y��*�S��j��8n*A�Ar|�8#�;3�,o��
  VR�Tb������^M��en?&<:�R���7���Ӟ��7��4ۘ�wj�w1��ҹ{�-[D�w�/p�����;u�)�<ێN���
  B
  ?w���Z�ݦŊ>���j��J��֗Kk�Zб�T$��ǽz}��g}�h������ʄ�Ԫ-��$�̅����_lV�%L�By��:�k��Ԥ�DP6���Ҷ���؟ְt�c~uc�Yp[<r}ju�>�Fx�Z�K�Qx�?/l�T�j
  �gPx�)J�� F�� 6�Q���FNy�G���ݿ0�� G��&���U�)#aT�w��6�IsYGGv�����
  �݀I���ϵ,Nܠ���? ����z��>��f)�Nr�듁�֩l�m�h��G?�K��9� ��B6
  �1���S!2Iԃ������I�)���X�����x��R��Q��T�p9�X��oz3F���5��8�f
  ���2��w㊢���[�Lո�á���j$
  ��g�X�9䵹F����F?�b^h�x���W��[��y�;r3׾i2T�=�q�{�Y������{�����t�F�#X7�
  �������v���p)XpA��K�
  |d��|[�Ml|G�k��.!#���x\�6wDs���s�Ѕ�[���\&�t'���W�x����i�Z�k�����β(ttaʺ�AZ���  �/NZ��>{6�#Y�Gs����(��O?��ݍJ��sk&���������  $�b+<�{��R
  q�9� �߱���
  ���G�y06�^KX2���9h���|q�0,����}�t˘`�|h�ki�r�ޕ��n��z4w�����KR���Q��/:M�h�

��P�'��}�l�*Պ��e�x'3�=�\���2��n�h����q����Z�W�nؠdu�;����:��s�-�$���7�y�����E�jR'�1��?:�,Rl��1�g
    sϥ2ʋ�@R v���u����{X�s��}m�%�@bxR\z���f��S �X�X3���

A: @Phil 's comment showed me I was way over complicating the situation. I created the url in the angular controller and used that in the ng-src. I removed the service completely and it works great.

A: Your response format above is not a base64 code, so there is now way it will be rendered as the image. Even if you try to encode your response content into base64 content, it still won't work. Please check what is stored on the server side and what is being returned.


text:
Q: Spark ml basic operation in Java I have Dataset <Row> dataset; and want to perform some basic operation on it.
For Example:- Suppose I have 3 columns "Id","Name","Age"
and data for these columns. I want to perform these below operation on this dataset based on Name column
[1] Remove white space from Name column
[2] Remove number  from Name column
[3] Remove special character from Name column
I am using java8, Apache-Spark and Apache-Spark-ml library
Please suggest best way to do this.

A: Use regexp_replace() to replace whitespaces, numbers & special characters. (Essentially retain only letters).
List<Row> rows = new ArrayList<Row>() {{
    add(RowFactory.create("validName"));
    add(RowFactory.create("name with whitespace    "));
    add(RowFactory.create("name with numbers 1234"));
    add(RowFactory.create("name with special chars !@#$%"));

}};

StructField[] structFields = new StructField[]{
        new StructField("Name", DataTypes.StringType, false, Metadata.empty()),
};

//create sample data
Dataset<Row> input = spark().createDataFrame(rows, new StructType(structFields));
input.withColumn("cleanedName", functions.regexp_replace(functions.col("Name"),"[^a-zA-Z]+", "")).show(100, false);

cleanedName column has the expected values:
+-----------------------------+--------------------+
|Name                         |cleanedName         |
+-----------------------------+--------------------+
|validName                    |validName           |
|name with whitespace         |namewithwhitespace  |
|name with numbers 1234       |namewithnumbers     |
|name with special chars !@#$%|namewithspecialchars|
+-----------------------------+--------------------+


text:
Q: Where should I call initialization code in Phoenix, which might involve connection to a db? I have some code which I need to call upon my Elixir Phoneix application startup. Some of the  parts of the code require a request to database to retrieve data that'll be used for initialization.
While I can call normal code -- one which doesn't do any requests to a database -- in
defmodule MyAppWeb.Endpoint do
  # [............]

  #
  # some of my init code will go here
  #

  def init(...) do
    # [.........]
  end
end

and if I understand correctly, code that does database, HTTP requests or something like that -- something that may take a lot of time -- shouldn't be called from MyAppWeb.Endpoint
Is this correct? If so, from where then I should such code that does initialization?

A: In the first place, don't put the code, unrelated to Phoenix itself, into its helpers.
Create your own GenServer, do whatever you need, and stop it gracefully.
There are three stages of GenServer initialization process:

*

*GenServer.start_link/3

*GenServer.init/1

*GenServer.handle_continue/2
The first one is executed in the calling process, two last are callbacks, executed in already started GenServer process, init/1 synchronously and handle_continue/2 asynchronously.
That said, the common practice to perform a long-running initialization would be:
defmodule MyInit do
  use GenServer

  @spec start_link(opts :: keyword()) :: GenServer.on_start()
  @doc "Starts the GenServer process"
  def start_link(opts \\ []) do
    GenServer.start_link(__MODULE__, ..., name: __MODULE__)
  end

  @impl GenServer
  @doc false
  def init(:ok),  do: {:ok, :ok, {:continue, :connect}}

  @impl GenServer
  @doc false
  def handle_continue(:connect, :ok) do
    do_init(...)
    {:stop, :normal, nil}
  end
end

And start this process from your supervision tree.

If it's critical for this initialization to complete before the endpoints are started, move the call to do_init into init/1 callback and put this GenServer before the endpoint in the supervision tree.


text:
Q: Spain's comeback In Sid Meier's Pirates when you capture all of the cities away from Spain there is a problem. Spain no longer exists. I can't attack my fellow men.
How can Spain once again have a foothold in the Spanish Main? Do Invasions come out of towns?

A: So far, I haven't seen an invasion force originating from a Settlement and I'd be surprised to see that happen.
However, you can aggravate a single city by capturing several of their nation's ships going to or leaving from that port. If it takes too long, you can raise their anger by pelting their fortress with shots on the world map. To do so, hit "Space" to shoot at their fortress when you are close to the city.
Soon the port's fortress will take shots at you, meaning that the city has started treating you as an enemy, allowing you to attack it. Once you capture the city and your troops sufficiently outnumber the remaining defenders you may install a Spanish viceroy as the new Governor, giving Spain a new foothold in the colonies.
Note that, both, the ship blockade and the bombardment, reduce the wealth of the city.

A: I haven't played in a while, but I ran into this exact thing a long time ago. My solution was to reinstate the Spanish Empire by conquering another port (I was fighting for the English, and we were also at war with the French at this point) that was French and reinstating a Spanish Governor, because it gave me the option of what country's banner I wanted to install. Using this method, I was able to reinstate the Spanish Empire, but because I was conquering cities for the Spanish, I quickly gained reputation there and ended up becoming a Count or something...
I know the newer version of Pirates! now has settlements, which I have seen can spontaneously generate a colony of any nationality, so I would think that given a weak enough port, the settlement could in theory capture the port, thus returning a nearly extinct empire to the map. I've not yet seen that exact thing happen, but I would only assume it's possible given I've received news that cities have been captured (ie changed flags) without my intervention at times.


text:
Q: i want to round up values like 124.33 to 124.50 and 124.57 to 125.00 in C# if doublevalue = 124.75 then it shoud be rounded to 125.00
if doublevalue = 124.25 then it shoud be rounded to 124.50
in short after decimal point digit greater than 50 must rounded to 100 and less than 50 should rounded to 50
please help me get this type of code

A: Simply do the following:
Math.Ceiling(YourValue * 2)/2

Explanation
Suppose your number can be written as X + Y, where X is the integer part and Y is the fractional part. Multiplying it with 2 will make it 2X + 2Y, where 2X will be an even number, double of the integer part. For Y, there are two cases:

*

*If Y >= 0.5, 2Y will be equal to 1 + Z (where 0 <= Z < 1), thus the entire number will be 2X + 1 + Z.

*If Y < 0.5, 2Y will be equal to Z (where 0 <= Z < 1), thus the entire number will be 2X + Z.

Doing Math.Ceiling() in the first case will return 2X + 2 and dividing it by 2 will return X + 1, which is the nearest higher integer, (3.7 will become 4).
Doing Math.Ceiling() in the second case will return 2X + 1 and dividing it by 2 will return X + 0.5, or X.5 , (3.3 will become 3.5).

A: your conditions are not clear from your question, but the principle is to isolate the digits after the decimal point and that decide what to do:
private static double GetFixedNumber(double n)
{
    var x = n - Math.Floor(n);
    double result = 0;

    if (x >= 0.75)
    {
        result = Math.Floor(n) + 1;
    }
    else if (x >= 0.25)
    {
        result = Math.Floor(n) + 0.5;
    }
    else
    {
        result = Math.Floor(n);
    }

    return result;
}

A: Or compute it yourself:
    // flipped the decision around - else it is kindof the same.
    static double WorksAsWell(double input)
    {
        var floored = Math.Floor(input);

        if (floored == input) // special case so exact 127. stays that way
            return floored;

        if (input - floored >= 0.5)
            return floored+1;

        return floored+0.5;
    }

    static double RoundToHalfesOrFulls(double input)
    {
        int asInt = (int)Math.Floor(input);
        double remainder = input-asInt;

        if(remainder < 0.5)
            return asInt+0.5;

        return asInt+1.0;
    }

    public static void Main()
    {
        for(int i= 12700; i < 12800; i+=5)
            System.Console.WriteLine(string.Format("{0} = {1}",i/100.0, RoundToHalfesOrFulls(i/100.0)));
    }
}

Output: (RoundToHalfesOrFulls)
127 = 127
127.05 = 127
127.1 = 127
127.15 = 127
127.2 = 127
127.25 = 127
127.3 = 127
127.35 = 127
127.4 = 127
127.45 = 127
127.5 = 127.5
127.55 = 127.5
127.6 = 127.5
127.65 = 127.5
127.7 = 127.5
127.75 = 127.5
127.8 = 127.5
127.85 = 127.5
127.9 = 127.5
127.95 = 127.5

A: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            Console.WriteLine( RoundUp(124.25, 2));
        }
        public static double RoundUp(double input, int places)
{
    double multiplier = input*2;
         double numberround  = Math.Round(multiplier, MidpointRounding.AwayFromZero)/2;

     return numberround;
}
    }
}


text:
Q: Jenkins Maven Job Charset I'm using Spring Test to test my Spring Application, which is basically a REST webservice that serves JSON and some other uploaded media.
The unit tests are working fine in all developer's machines, and some of them tests for strings returning inside the JSON responses, and a little subset of them tests special characters.
The application is completely configured to use UTF-8 with everything, however the JSON response is returning with the wrong charset, so the test fails.
I tried to configure on /etc/default/jenkins the following line:
JAVA_ARGS="-Djava.awt.headless=true -Dfile.encoding=UTF8"
But I still get the same result.
I also had the chance to see what Charset.defaultCharset() was, when running a particular test... And it appeared something like US-ASCII...
Can someone please tell me what am I doing wrong?

A: I found out what was wrong.
In my Spring Test configuration, I was reading a DML.sql file to create initial test data, and the line that initialized the database was like this:
<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="classpath:sql/DML.sql" />
</jdbc:initialize-database>

That left my configuration dependent from the server charset, and in my case I had that weird "US-ASCII" set in my server.
I made it independent by setting the encoding attribute to UTF-8:
<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="classpath:sql/DML.sql" encoding="UTF-8" />
</jdbc:initialize-database>

So the values that came from the H2 database could be tested against values with special characters.


text:
Q: How can i Start this CSS animation? i have this css animation code that just need to start animation in name order to make spin, but i dont know how can i do it !
the order should be opacity-48-25-0-3; opacity-48-25-1-3; opacity-48-25-2-3;

body {
  background-color: black;
  -webkit-backface-visibility: hidden;
}
.spin {
  right: 130px;
  top: 66px;
}
.spinner {
  position: relative;
  width: 0px;
  z-index: 2000000000;
}

JSFiddle : https://jsfiddle.net/nk0ec8ax/

Thanks for your Help


text:
Q: Visual Studio getting 'InvalidProgramException' when making changes while debugging I've been using Visual Studio 2010 for years now. I have a fairly complex VB.net project that I routinely make changes to. Recently, whenever I'm making changes in debug mode, it throws a System.InvalidProgramException - Common Language Runtime detected an invalid program error which forces me to stop running the program and then restart it again after I've saved my changes.

*

*This issue only happens when I make changes to a Sub or Function which is called by another Sub or Function. For example, if I make a change to a button click event, it's fine, but if I make a change to a function that button calls, it errors.

*A change as simple as adding blank lines in my code will cause this to happen. No code change at all...just literally hitting return to add blank lines between code lines.

*I installed Visual Studio 2013 thinking it would solve this. It does not. I still get the same errors.

*I tried moving my project files to a different HDD, I still get the same errors.

*I thought maybe I have corrupt memory, so I ran a full checkdisk and defrag but I still get the same errors.

*I've read where this error may happen with very large procedures or projects with lots of variables (although I thought this was fixed in newer .NET versions) so I've cleaned up my code. The largest Module has 30k lines.

The workaround is to stop the project running, save my changes and then restart it...however, that takes time because my program has to reinitialize everything when it runs, so I'd prefer to be able to make changes while debugging.
Also, I have .NET framework 4.5 installed
Update: I loaded up a backup of my code from a month ago and it runs fine...so apparently some recent changes I've made are causing this error. Once I figure out what's changed, I'll update this just for future reference in case anyone else runs into the same issue.