text:
Q: Getting an InvalidDataException extracting .zip file in Windows Store App with ZipArchive I am working on a Windows Store app proof of concept that will open a .zip file and extract the contents to an app-specific Roaming folder. I have looked into several popular libraries to extract the contents only to find that these libraries don't support Windows Store apps (at least not yet). So, I have decided to go with ZipArchive. I have the following code in a button click handler:
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    var fileOpenPicker = new FileOpenPicker();
    fileOpenPicker.FileTypeFilter.Add(".zip");
    var openedFile = await fileOpenPicker.PickSingleFileAsync();

    var booksFolder = await Windows.Storage.ApplicationData.Current.RoamingFolder.CreateFolderAsync("Stuff", CreationCollisionOption.OpenIfExists);
    var folder = await booksFolder.CreateFolderAsync(openedFile.Name.Replace(".zip", string.Empty), CreationCollisionOption.ReplaceExisting);

    using (var stream = await openedFile.OpenStreamForReadAsync())
    {
        using (var zip = new ZipArchive(stream, ZipArchiveMode.Read))
        {
            foreach (var entry in zip.Entries)
            {
                using (var entryStream = entry.Open())
                {
                    var file = await folder.CreateFileAsync(entry.Name);
                    using (var decompressedStream = await file.OpenStreamForWriteAsync())
                    {
                        using (var deflateStream = new DeflateStream(entryStream, CompressionMode.Decompress))
                        {
                            await deflateStream.CopyToAsync(decompressedStream, (int)entry.Length);
                        }
                    }
                }
            }
        }
    }
}

However, I get an InvalidDataException on the line
await deflateStream.CopyToAsync(decompressedStream, (int)entry.Length);

Here's the details of the exception:
System.IO.InvalidDataException was unhandled by user code
  HResult=-2146233087
  Message=Unknown block type. Stream might be corrupted.
  Source=System
  StackTrace:
       at System.IO.Compression.DeflateStream.EndRead(IAsyncResult asyncResult)
       at System.IO.Stream.<BeginEndReadAsync>b__e(Stream stream, IAsyncResult asyncResult)
       at System.Threading.Tasks.TaskFactory`1.FromAsyncTrimPromise`1.Complete(TInstance thisRef, Func`3 endMethod, IAsyncResult asyncResult, Boolean requiresSynchronization)
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.IO.Stream.<CopyToAsyncInternal>d__2.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
       at POC.MoviePlayer.GroupedItemsPage.<Button_Click_1>d__4.MoveNext() in c:\Users\Brent\Documents\Visual Studio 2012\Projects\POC.MoviePlayer\POC.MoviePlayer\GroupedItemsPage.xaml.cs:line 108
  InnerException:

The .zip file I am trying to import was created with Windows Explorer's Send To Compressed (Zipped) Folder option. I have also tried to create a .zip file in code, using ZipArchive, but I get more exceptions with that code too. Since that isn't my ideal use case anyway, I won't include my code to create the .zip unless it turns out to be useful to somebody.
I am hoping somebody can either see the error of my ways in the code above or provide a link to a solid library to work with zip files that is preferably open source. This frustrated developer would be very grateful for any help.

A: You don't have to decompress the result of entry.Open(). It is already decompressed.
You could also use ZipFileExtensions.ExtractToDirectory (http://msdn.microsoft.com/en-us/library/system.io.compression.zipfileextensions.extracttodirectory.aspx) to simplify your code.


text:
Q: how to enable oraoop for sqoop 1.4.6 I am using sqoop 1.4.6 and Oracle 11g with ojdbc6 driver.
I wanted to know since oraoop is built in sqoop 1.4.6 then why do I get this info in the log while running a sqoop job.
INFO oracle.OraOopManagerFactory: Data Connector for Oracle and Hadoop is disabled.
My job successfully runs but I know that oraoop connector is faster than just JDBC. How do I enable oraoop?
Thanks

A: If '--query' argument is specified in place of '--table' parm, Oraoop connector is not used.
Also check if oraoop is configured for correctly:

*

*download/check - oraoop-version.jar file available at $SQOOP_HOME/lib

*create/check - oraoop-site-template.xml file available at $SQOOP_HOME/conf

*check/add - oraoop file at available at $SQOOP_HOME/conf/managers.d
Detailed configurations steps are explained:

*

*configure_the_data_connector_for_oracle_and_hadoop

*oraoop user guide and oraoopuserguide_1.6

*confirm_the_data_connector_for_oracle_and_hadoop_can_initialize_the_oracle_session

A: Oraoop connector is an internal utility of sqoop from version 1.4.6, so for oraoop to be invoked your sqoop command must be oraoop specific.
For starters your sqoop command cannot contain --query tool as oraoop doesn't supports that, apart from that oraoop is only invoked for more than one mappers.
If you are doing all these things right then you can try two more things:

*

*Using the --direct option

*Use this with your oraoop query -D oraoop.disabled=false
A sample working oraoop query is :
sqoop import --connect jdbc:oracle:thin:@127.0.0.1:1521:XE --username ROOT --password manager --table temp --target-dir /sqoop/tmp1 -m 3

A: You need to specify the --direct parameter if I remember correctly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get access to global variable in template? I want to create global object with settings which I need to get from REST API. I need to make one request to REST API and get settings and after that I want to get access to these settings from any controllers and from any templates. What can you advice, what is the best practice for that problem?

A: Concept
Good practice would be to use initializers. They allow injection of any data to routes, controllers or any other kind of object.
Lets take an example ( example from Ember.js official site )
1 . You have an Application and you have a logger service like this -
App = Ember.Application.extend();

App.Logger = Ember.Object.extend({
  log: function(m) {
    console.log(m);
  }
});

2 . Now you want to have this function log to available on all routes like this -
App.IndexRoute = Ember.Route.extend({
  activate: function(){
    // The logger property is injected into all routes
    this.logger.log('Entered the index route!');
  }
});

3. Tell ember to inject an object named Logger to all routes. Use initializer Like this
//I want to inject something
Ember.Application.initializer({

  //this dependency name is logger
  name: 'logger',

  //whenever ember runs
  initialize: function(container, application) {

    //register my logger object under a name
    application.register('logger:main', App.Logger);

    //and use this service 'logger' in all 'routes'
    application.inject('route', 'logger', 'logger:main');
  }
});

With this you can have your application level data / code available in all routes and controller.
Once you get your data in controller you can use it in templates pretty easily.
How to make API call with initializers ??
Initializer can be used to run after some other services has been resolved. Like in our case store. store is the object we need to make API call to server in good way (We can use $.getJSON() or anything else no issues)
Tell the initializers to run after store loaded
//I want to inject something but only after store resolved
Ember.Application.initializer({

  //this dependency name is logger
  name: 'logger',

  //wait for store object to be loaded, we need it to make API call
  after : 'store',

  //whenever ember runs
  initialize: function(container, application) {

      //grab the store object from container
      var store = container.lookup('store:main');

      //now you the store make that API call
      self.store.find('user',{current:true}).then(function(data){

            //we have the data we can inject it
            data = data.get('firstObject');
            container.lookup('controller:base').set('user', data);

            //user lookup success
            console.log("We have found an user. Yeah ember rocks.");

       });
   }

});

A: The settings object you are describing should probably live inside ApplicationRoute's model hook. You can then retrieve it in all your other models by saying modelFor('application') (see here). There is also a needs API (see here) that lets you share stuff between controllers in the application.


text:
Q: Zoom out viewport I'm trying to do a zoom out on the viewport to .8 for heights bellow 1080.
So far I've done this:
HTML HEAD
<meta name="viewport" content="width=device-width, initial-scale=1" />

CSS
@media screen and (max-height:1079px){
    @viewport {
        width: device-width;
        zoom: .8;
    }
}

No prefix since I'm using firefox to test it.
Any ideas?
Thanks!

A: Since you mentioned Firefox, the problem is that Firefox, as of versoin 37, does not support the @viewport at rule. Since Firefox has a unresolved bug on the issue from 2012, you might want to try an alternative such as reducing font-size to .8em.
If you check the Firefox console, you will see this css error:


text:
Q: How to organize work between 2 git repos? We have a setup where we internally use git to do our work and at the same time the client we deliver the work to also uses git on their own.
We also want to have a strict border between 2 repos so that client is not involved into our repo workflow (internal issues, users, PR policies, etc) nor we want to be involved into their.
We are considering workfow like this:

*

*Our devs do all their work against our-repo in development branch (set as default)

*Our repo admin has access to client-repo (meaning he has 2 remotes: our-repo and clients-repo)

*Once something is ready to deploy (meaning, is pushed to our master branch) he gets it and push it to clients-repo

*In case client themselves do some changes (rare but possible), our admin gets it and merge to our-repo
Would this setup work? Am i missing anything important?
Are there any better alternatives?

A: I think that having two separate repos which both contain logically the same (or at least very similar) code is unnecessary, and a generally bad idea.  I suggest that you just maintain a single repo.  Make the master branch (and possibly other branches) protected in GitHub.  You may read Enabling branch restrictions for more information on how to do that.
When your clients want to do their own work, simply let them create a new feature branch.  If they want, they may create a pull request back to master, which you and your internal team can carefully review, before merging.  Since master would not be protected, your client would never have the direct ability to alter the codebase.

A: I see github.com's permission matrix at https://help.github.com/articles/repository-permission-levels-for-an-organization/
Your wish can not be reality, if our team and our client use github.com in same time (let see matrix at row Open issues, pull, etc.)
I have an idea

*

*Our team use github.com service

*Our client use a git mirror repository (not on github.com) https://help.github.com/articles/duplicating-a-repository/
Therefore, our client cannot see pull request process, issue, issue discussion, etc. they only see source code what our team deliver to them.


text:
Q: unable to install python 3.6 on linux I run below commands after unzipping that python 3.6 tar.xz file.
./configure
make
make install

Error log:
ranlib libpython3.6m.a
gcc -pthread   -Xlinker -export-dynamic -o python Programs/python.o libpython3.6m.a -lpthread -ldl  -lutil -lrt   -lm
if test "no-framework" = "no-framework" ; then \
        /usr/bin/install -c python /usr/local/bin/python3.6m; \
    else \
        /usr/bin/install -c -s Mac/pythonw /usr/local/bin/python3.6m; \
    fi
/usr/bin/install: cannot create regular file `/usr/local/bin/python3.6m': Read-only file system
make: *** [altbininstall] Error 1

When i run ./configure followed by make , and then make install i run into this error!

A: Have you tried running the above commands using sudo powers?
original answer: https://askubuntu.com/q/865554/667903
sudo make install
or
If you are using Ubuntu 16.10 or 17.04, then Python 3.6 is in the universe repository, so you can just run
sudo apt-get update
sudo apt-get install python3.6

A: Your filesystem seems to be read-only. You have to remount the partition where /usr/local/bin/ is located with write permissions
The syntax for mount is
mount -o remount,rw /partition/identifier /mount/point

Let's say you have / on /dev/sda2
mount -o remount,rw / /dev/sda2

should fix your problem.
To check your mount points:
cat /etc/fstab or df
To check the permissions:
cat /proc/mounts

A: Try after installing build essentials whic contains compilers,package dev tools and libs:
sudo apt-get install build-essential


text:
Q: Included file thinks its in the root, while its in a sub folder I'm using the latest version of CodeIgniter. In my application I have to include a PHP file, like 'example.php'. I really need this file, because rewriting it to CI would take to much time. The include is just used, to include some old stuff in a frame.
The point: The include works fine, but the included file thinks its in the root while its really in a sub folder.
The file should be in:  foo/bar/example.php.
Nevertheless the file actually works, but in that file I also have to include other files.
Things tried:

*

*Including the includes in the example.php via the base url (rather than ../../secondInclude.php)

*At that point it can find the second include, but it gives a big browser error (lost connection to the server);

*Tried PHP chdir, but gave the same result as point 2.

I'm not sure if its a CI problem, or my server (IIS7) or something else.

A: When including a FIle Look at the root index.php file
// Path to the system folder
define('BASEPATH', str_replace("\\", "/", $system_path));

// Path to the front controller (this file)
define('FCPATH', str_replace(SELF, '', __FILE__));

// Name of the "system folder"
define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));

 // The path to the "application" folder
 define('APPPATH', $application_folder.'/');

so if the file you want to include is inside  application/ directory
use APPPATH.'path/to/file'.EXT;
Another Example
suppose you created a new file in a new directory inside application directory;
application/custom_folder/custom_file.php
to include this file you need to determine where your file is located,
then use the PATH defined above.
so to include you must use
APPPATH.'custom_folder/custom_file'.EXT , the .EXT is just PHP

A: Suppose your included files are kept in includes folder in views
then you can easy to include that files with:
$this->load->view('includes/example.php');

works like
include 'includes/example.php'; // in Core PHP


text:
Q: MVC C# activation url redirects to other path I have code that i used a year or two ago to create an activation link that is send by email, using a code as a parameter, i tried so many different ways, encoding, using other syntax, adding web.config settings <pages validateRequest="false" />
requestValidationMode="2.0"
, annotations [AllowHtml], literally tried dozen of post on the internet but none of them worked.
So i am overseeing something here, that i am sure but i can't find the solution.
The error i get is:
    A potentially dangerous Request.Path value was detected from the client (?)
The format i use is
Url.Action("action","controller", new { Id = guidValue }, Request.Url.Scheme)
My routing is the Default so this should work.
The Url is like this in the address bar once clicked:
http://localhost:52641/Account/Login?ReturnUrl=%2FAccount%2FAccountActivation%2F%3Fid%3Dfc39f53f-6fa7-43d2-b30a-8b4e20f0f237

While it should give me:
http://localhost:52641/Account/AccountActivation?id=fc39f53f-6fa7-43d2-b30a-8b4e20f0f237

What is happening here?
Thank you for any feedback!

A: I removed the complete built in Authentication (NuGet packages & classes)
from my solution (since i didn't needed them) and this made the above case work as it was. I can't elaborate more on the what's and how's (i am sure other people can) but i think it has to do with routing that comes with the authentication.


text:
Q: begin() and end() for STL algorithms I have a class whose data container is backed by an array, and I have the following implementations for begin() and end().
template <size_t size>
double * MyContainerClass<size>::begin(){
    return std::begin(mContainer);
}

template <size_t size>
double * MyContainerClass<size>::end(){
    return std::end(mContainer);
}

In other member functions, I am attempting to use begin() and end() for STL algorithms such as std::transform and std::copy. When const objects are passed as parameters to these member functions, I encounter the error:

error: passing 'const MyContainerClass<size>' as 'this' argument discards qualifiers.
  note: in call to 'double* MyContainerClass<size>::begin() [with unsigned int size = size]'

Is this caused by incorrect begin() and end() implementations?
std::copy(begin(), end(), someOutputIterator);

A:
Is this caused by incorrect begin() and end() implementations?

Yes, you need const versions of the functions. For example:
template <size_t size>
const double * MyContainerClass<size>::begin() const {
    return std::begin(mContainer);
}

A: The important word here is 'const': You need to provide additional const versions of your begin() and end() functions, that return const double*.
If you are using C++ 11, you may also want to provide cbegin() and cend().


text:
Q: ReasonPhrase: 'Forbidden' HttpResponseMessage winrt i'm getting this error :ReasonPhrase: 'Forbidden' in the response variable:
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(uri);
string result = await response.Content.ReadAsStringAsync();

besides i used it with an other url and it works fine ! any ideas please?


text:
Q: hibernate map> I have the following tables:
@Entity
@Table(name = "events")
Event
    --id
    --name

@Entity
@Table(name = "state")
State
    --id
    --name

@Entity
@Table(name = "action")
Action
    --id
    --name
@Entity
@Table(name = "state_event_action")
    StateEventAction
--id
--state_id
--event_id
--action_id

I would like in state class to get map<key, set<value>> of Map<Event, set<StateEventAction>>
How can I do it in Hibernate?

A:
I would like in state class to get map<key, Set<value>> of Map<Event, Set<StateEventAction>>

Hibernate does not support collection of collections such as List of Lists, Map of Sets, etc out of the box. But you could implement your own UserCollectionType to add support for this kind of data structure. This blog post shows how to do so  using the MultiMap implementation from Apache commons.
My suggestion would be to use a similar approach, but maybe to prefer the generified Multimap from Google Guava.

A: If you want to recieve Map of sets, it means that there are several actions for each (state_id, event_id) actions. So you have wrong entity's mappings. It should be
@Entity
@Table(name = "state_event_action")
StateEventAction
--id
--state_id
--event_id
--Set<action> actions

In this case you can write :
@Entity @Table(name = "state")
State
    --id
    --name
 Map<Event,StateEventAction> eventActions;

A: You will probably need to first query all the StateEventAction objects for the state then write your own code to first create a set for the event if not already created then add the StateEventAction obejct to the set.
State state = // < the state object;
Query q = Session.createQuery("from StateEventAction sea inner join fetch sea.event where sea.state = :state");
q.setEntity("state", state);

Map<Event, Set<StateEventAction>> map = new HashMap<Event, Set<StateEventAction>>();

for(Iterator itr = q.list().iterator(); itr.hasNext();) {
   StateEventAction sea = itr.next();
   Event event = sea.getEvent();
   Set<StateEventAction> theSet = map.get(event);
   if(theSet == null) {
      theSet = new HashSet<StateEventAction>();
      map.put(event, theSet);
   }
   theSet.add(sea);
}


text:
Q: Datetime difference between two columns without counting the full 24 hours here are two really useful questions for datetime comparison in python:
Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes
Determine the difference between two DateTimes, only counting opening hours
I have a dataframe in python with two columns:
A                      B
10:00:00 01.01.2019    12:00:00 02.01.2019

And I have opening hours (which are relevant hours), which only should count for the calculation, so not the full 24 hours and maybe not every day. So my business would be open from: 10:00:00 - 18:00:00 every day, how can i adjust:
df_time['td'] = df_time['B']-df_time['A']

That the outcome would be 10 hours in this case? And it is open from monday to friday.

A: Not a full answer, but I would do:

*

*Count the time in the first day 18:00:00 - df['A'].dt.time

*Count the time in the last day  df['B'] - 10:00:00

*Count the day in between and multiply by 8.


text:
Q: Is there a way to implement Python's join() in C++? I am trying to port some feature from my password manager into c++ , but however I would like if its way to port this line of python to c++ equivalent. I wish to implement at least close to this 2 lines of code to c++
t = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
key = ''.join([secrets.choice(t) for _ in range(20)])

#include "common.h"
#include <iostream>

std::string Common::ascii_lowercase() {
    std::string ascii_lowercase;
    for (char c = 97; c <= 122; c++)
        ascii_lowercase += c;
    return ascii_lowercase;
}

std::string Common::ascii_uppercase() {
    std::string result;
    for (char c = 65; c <= 90; c++)
        result += c;
    return result;
}

std::string Common::digits(){
    std::string digits;
    for (int i = 0; i <= 9; i++) {
        digits += std::to_string(i);
    }
    return digits;
}

std::string Common::punctuation() {
    std::string punctuation;
    for (int i = 33; i <= 47; i++)
        punctuation += i;
    for (int j = 58; j <= 64; j++)
        punctuation += j;
    for (int z = 91; z <= 96; z++)
        punctuation += z;
    return punctuation;
}

A: You can create a function join() that will take your sequence and the separator you want to use and return the same that the python method does.

Example:
std::string join(const std::vector<std::string> & sequence, const std::string & separator)
{
    std::string result;
    for(size_t i = 0; i < sequence.size(); ++i)
        result += sequence[i] + ((i != sequence.size()-1) ? separator : "");
    return result;
}

You can use it as follows:
std::vector<std::string> seq {"One", "Two", "Three", "Four"};
std::cout << join(seq, "--") << std::endl;

the output will be:

One--Two--Three--Four

Of course, you can use an other container than std::vector, it is just an example.
I hope it will help you.


text:
Q: In Android Studio, how do I create a folder for project documentation? In Eclipse, I had some folders in the project root that were not code - containing text files with notes about the project, Photoshop files for artwork and so on.  Having migrated to Android Studio, these extra folders in the project root are not visible in the Project navigation pane - I only see the app folder and Gradle Scripts.
Is there some way to create a non-code folder that is visible in the Project pane but that is outside the app module?
I thought "Create New Module" in the Project Structure dialogue might do it, but it only offers me templates for modules that contain Android code.
--- EDIT ---
Thanks to @SvdTweel's answer I've stumbled across something that seems to do what I want:

*

*switch to the Project view

*create the documentation folder in the project root

*right-click it and select Mark Directory as>Resources Root

*switch back to the Android view and you see a new folder named "resources"

Will this have any adverse effects?  Is this folder still ignored when building the app module?

A: In the Project Structure you can switch from Android to Project.
The default Android view structures and minimalizes the directories and files so that you as a developer can easier navigate through your project.
The Project view shows everything just as you would see when you browse it with your file explorer on your OS.
I think that is what you search for to create files and directories in the root of the project.

A: You can put the doc files in the test/resources folder. This is clumsy, but it makes them visible in the Android view while keeping them out of the build.
Bonus: code completion when editing Markdown code samples using the JetBrains Markdown plugin.


text:
Q: Manually Trigger EJB Schedule for testing I have a Method annotated with javax.ejb.Schedule:
@Schedule(minute = "00", hour = "23")
public void dailyTask()

It works perfectly, but for end-to-end testing purposes, I want to manually trigger this method, ideally without code changes.
I googled, searched for MBeans in JVisualVM but was not successful. Is this possible? How?

A: Just an idea: you could inject this component into your testcase to call this public method manually, e.g. like this (untested):
@Singleton
public class YourClass {
    ...
    @Schedule(minute = "00", hour = "23")
    public void dailyTask() {
        ...
    }

public class YourTestClass {
    @EJB
    private YourClass yourTestClass;
    ...
    void someTestMethod() {
        yourTestClass.dailyTask();
    }


text:
Q: Drupal 6: how to make CCK default values translatable? In my multilanguage Drupal 6 website I need to make my CCK field default values translatable, i.e.

*

*Hello - in the English version

*Bonjour - in the French one

I cannot find this text with Translation Table, neither are these values in variable table so that I can use multilingual variables.
Do You know how to have different default values in different languages?

A: This method is a bit of a hack. Im not sure I would deploy this without really considering the consequences. For a simple usecase it MIGHT be ok.
Create a custom module, lets say def_translate. To def_translate.module, add a function
function def_translate_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if($node->type == "sometype"
        && $op == "load"
        && $node->field_some_cck_field_type[0]['value'] == "your default value")
   {
      $node->field_some_cck_field_type[0]['value'] =
              t($node->field_some_cck_field_type[0]['value']);
  }
}

Ok - so what is this doing?
When a node is loaded, hook_nodeapi gets called, with $op set to "load". This gives us an opportunity to do manipulate the node before it is rendered. Before we do anything we check

*

*Is this the right type of node?

*Is our op = "load"?

*Is the value our default value?

What we then do is pass the existing default value through the t() function. This will make the default string available to i18n translation table, and you can then use the normal way of translating strings.
*DISCLAIMER*
I have not tested this myself in production. Im not entirely sure what the effects will be. You probably want to think this through before implementing it, and you probably want to put some features in to look up the default values from the DB incase they are changed in the CCK UI.
Hope this helps - or possibly shakes a hint of a solution to your problem!

A: When you define the CCK field, you can enter a PHP code snippet to override the default value of the field.
Enter the following there :
return array(0 => array('value' => t('Hello')));

Now access a node add page with this CCK field from a non-English version so that it gets added to translatable strings.
Now you're able to translate it using the "Translate interface" menu (it might take a visit to the "create" page of your cck type first though). It doesn't require any extra modules in fact, just basic D6 (and it probably works in D5 and D7 as well).


text:
Q: How to workaround a bug in SVG rotation CSS on Chrome 73? I use a SVG image that mimics the Google loading animated icon:
After installing Chrome 73, the rotation of the SVG became erratic.
Please see this code:

https://codepen.io/grudnitzki/pen/LavYWK
In Firefox and Edge the rotation still works fine.
Any workarounds?

A: Maybe it's a bug of new chrome version. You should report it to google. For now, to fix your problem, you can use svg code in HTML, and do position for the parent div.

.circular-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
  padding: 10px;
  background: #fafafa;
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

  <svg xmlns="http://www.w3.org/2000/svg" class="circular" viewBox="25 25 50 50" width="50px" height="50px" style="
    /* position: absolute; */
    /* top: 50%; */
    /* left: 50%; */
    /* box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14),   0 1px 5px 0 rgba(0, 0, 0, 0.12); */
    /* padding: 10px; */
    /* background: #fafafa; */
    /* width: 50px; */
    /* height: 50px; */
    /* border-radius: 50%; */
"><circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="5" stroke-miterlimit="10"/></svg>

A: They seem to have issues with the viewBox translation and also with the transform-origin of the root <svg> element.
Setting the viewBox to 0 0 50 50 and translating your circle by -25, along with wrapping it in a <g> that will get the rotation fixes it:

const svg = `<svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 50 50" width="50px" height="50px">

  <g class="circular">
    <circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="5" stroke-miterlimit="10"/>
  </g>
</svg>`;
img.src = URL.createObjectURL(new Blob([svg], {type:'image/svg+xml'}))
.circular-loading{position:absolute;top:50%;left:50%;box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12);padding:10px;background:#fafafa;width:50px;height:50px;border-radius:50%;}

And if you don't wish to insert a new <g> element, then you could also just set the rotate animation on the <circle> directly (after fixing the viewBox):

const svg = `<svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 50 50" width="50px" height="50px">

  <circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="5" stroke-miterlimit="10"/>
</svg>`;
img.src = URL.createObjectURL(new Blob([svg], {type:'image/svg+xml'}))
.circular-loading{position:absolute;top:50%;left:50%;box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12);padding:10px;background:#fafafa;width:50px;height:50px;border-radius:50%;}


text:
Q: Gradle Multiproject War withEclipse gradle plugin. Not including project dependencies in tomcat webapp/app/WEB-INF/lib In a gradle multiproject, I have 3 projects:

*

*The first one contains basic utils (plugin; java-library)

*The second is a java application that depends on the first project (plugin: java)

*The third is a web application, that depends on the first project (plugin: war)

All 3 projects are declared in settings.gradle of the parent project
The first project is referenced from the second and third project setting:
api(project(":FirstProject"))
The second project runs without problems from Eclipse (Run As- Java application)
The third project cannot run properly as has missing dependencies at run time (Run As - run on server)
Looking in the directory where local tomcat resides in eclipse
/home/ximo/WORKSPACES/WS01/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/CSV01/WEB-INF/lib
I have detected that the first project jar is missing (firstproject.jar)
But when executing the build task from the "Gradle tasks" view, the generated war does contain the "missing" jar.
So the problem only arises when Eclipse deploys the application to the local tomcat for running (or debugging) locally the application.
I have used 2 possible "dirty" solutions for this problem:

*

*Copying this jar by hand to the referenced deployment lib folder.

*Adding to the build.gradle a reference to the missing jar
implementation files('path_to_jar/firstproject.jar')
Any idea for solving this issue?
Thanks.


text:
Q: Transfering Word table of contents into HTML-Code I want to transfer a table of contents from Word into HTML-Code.
Table of Contents
Im wondering, how to realise those dots between the page name and the page number because the lenght of the page names can vary.
Is there also a way for me to make the table dynamic? For exmaple I'm writing something in a h1-tag and it automatically fills the content of the tag + the page number with this layout into the table of contents?
So far I'm clueless on what to do, can someone please help me with this?
Thanks!


text:
Q: How to know through storefront website of Salesforce Commerce Cloud where Einstein is configured and providing results or not? Through Salesforce Commerce Cloud Storefront websites, i would like to know whether particular websites running showing more results where Einstein is configured and providing results or not?
Can anyone briefly knows any steps?

*

*Any DOM elements render by Einstein search if it configured If yes where can I find it?

*Based on single search terms("shoes", "shirts") or multiple search terms like "shoes under 100"?

A: There is a browser plugin available for this (Chrome):
https://chrome.google.com/webstore/detail/commerce-cloud-recommenda/dobmbolmcejainkefklnpkjbaibgjihn
Though this allows you to verify if you configured your site correctly, you can check others.


text:
Q: The folders / files generated by our scripts don't have the proper rights So the problem is, when we create new websites on our dev server, some of the files and folders created don't have the execute rights so we have to manually do a
chmod -R 777 /web/websitename
Here is an example of a freshly created website folder :
http://i.stack.imgur.com/ipw5E.png
So now my question is : is there a way to make it so that we don't have to manually set rights everytime a new folder is created? Thanks in advance. (the umask of the user running php / apache is 022)

A: What i see you are creating your websites in /web which is not recommendable, you should always create website in /var/www/html which is the default DocumentRoot of apache in redhat/centos linux or you can use an ISP control panel package such as virtualmin with webmin to do hosting. Basically try setting the website in /var/www/html you won't need to change the permission or if you change the DocumentRoot try giving the ownership.
Thanks & Regards,
Alok


text:
Q: SLES linux is not updating resolvers/nameservers from DHCP server I have two VMs in the same network - CentOS and SUSE linux. I didn't made any changes to configure DHCP client in these machines. When both the VMs are powered on, both the VMs are getting IPs but only CentOS getting the DHCP DNS hostname and resolvers/nameservers updated in /etc/resolve.conf properly whereas in SLES its not updating nameservers from DHCP server.
Does the SLES cannot fetch nameservers/resolvers from DHCP server? how to fix it?
I want the VMs to discover IP, DNS and resolvers automatically from the infoblox DHCP server. As I understand it, these VMs sends a broadcast message to 255.255.255.255. Typically a DHCP-relay catches this message and sends the request to the appropriate DHCP server. The DHCP server sends back a IP OFFER after which there is an exchange of REQUEST and ACKNOWLEDGE between the VM and the server.


text:
Q: dll entry point question/advice needed I have a dynamic library of c++ code that is cross platform and mostly just native c++. I then use this dynamic library from my main exe. Up until now all has been good on OSX using gcc. Now I'm on windows I am confused as to what method I should use to enter the dll. I don't have a DllMain function at present as this wasn't required in gcc (to my knowledge). My initial tests worked but on inspection revealed that strangely one of my class constructors was being called on dll load, so I figured I needed to do something more on windows. So do I:

*

*add a DllMain function?

*am I safe to just use the noentry compiler option?

When I do either of the above I start getting compiler complaints in the vein of ".CRT section exists there may be unhandled static initializers or terminators"
I have read up on this using this article, but any advice and clarity on the best way forward would be greatly appreciated. Its all a bit blurry in my head as to what I need to do.

A: Based on the .CRT error, you definitely need a DllMain function. For most Windows compilers, a DllMain will be provided for you automatically, so that you don't need to write one yourself. Based on other parts of your question it seems most likely that you are using Visual C++, whose CRT does provide a DllMain for you. So while you do need a DllMain, you don't need to write the code for it.
The default VC CRT DllMain is used to initialize the CRT for the DLL in question, and to initialise all the static/global variables that the dll provides.
The model for DLLs on Unix and Windows is significantly different, and you should think of each DLL as having a more 'private' set of state. Although, if all Dlls opt into the same version of the CRT dll, some of that state will then be shared.
Because the CRT is providing a DllMain for you, you should not throw /noentry on the linker.
The .CRT section exists error (which you must have seen by throwing /noentry) is telling you that you need a DllMain because you've got one or more objects in your DLL that require static initialisation.
Martyn

A: If it is just a library, then NOENTRY should suffice. DllMain is there to control events that happen with the DLL (i.e. attach, detach etc).

A: You can change the code (slightly) to avoid all entry points but main.  Essentially, if you have any variable defined outside of the functions (globally but not statically linked), wrap them in a function call.  Use the often-forgotten static function variables.
Ie, change global declaration
SomeType var_name;

to this:
SomeType & var_name(){static SomeType var; return var;}

Similarly, you can change static class instance variables by changing this:
struct Container{
    Container();
    static Container instance;
};

Container Container::instance;

to this:
struct Container{
    Container();
    static Container & instance();
};

Container & Container::instance(){
    static Container var;
    return var;
}

This is essentially a singleton, but there might be some concurrency issues if the 1st time you access the instance will be from a multi-threaded environment.  In fact, the thing to keep in mind is that unlike globally-defined variables, static locally-defined variables will be initialized the first time the function is called.


text:
Q: Display problem in HP Compaq laptop I am recently installed Ubuntu 12.04 in my laptop HP Compaq with an AMD Turion processor.Model no. HP presario V6000. It works well when booted from DVD but after installation display will not work and notification comes saying that paid drivers are avilable for downloading. But it does not give any detailes and I can not explore it because there is no display. Please advice me how to procewed.
Sachidananda

A: That notification says something about Proprietary Drivers not paid.
Anyway open the Dash and type Software and Updates. Another way is to open Terminal (Ctrl+Alt+T) and type gksu software-properties-gtk then hit Enter.
Once it opens select the last tab Additional Drivers. You should see there the drivers available for your PC. Select one of the tested ones and click Apply Changes.
Another way to install graphics drivers is from terminal:
If you have NVidia:
sudo apt-get install nvidia-current

If you have ATI:
sudo apt-get install fglrx

After installation it would be a good idea to restart, or at least log out and back in.


text:
Q: Getting multiple outputs from my dictionary when I need only one Im having a little problem with only printing the corresponding abbreviation that is stored in a dictionary
user = input("Enter a Abbreviation: ")

dictionary = {"ADSL": "Application Programming Interface",
              "IDE": "Integrated Development Enviroment",
              "SDK": "Software Development Kit",
              "UI": "User Interface",
              "UX": "User eXperience",
              "OPP": "Object Oriented Programming"
              }

for x in dictionary:
    if user in x:
        print(user + ":" + " " + dictionary[x])

    elif x != dictionary:
        print("Abbreviation not found")

This is my output
Enter a Abbreviation: UI
Abbreviation not found
Abbreviation not found
Abbreviation not found
UI: User Interface
Abbreviation not found
Abbreviation not found

I only need the entered abbreviation key value not all the Abbreviation not found outputs, I hope this makes sense

A: The good point of a dictionary is that is "indexed" so you don't need to find the key. You are following a array approach, and that is a wrong approach.
user = input("Enter a Abbreviation: ")

dictionary = {"ADSL": "Application Programming Interface",
              "IDE": "Integrated Development Enviroment",
              "SDK": "Software Development Kit",
              "UI": "User Interface",
              "UX": "User eXperience",
              "OPP": "Object Oriented Programming"
              }

if user in dictionary:
   print(user + ":" + " " + dictionary[user])
else:
   print("Abbreviation not found")

You can find more information about dictionaries here, here and on google. It is very important to know when to use arrays, dictionaries, lists, queues...

A: Maybe just this :
user = input("Enter a Abbreviation: ")

dictionary = {"ADSL": "Application Programming Interface",
              "IDE": "Integrated Development Enviroment",
              "SDK": "Software Development Kit",
              "UI": "User Interface",
              "UX": "User eXperience",
              "OPP": "Object Oriented Programming"
              }

for x in dictionary:
    if user in x:
        print(user + ":" + " " + dictionary[x])
    else:
        continue

A: I tried this code and it works... Looks like you were checking all the options...
user = input("Enter a Abbreviation: ")

dictionary = {"ADSL": "Application Programming Interface",
              "IDE": "Integrated Development Enviroment",
              "SDK": "Software Development Kit",
              "UI": "User Interface",
              "UX": "User eXperience",
              "OPP": "Object Oriented Programming"
              }

found = 0
for x in dictionary:
    if user in x:
        found = 1
        print(user + ":" + " " + dictionary[x])

if found == 0:
    print("Abbreviation not found")

A: Looks like you need dict.get.
user = input("Enter a Abbreviation: ")

dictionary = {"ADSL": "Application Programming Interface",
              "IDE": "Integrated Development Enviroment",
              "SDK": "Software Development Kit",
              "UI": "User Interface",
              "UX": "User eXperience",
              "OPP": "Object Oriented Programming"
              }

result = dictionary.get(user.upper())
if result:
    print(user + ":" + " " + result )
else:
    print("Abbreviation not found")

You don't need to loop if you have the key


text:
Q: Ngif else with css [Angular] is there a way to define that when my condition is not true, my component gets other attribute styles in Angular? i want to define my main css file.
i want something like this:
example (s-help.component.html): (not correct)

css
.s-help{
    background-repeat: no-repeat;
    background-position: center left calc(0.37em + 0.37rem);
    background-size: calc(1em + 1rem) calc(1em + 1rem);
    border: 2px solid $warning !important;
    border-radius: 4px;
    display: block !important;
    color: $gray-700;
    min-width: 220px;
    white-space: normal !important;
    padding-left: 5px !important;
    padding-right: 5px !important;

}
.s-help-content {
    padding-top: 6px;
    padding-bottom: 6px;
    padding-left: 45px;
    padding-right: 6px;
}

.test {
    display: none;
}

component used in code
<s-help [visible]="true" [ngClass]="'s-help'" [text]="'INFOTEXT.101' | translate"></s-help>

my issue is that the border of the component is visible all time, even if the condition is false
to make it more clear: https://stackblitz.com/edit/angular-ivy-etrn9z?file=src%2Fapp%2Fcomp%2Fcomp.component.html i dont want the border under the first info text

A: Is this what you need? ngClass will take a javascript expression as an input, here you can conditionally add the class or remove if needed!

updated stackblitz


text:
Q: Cannot connect java client to cassandra with password authentication enabled I have a default install of Datastax enterprise on my macbook. I was able to create my keyspace and setup all my applications including using solr.
I am trying to develop a set of steps to turn on password authentication for our dev cluster.
Thus far I have updated /usr/local/dse/resources/cassandra/conf/cassandra.yaml and changed the following properties:
authenticator: PasswordAuthenticator
authorizer: CassandraAuthorizer

I restarted the node and could login and query my keyspace using cqlsh:
cqlsh -u cassandra -p cassandra

At this point I tried setting the Credentials on the Session builder:
Host is: cassandra.host=localhost
Session session = keyspaceToSessionMap.get(keyspace);
    if( session == null){
        Cluster cluster = Cluster.builder().addContactPoints(hosts)
                .withCredentials(username, password)
                //.withSSL()
                .build();
        session = cluster.connect(keyspace);
        keyspaceToSessionMap.put(keyspace,session);
    }

I could not successfully connect however. So I added a new user and was able to again login via cqlsh but still cannot get the Java driver to connect.
cqlsh -u username -p password
Connected to LocalCluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 2.1.8.689 | DSE 4.7.3 | CQL spec 3.2.0 | Native protocol v3]

I am using 'com.datastax.cassandra:cassandra-driver-dse:2.1.9' via gradle for the driver.
I always get the following stack trace and through debugging can see the username and password are set properly:
Caused by: com.datastax.driver.core.exceptions.AuthenticationException: Authentication error on host localhost/127.0.0.1:9042: Username and/or password are incorrect
at com.datastax.driver.core.Connection$8.apply(Connection.java:376)
at com.datastax.driver.core.Connection$8.apply(Connection.java:346)

This seems like it should be simple but I am stumped.
My dependencies graph in relation to cassandra driver contains the following:
+--- com.datastax.cassandra:cassandra-driver-dse:2.1.9
|    \--- com.datastax.cassandra:cassandra-driver-core:2.1.9 -> 2.1.8
|         +--- io.netty:netty-handler:4.0.27.Final
|         |    +--- io.netty:netty-buffer:4.0.27.Final
|         |    |    \--- io.netty:netty-common:4.0.27.Final
|         |    +--- io.netty:netty-transport:4.0.27.Final
|         |    |    \--- io.netty:netty-buffer:4.0.27.Final (*)
|         |    \--- io.netty:netty-codec:4.0.27.Final
|         |         \--- io.netty:netty-transport:4.0.27.Final (*)
|         +--- com.google.guava:guava:14.0.1 -> 18.0
|         \--- com.codahale.metrics:metrics-core:3.0.2
|              \--- org.slf4j:slf4j-api:1.7.5 -> 1.7.12

I created the following test which passes.
Cluster cluster = Cluster.builder().addContactPoints("localhost")
                    .withCredentials("username", "password")
                    //.withSSL()
                    .build();
            Session session = cluster.connect("keyspace");
            Assert.assertNotNull(session);

The only difference I can tell between the two is that "localhost" is now a constant rather than an array of size 1.

A: Found I had a trailing whitespace and that was the root cause.
Cluster cluster = Cluster.builder().addContactPoints(hosts)
                .withCredentials(username.trim(), password.trim())
                //.withSSL()
                .build();


text:
Q: Nothing works for me for changing background of menu options in android I tried couple of techniques to change the background of my menu options (default is black and I have to change it), but nothing worked for me. I am using min sdk 11.
Two approaches that I used:
First) Changing in onCreateOptionsMenu function:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = new MenuInflater(getApplicationContext());
    inflater.inflate(R.menu.options_menu, menu);
    setMenuBackground();
    return true;
}

/*IconMenuItemView is the class that creates and controls the options menu
 * which is derived from basic View class. So We can use a LayoutInflater
 * object to create a view and apply the background.
 */
protected void setMenuBackground(){
    getLayoutInflater().setFactory( new Factory() {

        @Override
        public View onCreateView ( String name, Context context, AttributeSet attrs ) {

            if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {

                try { // Ask our inflater to create the view
                    LayoutInflater f = getLayoutInflater();
                    final View view = f.createView( name, null, attrs );
                    /*
                     * The background gets refreshed each time a new item is added the options menu.
                     * So each time Android applies the default background we need to set our own
                     * background. This is done using a thread giving the background change as runnable
                     * object
                     */
                    new Handler().post( new Runnable() {
                        public void run () {
                            view.setBackgroundResource( R.drawable.my_gradient);
                        }
                    } );
                    return view;
                }
                catch ( InflateException e ) {}
                catch ( ClassNotFoundException e ) {}
            }
            return null;
        }
    });
}

}
Second) Changing in styles.xml
<style name="Theme_MyStyled" parent="AppBaseTheme">
   <item name="android:panelFullBackground">@drawable/my_gradient</item>
</style>

My drawable is:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
  <gradient android:startColor="#990000ff" android:centerColor="#99800000" android:endColor="#99FFD485" android:angle="270" />
</shape>

Can someone tell how can it work for me? Thanks in advance..


text:
Q: Finding eigenvalues of tridiagonal matrix using MATLAB $$\begin{bmatrix}
-1 & 1 & 0 &\dots &\dots &\dots &0\\
1 & -2 & 1 & \ddots &    &   &  \vdots\\
0 & 1 & -2 & \ddots & \ddots &  &  \vdots\\
\vdots & \ddots & \ddots & \ddots & \ddots & \ddots & \vdots\\
\vdots & & \ddots & \ddots & -2 & 1 & 0\\
\vdots & & & \ddots & 1 & -2 & 1\\
0 & \dots & \dots & \dots & 0 & 1 & -1\\
\end{bmatrix}\in \mathbb{R}^{N\times N}$$
Is the matrix I'm trying to solve. I'm trying to figure out what to do in MATLAB, but I'm not familiar with the program to use it. What is the process one would to to solve for the eigen values for this matrix?

A: Using diag you can create your matrix 1. Using eig you can determine the eigenvalues 2.
Here is the code:
n = 4;
A = diag(-2*ones(n,1))+ diag(ones(n-1,1),1) + diag(ones(n-1,1),-1);
A(1,1) = -1;A(n,n) = -1;
eig(A)

You can alter $n$ to change the size of the matrix. Because we are using MATLAB we can easily visualize the eigenvalues for different $n$. With this code:
for n = 1:50
A = diag(-2*ones(n,1))+ diag(ones(n-1,1),1) + diag(ones(n-1,1),-1);
A(1,1) = -1;A(n,n) = -1;
plot(eig(A),n,'o')
hold  on
end

We can create this picture, with the eigenvalues on the x-axis and the size of the matrix on the y-axis. You can see a pattern, you can prove why this is.


text:
Q: Get row id in tableview options I am using swipe gesture for tableview cell options.
This is my code:
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {

    var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Sil" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in

        let shareMenu = UIAlertController(title: nil, message: "Emin misiniz ?", preferredStyle: .ActionSheet)

        let twitterAction = UIAlertAction(title: "Sil", style: UIAlertActionStyle.Default, handler: self.deleteConversation)
        let cancelAction = UIAlertAction(title: "İptal", style: UIAlertActionStyle.Cancel, handler: nil)

        shareMenu.addAction(twitterAction)
        shareMenu.addAction(cancelAction)

        self.presentViewController(shareMenu, animated: true, completion: nil)
    })
    return [shareAction]

}

You can see in the code, i am using deleteConversation method for handler. But I don't know how to get row id in deleteConversation method.
This is my deleteConversation method:
func deleteConversation(alert: UIAlertAction!) {
    //I need the row id here
    println("sill")
}

How can I get the row id in handler method ?

A: Class YourClassNameHere

var cellIndexPath: NSIndexPath?

// Other stuff here...

func tableView(tableView: UITableView, editActionsForRowAtIndexPath   indexPath: NSIndexPath) -> [AnyObject]? {

cellIndexPath = indexPath

var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Sil" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in

    let shareMenu = UIAlertController(title: nil, message: "Emin misiniz ?", preferredStyle: .ActionSheet)

    let twitterAction = UIAlertAction(title: "Sil", style: UIAlertActionStyle.Default, handler: self.deleteConversation)
    let cancelAction = UIAlertAction(title: "İptal", style: UIAlertActionStyle.Cancel, handler: nil)

    shareMenu.addAction(twitterAction)
    shareMenu.addAction(cancelAction)

    self.presentViewController(shareMenu, animated: true, completion: nil)
})
return [shareAction]

}

func deleteConversation(alert: UIAlertAction!) {
  //Print row indexpath here
  println("sill \(cellIndexPath.row)")
}

A: You have a couple of choices. You can save the row/indexPath of the edit action to a new instance variable at the beginning of your editActionsForRowAtIndexPath, and then look at that instance variable in your deleteConversation function. (You would need to create a new class-wide instance variable in your view controller for this option to work.)
Second option: You can pass in an inline block in your call to create the twitter action:
func tableView(tableView: UITableView,
  editActionsForRowAtIndexPath
  indexPath: NSIndexPath) -> [AnyObject]?
{
  //skipped code here...
  let twitterAction = UIAlertAction(
    title: "Sil",
    style: UIAlertActionStyle.Default,
    handler:
    {
      (alert: UIAlertAction!)  in
      println("User asked to delete twitter feed at index \(indexPath.row)")
    })
  //skipped more code here...
}

With that syntax you are passing in a closure as the twitter action handler, and defining the closure in-line. When you do that the closure has access to the variables in it's enclosing scope. In this case it gives us access to the indexPath that's passed in.

A: I assume by ID you mean indexPath?
In order to get it, have you tried using indexPathForSelectedRow on self.tableView?


text:
Q: Android view isDirty inside onClick I want to check if the text in some EditText is changed, after user clicks some Button. But View#isDirty seems not to return the correct state of the EditText if called inside onClick. For instance, I wrote something like this:
public class MainActivity extends Activity {
    EditText editText;
    Button button;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button = (Button) findViewById(R.id.f);
        editText = (EditText) findViewById(R.id.e);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println((editText.isDirty() ? "is dirty" : "is clean"));
            }
        });
    }
}

before i make any change to the editText, it outputs is clean, as expected. But the same is clean is printed even after I write something in editText.

When will isDirty be called? And is it the correct way to do this at all?

Update:

I also want to check if some Switch and Spinner values are changed. Is isDirty() the correct way to do this?

A: I would suggest to use:
https://stackoverflow.com/a/9459848/5684335
The comment from Okas is a good explanation why.

A: By the time you click your button edittext is no longer dirty - text is already updated and view redrawn. Maybe if you change your onclick handler you will understand better what is going on.
button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editText = (EditText) findViewById(R.id.e);
            System.out.println((editText.isDirty() ? "is dirty" : "is clean"));
        }
    });

isDirty will return true only as long as view has not been redrawn. This happens quite quickly and basically you do not have (and dont need) any control over this.
I think you need to use some other methods to achieve what you want.


text:
Q: How to have Gmail receiving email for an account in another domain? I have my own domain and also a Gmail account. I would like to have all the emails sent to my domain's email address redirected to my Gmail account; that is, I want all the emails sent to myname@mydomain.com to be received on my Gmail account instead, as if they had been sent to myname@gmail.com
I have configured my domain's DNS records to point to Gmail's mail server, as explained in Gmail documentation. However, when I send a message to myname@mydomain.com I receive an error message saying that:

mx.google.com rejected your message to the following e-mail addresses:
myname@mydomain.com
The email account that you tried to reach does not exist. Please try
  double-checking the recipient's email address for typos or unnecessary
  spaces.

I have myname@mydomain.com configured as an alternate "From" address to send emails in Gmail, otherwise I can't find any related configuration parameter in Gmail itself.
So, the question is: how should I configure my domain's DNS records and/or my Gmail account to accept emails sent to myname@mydomain.com? I know it is possible since I have done it in the past, I just can't remember how. Thank you!

A: You need to do the following:

*

*Have google apps panel and link mydomain.com there, verify its ownership and activate Google Mail service on mydomain.com

*Once done! create a new email account myname@mydomain.com and forward all incoming mails to myname@gmail.com
Most probably mx.google.com is rejecting mails due to unverified domain name mydomain.com and no linked Google Mail service.


text:
Q: In Heroku, is there a way to add multiple HTTP post hooks? I am currently using Heroku's HTTP post hook add-on to send a message to my company's chat client, but now I want to do more with it. Is it possible to add multiple HTTP post hooks, so more than one service could be notified when a deploy happens? (no I don't want to receive emails).
Thanks!
-Doug

A: My friend Jared made an app for this: https://github.com/deadlyicon/deploy-hook-forker

A: Not right now - a workaround would be having a tiny app to receives your HTTP post hook and trigger all the HTTP hooks you need.


text:
Q: How to make Vue i18n load translations from .json file in Unit Test? Using vue-i18n (v8.25.0 with vue v2.6.14), until now I had all my translations in .ts files holding the JS objects:
import { LocaleMessages } from 'vue-i18n'

const translations: LocaleMessages = {
  en: {
    test: 'Test',
  },
}

export default translations

Now, in order to better manage the translations, I switched to using .json files for the translation objects and importing these json files in the code.
So the en.json translation file is just
{
  "test": "Test"
}

and it is imported in a .ts file using
import { LocaleMessages } from 'vue-i18n'
import translation from './en.json'

const translations: LocaleMessages = {
  en: translation,
}

export default translations

Of course, I set
"resolveJsonModule": true, in tsconfig.json to make the json-Import work.
This works when serving the application - so the translations are correctly loaded.
But when executing unit tests using vue-cli-service test:unit, the translations are not loaded and the following warnings are logged:
[vue-i18n] Cannot translate the value of keypath 'test'. Use the value of keypath as default.
This causes some unit tests to fail that assert that the English translated value is there.
Until now, these tests ran successfully but since changing to json files, this no longer works.
I guess, somehow jest does not load the json imports correctly. Is there anything I need to adjust to make jest also load the json translation files in test runs (an "equivalent" to resolveJsonModule: true)?

A: By randomly trying out different stuff, I found a solution.
I totally don't get it but here is what made it work:
Using the default jest.config.js with the following contents
module.exports = {
  preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
}

made the error appear (translations not being available in Unit Tests).
But after adding the following two moduleFileExtensions, it suddenly worked again:
module.exports = {
  preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
  moduleFileExtensions: [
    'js',
    'ts',
  ],
}

I totally don't get it since @vue/cli-plugin-unit-jest/presets/typescript-and-babel by itself includes @vue/cli-plugin-unit-jest/presets/typescript that defines
moduleFileExtensions: ['ts', 'tsx'],

and derives from @vue/cli-plugin-unit-jest/presets/default that defines
moduleFileExtensions: [
    'js',
    'jsx',
    'json',
    // tell Jest to handle *.vue files
    'vue'
  ],

(see here)
But for whatever reason, adding the js and ts moduleFileExtensions explicitly to my own jest.config.js made it process json files again.
It feels like a bug to me, though.


text:
Q: iTextSharp display 'error' using PdfContentByte and ColumnText I'm trying to use PdfContentByte and ColumnText to display notes imported from customer orders. The document and notes display correctly however, when I scroll down at all in the document, I get an error saying "An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem"
I've looked around and found answers like: PDFs generated using itextsharp giving error at the time of first print command
But the method doesn't appear to have any nesting issues:
  private void DisplayNotes(OrderVerificationData ovNotes)
    {
        _notes = ovNotes.orderNotes;
        _resultNotes = _notes.Split(_notesSeparators, StringSplitOptions.RemoveEmptyEntries);
        Phrase notesDisplay = FormatPhrase("");
        PdfContentByte dc = _instance.DirectContent;
        var ct = new ColumnText(dc);
        foreach (string t in _resultNotes)
        {
            notesDisplay.Add(t);
            notesDisplay.Add(Environment.NewLine);
        }

        dc.BeginText();
        dc.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 10f);
        dc.SetTextMatrix(50f, _verticalAlign);

        if (_verticalAlign <= 40)//new page stuff, error still occurs when commented out
        {
            dc.EndText();
            FooterCreation(ovNotes);
            _document.NewPage();
            _numberOfPages += 1;
            _verticalAlign = 690;
            dc.BeginText();
            dc.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 9f);
            dc.SetTextMatrix(50f, _verticalAlign);
        }

        ct.SetSimpleColumn(notesDisplay, 55f, 0f, 400f, _verticalAlign, 10f, Element.ALIGN_LEFT);
        ct.Go();
        dc.EndText();
    }

I don't recall column text needing to be closed, nor could I find anything that said it had to be. Is there something else that's causing this issue?
Removing all usage of this method from the rest of the file causes the pdf to be displayed properly.

A: You are creating illegal PDF syntax. A text object is created by introducing the BT (begin text) and ET (end text) operator. There are different ways to introduce these operators using iTextSharp.
One way is by adding these operators using low-level syntax:
dc.BeginText();
dc.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 10f);
dc.SetTextMatrix(50f, _verticalAlign);
dc.ShowText("Some text");
dc.EndText();

The other way is by using ColumnText, a class that hides all the low-level operations:
var ct = new ColumnText(dc);
ct.SetSimpleColumn(notesDisplay, 55f, 0f, 400f, _verticalAlign, 10f, Element.ALIGN_LEFT);
ct.Go();

For reasons unknown, you are mixing both approaches, creating code that is very hard to understand, maintain, debug. Please remove all the lines that use the dc variable, except for the line where dc is used as a parameter to create the ColumnText object.


text:
Q: How to set TO multiple addresses while sending an email in Hybris I am developing a wishlist functionality; there comes a requirement to give privilege to the customer to share a wishlist. When he clicks on share, a popup opens with two fields to input 1.) To mail addresses, 2) Some comments.
I wrote a VM template, event listener, a context class and a businessprocess.xml.
Now when I start the business process in the listener, it will invoke my context class; populates all the required attributes to the context and that context will be used to display dynamic stuff on the VM template.
But I could not find where I can actually input my TO ADDRESSES in this whole process.
My init method in the context class goes something like this.
{
    super.init(wishlistShareEmailProcessModel, emailPageModel);
    put("wishlistComments", wishlistShareEmailProcessModel.getComments());
    put("wishlistName", wishlistShareEmailProcessModel.getWishlistName());
}

kindly suggest me(I am using 6.3 btw)

A: Override EMAIL property to set TO email address
{
    super.init(wishlistShareEmailProcessModel, emailPageModel);
    put("wishlistComments", wishlistShareEmailProcessModel.getComments());
    put("wishlistName", wishlistShareEmailProcessModel.getWishlistName());
    put(DISPLAY_NAME, "User Display Name"); //wishlistShareEmailProcessModel.getDisplayName()
    put(EMAIL, wishlistShareEmailProcessModel.getToEmail()); //wishlistShareEmailProcessModel.getToEmail()
}

You can refer this answer

Edit: To support multiple To email addresses refer below post
https://www.helphybris.com/2018/03/multiple-toaddress-attachment-in-email-hybris.html


text:
Q: Performance issues using webcam on Google Chrome? We have created a webcam application in Flash, using actionscript 3.  The application runs smoothly on Internet Explorer, Firefox, Safari & Opera.  However when trying it on Google Chrome the webcam experience has a severe performance drop.
We use the latest Chrome version on a Windows Vista machine.  As mentioned all other browsers runs the application just fine which makes me believe that there is some issue with the latest version of Chrome and Flash Player.
Anyone here have heard anything or knows more about the subject?  Could it be application specific reasons?  It's pretty hard to figure out what the cause could be.
Thanks in advance!

A: Try to disable standard chrome version  flash player from

chrome://plugins/

and enable/install own version.

A: Okay I figured I would answer my own question if anyone else happen upon the same problem (which I am sure someone will!).
As explained in this thread and around the interwebs the main problem when it comes to Chrome and Flash applications is the Flash Pepper Player (FPP).  This is a player that auto updates along with Chrome to make it more user friendly.  Sadly the player is not very stable and a lot of issues can occur such as rendering problems and just plain performance issues.
This seems more prone to happen on PCs than, for instance, on Macs.
To get rid of this problem users are adviced (Not by Chrome or Adobe but by your friendly internet community) to disable the FPP (chrome://plugins/) and manually download the flash player as one would on IE or Firefox for instance.
Here's some more information:
Stack Overflow
How to Disable the Chrome Pepper Flash Player
Computer World
Good Luck!


text:
Q: Only put a certain number of lines in a char array I have a file with 2939 lines, and I am trying to save the five lines together in one index of a 2D char array.
So,
 char [][] myArray;
 myArray[0] = {} //<--char array of first five lines
 myArray[1]= //char array of next five lines

the way I am implementing this is:
int countLines=0;
while (sc.hasNext() countLines <5) { //sc is scanner
   //read each line and append to a string builder
   //then convert stringbuilder to char array and
   //store in myArray[0]

   countLines++;
 }

I am stuck on the part of storing the next five lines in myArray[1]. Any help would be appreciated. Thanks!

A: Prefer using Lists instead of arrays:
    List<String> myArray = new ArrayList<String>();
    while (sc.hasNext()) {
       myArray.add(sc.nextLine());
    }
    // your 5 first line:
    // your 5 first line array:
    List<String> fiveLines = myArray.subList(0, 5);

A: use array list they since you dont know size of array
 ArrayList<String> strs = new ArrayList<String>();

now add as
 strs.add("your string");

get size
strs.size();

A: You can try this
while(sc.hasNext()) {
    if(countLines < 5) {
        //store in myArray[0]
    } else if(countLines >= 5 && countLines < 10) {
        //store in myArray[1]
    }
    countLines++;
 }


text:
Q: multiple definition in stl class header I am getting stuck using this class, when I used in the main.cpp there is no problem and execute perfectly, but when I use it as a member class the compiler doesn't like it and sends the message "Multiple definition of:"
Here is the class:
RTPSocket.h:
#ifndef RTP_SOCKET_HDR
#define RTP_SOCKET_HDR
    namespace RTPConnection
    {

    enum EMode
    {
        Sender,
        Receiver
    };

    template<EMode Mode>
    class RTPSocket
    {
    };
    }//end namespace

#define RTP_SOCKET_IMP
#include "RTPSocket_Imp.h"//file where i declare the implementation code
#undef RTP_SOCKET_IMP
#endif

this class by itself doesn't have any problem but when i use it in my class, but ....
used in another class
my file.h
#include RTPSocket.h
class CommClass
{
private:
RTPSocket<RTPConnection::Receiver>  * mRTPServer;
}

the compiler give this error message:
multiple definition of 'enum RTPConnection::EMode'
this is a method that is declared in another file "rtpsocket_imp.h"
with the guard declared:
template<EMode Mode>
void RTPSocket<Mode>::write(char* aArray,
                                      const size_t aiSize)
{
    std::string message("The write function is operative only on Sender Mode");
    throw BadTemplate(message);
}

A: You want include guards around the header:
#ifndef RTPSOCKET_H
#define RTPSOCKET_H

// header contents go here

#endif

This will prevent the header contents from being included more than once per source file, so you will not accidentally get multiple definitions.
UPDATE: Since you say you have include guards, then possible causes of the error might be:

*

*misspelling the include guard name, so it doesn't work

*defining something with the same name in another header (or the source file that includes it)

*undefining the include guard name.

But without seeing code that reproduces the error, I can only guess what might be wrong.

A: You need an include guard.
Inside the RTPSocket.h  file at the top put
#ifndef RTPSOCKET_INCLUDED
#define RTPSOCKET_INCLUDED

and at the end put
#endif

If that's not the problem, and you do have an include guard, I suggest you search for

enum EMode

in your code and find all the places you have defined it, and make sure you just define it once.

A: My problem was the CMakeLists.txt that was building this project.
My fault!


text:
Q: Adding custom test fields to magento packslip i want to add custom field to packslip infact want new format for it as below:

Customer Shipping Add

Admin Address or store address

some other detail

i found page "app/code/core/Mage/Sales/Model/Order/Pdf/shipment.php"
public function getPdf($shipments = array())

how to add this to my pdf


text:
Q: Can I use a shielded multiple conductor cable to carry current (0-100mA) from multiple current transformer clamps (CT) that sense AC current? I need to run cables for 12 CTs (Split Core Current Transformers) that will be sensing current on multiple branches inside my outdoor electrical panel. In case it matters, it is a 240V split-phase 200A panel (typical USA residential).
Each CT uses UL2457 2 conductor 24AWG shielded cable, however instead of running 12 of them, I was hoping to use multiple 4 or 6 conductor cables between my panel and the exterior box holding the multi-channel energy meter. Except for the 200A CTs, all other CTs do not have burden resistors so the signal will me 0-26mA, but in theory could be 0-100mA depending on which CT I end up using. For the 200A CTs I plan on using a single 2 conductor cable for each given the signal is a low voltage.
It is my understanding that current signals do not interfere with each other so I should be able to have 2 CTs for the same 240V appliance (therefore 1 CT per split-phase) running in a single 4 conductor cable. I want to confirm that there will not be any interference between the two current signals and that the fact they are not on the same phase will not matter.
An alternative, if phase does matter and current signals do not interfere with each other, would be to use a 6 conductor cable so I can wire 3 CTs on the same phase through a single cable (the energy meter has 6ch per board, 3 on each phase). Would this work?


text:
Q: What is the difference between using let keyword in a for loop and not using let keyword while declaring iterative variable? I was doing a determinant challenge on codewars when I encountered this issue. Apparently, my for loop for i was running only once when the matrix was 4x4 or bigger but it was running fine for a 3x3 matrix. But when I put let before i, it worked for a matrix of any size (3x3 or bigger). I'm not an experienced JS programmer, so, I'd love it if someone could explain the difference and/or reason why my program was acting in this way.

//Buggy code
const determinant = (matrix) => {
    if(matrix[0].length === 1) return matrix[0][0]
    if(matrix[0].length === 2) return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]))
    sum = 0
    for(i = 0; i < matrix[0].length; i++){
        console.log(matrix, i)
        subMat = []
        for(j = 1; j < matrix.length; j++) {
            subMat2 = []
            for(k = 0; k < matrix[0].length; k++){
                if(i === k) {}
                else subMat2.push(matrix[j][k])
                // else if(matrix[j][k] !== matrix[0][i])
            }
            console.log(subMat2)
            subMat.push(subMat2)
        }
        if(i % 2 === 0) sum += matrix[0][i] * (determinant(subMat))
        else sum += -(matrix[0][i] * (determinant(subMat)))
        console.log(subMat, sum, matrix[0].length)
    }
    return sum
}

//Correct code
const determinantCorrected = (matrix) => {
    if(matrix[0].length === 1) return matrix[0][0]
    if(matrix[0].length === 2) return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]))
    sum = 0
    for(let i = 0; i < matrix[0].length; i++){
        console.log(matrix, i)
        subMat = []
        for(j = 1; j < matrix.length; j++) {
            subMat2 = []
            for(k = 0; k < matrix[0].length; k++){
                if(i === k) {}
                else subMat2.push(matrix[j][k])
                // else if(matrix[j][k] !== matrix[0][i])
            }
            console.log(subMat2)
            subMat.push(subMat2)
        }
        if(i % 2 === 0) sum += matrix[0][i] * (determinant(subMat))
        else sum += -(matrix[0][i] * (determinant(subMat)))
        console.log(subMat, sum, matrix[0].length)
    }
    return sum
}


text:
Q: Can't byte variable express 125 in Java? I'm totally java beginner and not good at English. So I don't know how to ask what I really want to know, but I trying..
After I learned some code about using byte I practiced. But the result was not what I expected..
below is my code!
public static void main(String[] args){
    byte n1 = -2; // 10000010
    byte r1 = (byte) (~n1); // expectation: 125(01111101)
    System.out.println(r1);
}

but the result was "1"..
I learned that byte can express -128~+127 and I thought Eclipse would show me "125", but it was "1" so I want to know why..
Thank you for your attention to my question.

A: ~x is equivalent to x ^ -1 in Java, so ~n1 is -2 ^ -1 = 1.
As Eran pointed out in the comments, the issue is that you are mistaken about the bitwise representation of -2. -2 is 11111110, while 1000010 is actually -126.


text:
Q: Find process and print application name in unix I have Raw PS command output in a file and i want find like if pmon is found then i need to print like Oracle,Database, if the Jboss found need to print like Jboss,Middle-ware.
I have the mapping file like below
Pmon,Oracle,Database
Jboss,Jboss,Middle-ware
Weblogic,Weblogic,Middle-ware.
i need to write a shell script for this, can you please help me.
Thanks

A: SOmething like this, maybe?:
$ cat foo
pmon Oracle,Database
jboss Jboss,Middle-ware
weblogic Weblogic,Middle-ware.
bash Bash,shell

Code:
$ ps | awk '
BEGIN {                           # hash the mapping file foo in the BEGINning:
    while((getline < "foo") > 0)  # read records from file
        a[$1]=$2                  # hash to a
    close("foo") }                # be nice now and shut it up
$NF in a { $0=$0 OFS a[$NF] }     # append mapping to the end of output
1'                                # print
  PID TTY          TIME CMD
 4611 pts/3    00:00:04 bash Bash,shell
15691 pts/3    00:00:00 ps
15692 pts/3    00:00:00 awk
31785 pts/3    00:00:00 emacs

Downside: a[$1]=$2 only allows one word mappings, mapping like:
emacs greatest entity's right hand

would fail (well, not entirely, it would output emacs greatest :).

A: Thanks Jamesh for your time.
I am able to achieve with this
while read line
do
txtgrep=echo $line | cut -d@ -f1
txtappend=echo $line | cut -d@ -f2
done
i have modified the mapping file like
jboss@jboss,middleware


text:
Q: Connect to MySQL Database Remote I have a MySQL database on another computer and I want to be able to connect from other computers (even computers on different networks). I did the following
MySQL
CREATE USER 'username_here'@'%' IDENTIFIED BY 'password_here';

then
GRANT ALL PRIVILEGES ON *.* TO 'username_here'@'%';
FLUSH PRIVILEGES;

I also commented out bind-address in the my.ini file (I have windows)
Then in the Java application (that utilizes the MySQL database) I did
jdbc:mysql://public_ip:3306/database_name

I used my public ip address in the jdbc url.
Finally, I opened port 3306 in firewall. But I am not able to connect to the database remotely. What other things do I need to do to connect?

A: First of all: Do not public post your real ip address and port and also say that you opened the firewall. Perhaps hackers now find it too easy to hack, but you can not rely on that ;-).
To your problem: Perhaps you configured your mysql to listen at localhost 3306 and not to your public ip address. Please enter netstat -ltn in your shell. If there is a line
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN

and none with the public host address then you only have access from inside the network. Then, you have to configure your host adress in your mysql ini file. (just replace 127.0.0.1 or localhost by your ip address.

A: FYI : It is a very bad idea to have a publicly open port to your database server, specially MySQL default(3306) port. You are just inviting people to try to break into your database.
To access MySQL remotely, follow below steps :
1) Comment out following lines in my.cnf file.
#bind-address           = 127.0.0.1
#skip-networking

2) Restart mysql server.
net stop MySQL
net start MySQL

If you got The service name is invalid then Open task manager => Click Service button => search MySql service => Restart
Remotely connect with mysql :
mysql -h HOST -u USERNAME -pPASSWORD

You can also check the open port with nmap command :
nmap -PN Ip_address

Note : Mask your ip address in your question.
MySQL Java Connectivity :
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
Connection connection = DriverManager.getConnection("jdbc:mysql://publicIpAddress/dbName?",
                        sqluser,password);


text:
Q: Как получить одну фигуру вместо двух? При введении любых возможных значений (круг или квадрат, синий или зеленый или красный, и значения ширины и высоты) в promtp у меня вылезает всегда две фигуры. А Нужно что бы поседение два параметра (ширина и высота) применялись к одой фигуре.
То есть я ввожу: квадрат, синий, 600, 800 - и появлялся один синий квадрат с сторонами 600 на 800
let figura = prompt('Какую фигуру вам нужно?', '');
let tsvet = prompt('Какого цвета вам нужно фигура?', '');
let razmer1 = prompt('Какая ширина будет у фигуры (в пикселях)?', '');
let razmer2 = prompt('Какая высота будет у фигуры (в пикселях)?', '');

if ((figura == 'круг') & (tsvet == 'красный')) document.write('<div2r style="width:' + razmer1 + 'px"></div2r>')
if ((figura == 'круг') & (tsvet == 'зеленый')) document.write('<div2g style="width:' + razmer1 + 'px"></div2b>')
if ((figura == 'круг') & (tsvet == 'синий')) document.write('<div2b style="width:' + razmer1 + 'px"></div2g>')

if ((figura == 'квадрат') & (tsvet == 'красный')) document.write('<div1r style="width:' + razmer1 + 'px"></div1r>')
if ((figura == 'квадрат') & (tsvet == 'зеленый')) document.write('<div1g style="width:' + razmer1 + 'px"></div1b>')
if ((figura == 'квадрат') & (tsvet == 'синий')) document.write('<div1b style="width:' + razmer1 + 'px"></div1g>')

if ((figura == 'круг') & (tsvet == 'красный')) document.write ('<div2r style="height:' + razmer2 + 'px"></div2r>')
if ((figura == 'круг') & (tsvet == 'зеленый')) document.write('<div2g style="height:' + razmer2 + 'px"></div2g>')
if ((figura == 'круг') & (tsvet == 'синий')) document.write('<div2b style="height:' + razmer2 + 'px"></div2b>')

if ((figura == 'квадрат') & (tsvet == 'красный')) document.write('<div1r style="height:' + razmer2 + 'px"></div1r>')
if ((figura == 'квадрат') & (tsvet == 'зеленый')) document.write('<div1g style="height:' + razmer2 + 'px"></div1g>')
if ((figura == 'квадрат') & (tsvet == 'синий')) document.write('<div1b style="height:' + razmer2 + 'px"></div1b>')

div1r{
width: 150px ;
height: 150px;
background-color: red;
float: left;
margin: 10px;
}
div1g{
width: 150px ;
height: 150px;
background-color: green;
float: left;
margin: 10px;
}
div1b{
width: 150px ;
height: 150px;
background-color: blue;
float: left;
margin: 10px;
}
div2r{
width: 150px ;
height: 150px;
background-color: red;
float: left;
margin: 10px;
border-radius: 100px;
}
div2g{
width: 150px ;
height: 150px;
background-color: green;
float: left;
margin: 10px;
border-radius: 100px;
}
div2b{
width: 150px ;
height: 150px;
background-color: blue;
float: left;
margin: 10px;
border-radius: 100px;
}

<html>
 <head>
 <title>5111-61</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <link rel="stylesheet" href="Untitled-1.css" type="text/css" />
 </head>
 <body>
<script src="script.js"></script>
 </body>
 </html>

A: У Вас "вылезает" не две, а четыре фигуры. Перенесите все prompt-ы в начало скрипта.
document.write('<div2r style="width:' + razmer1 + 'px;height:' + razmer2 + 'px;"></div2r>');


text:
Q: Elastic Beanstalk silently fails to install ruby gem I'm trying to install the github-pages ruby gem in an AWS Elastic Beanstalk app.  According to the docs, to do this you add an .ebextentions/somename.config file that declares the package as a dependency.  My packages.config looks like this:
packages:
  yum:
    ruby-devel: []
    zlib-devel: []
  rubygems:
    github-pages: []

The eb logs claim that the package was installed successfully.
2016-06-05 21:44:52,037 [INFO] Installing github-pages version None via gem
2016-06-05 21:45:30,360 [INFO] Gem installed: github-pages-None

But when I ssh into the instance the jekyll command isn't found:
[ec2-user@ip-***~]$ jekyll
-bash: jekyll: command not found

Also gem list | grep github returns nothing.

Why isn't the package being installed and what can I do to make it install?
Thanks

A: The easiest method of doing this is to use RVM. It manages Ruby and all its gems for you and it's easy to use. See this link for using it.
If you did not want to use that you will need to modify your PATH variables so it can find your gems. I have found this to be tedious and reverted to RVM, but here are the general steps.
You will need to find out where your gems are getting installed. If you did gem install ... the gems will be in ~/.gem/ruby/1.8/gems/bin, if you used sudo gem install ... the gems will be somewhere in /System/Library/Frameworks/Ruby.framework/Versions/1.8/Resources
You have to add this path to your PATH variable. Easiest way to do this is by running :
echo 'PATH=$PATH:above/path/to/gems' >> ~/.bash_profile


text:
Q: Can I run cordova app in background
So I'm asking all of you PhoneGap/Cordova/... experts, I have an upcoming project in which I'm targeting both iOS and Android and I have to make a decision whether to do it Cross-Platform or native.
However, this app has to run in background at some point of its life cycle. I've found these plugins but some people are saying it's not working:

*

*katzer/cordova-plugin-background-mode

*jocull/phonegap-backgroundjs

*Red-Folder/bgs-core
The question is can I do backgrounding with Crodova technologies ? If yes which is the best plugin ?
Please help. Thanks.

A: You have to keep in mind that Cordova apps run in a webview in the main (GUI) thread of your app. In practical terms, your app will run minimized only until the OS decides it wants to halt it for whatever reason (typically to preserve RAM and/or battery).
For Android applications, you can create your own Cordova plugin that implements a background service. Instead of doing this from scratch, you can use Red-Folder/bgs-core as a starting point. You'll have to write the logic of your bg service using java and the Android SDK.
For iOS applications it's trickier. Apple only allows background code for a number of use cases: Audio playback, GPS tracking, others. The cordova-plugin-background-mode fakes background Audio playback to keep the app alive but it won't be accepted to the app store. My (very superficial) testing on iOS showed that when using the cordova-plugin-background-mode and actually playing background audio, my Javascript callbacks inside my app would be called erratically (called late and sometimes not called at all).
For my use case, I ended up implementing an Android service as mentioned and an iOS plugin that uses Apple's AVQueuePlayer to play background audio and video while the app is minimized.


text:
Q: External Lists not working Two problems.

*

*Despite spending all day learning BCS and Enterprise Features and getting all the different levels of credentials set in Central Administration when I put an External List webpart on my page it does  see my External Content Type that I have created however it gives me a login error as it is trying to login in as 'NT AUTHORITY\ANONYMOUS LOGON' so the webpart content doesnt exist.

*If I try to create an External List from within the browser it doesnt see my External Content Type. If i try to create an External List from within Designer it sees the External Content Type which it also say is good for lists however on creation it just says failed to save with zero information as to why.
help?

A: As the question is quite general and you didn't provide specific information how you created bcs connection, even what's the external data you're trying to connect to, There might be some possible problems that cause the problem.

*

*I'm assuming that BCS service is started and running.

*Check if the account you're creating the BCS connection (through SPD) is a farm administrator account. If not, search on how to use another account, there is a workaround.

*What authentication mode are you using for your ECT?
2.1. If it's a BDC Identity make sure that you ran the scripts to enable BDC Identity
2.2. If it's a impersonate Windows Identity - check the Metadata Store Permissions and Object Permissions plus check if Secure Stored Application is set correctly for a user that connects with external data

*If you're using SQL Server as external data then make sure that BDC Identity or whatever user account you're using for BCS connection is added to database you're trying to access.

If none of above ideas helped, please provide some more information.


text:
Q: Bash - Number color based on sign, tabbed I have lines like these in the terminal
8  XLM      3.85  -10.18  -32.94   0.00003836      0.564      0.470    8.402
9  MIOTA   -0.60   -3.38  -11.22    0.0002438      3.582      2.986    8.300
10 DASH     0.55   -2.01   -6.55    0.0742421   1090.820    909.358    7.102
11 NEO     -0.40   -0.88   27.09   0.00832249    122.280    101.938    6.626
12 TRX      7.33  -18.68   42.45   0.00000791      0.116      0.097    6.369

and I would like to print the 3,4,5 fields in green if they're positive or in red if they're negative. I'm using awk and printf but cannot have both color and correct tabbing with printf.
If I add color codes with awk like
awk '{ if($3<0){$3="\033[0;31m"sprintf("%.2f",$3)"\033[0;0m"} else {$3="\033[0;32m"sprintf("%.2f",$3)"\033[0;0m"};}1'

then the tabbing is lost or messed up.
The full command without colors is
curl -s "https://api.coinmarketcap.com/v1/ticker/?convert=EUR&limit=20" | jq -r '.[] | [.rank, .symbol, .percent_change_1h, .percent_change_24h, .percent_change_7d, .price_btc, .price_usd, .price_eur, .market_cap_eur] | @tsv' | awk '{ $3=sprintf("%.2f",$3); $4=sprintf("%.2f",$4); $5=sprintf("%.2f",$5); $6=sprintf("%.8f",$6); $7=sprintf("%.2f",$7); $8=sprintf("%.2f",$8); $9=sprintf("%.3f",$9/(1*10^9)) }1' | xargs printf '%2s %-5s %7s %7s %7s %12s %10s %10s %8s\n' 'r' 'curr' '1d' '24h' '7d' 'btc' 'usd' 'eur' 'mcap B'

A: Your field spacing is getting modified because you're modifying a field which causes awk to recompile the record replacing input spaces (IFS) with OFS values. If you change the whole record instead of any individual field then awk won't change the spacing between fields:
With GNU awk for gensub():
$ cat tst.awk
BEGIN { red="\033[0;31m"; green="\033[0;32m"; norm="\033[0;0m" }
{
    for (i=3; i<=5; i++) {
        $0 = gensub("(([^[:space:]]+[[:space:]]+){"i-1"})([^[:space:]]+)", "\\1" ($i < 0 ? red : green) "\\3" norm,1)
    }
    print
}

or with any awk:
$ cat tst.awk
BEGIN { red="\033[0;31m"; green="\033[0;32m"; norm="\033[0;0m" }
{
    for (i=3; i<=5; i++) {
        sub("([^[:space:]]+[[:space:]]+){"i-1"}", "&" ($i < 0 ? red : green))
        sub("([^[:space:]]+[[:space:]]+){"i-1"}[^[:space:]]+", "&" norm)
    }
    print
}

$ awk -f tst.awk file
8  XLM      3.85  -10.18  -32.94   0.00003836      0.564      0.470    8.402
9  MIOTA   -0.60   -3.38  -11.22    0.0002438      3.582      2.986    8.300
10 DASH     0.55   -2.01   -6.55    0.0742421   1090.820    909.358    7.102
11 NEO     -0.40   -0.88   27.09   0.00832249    122.280    101.938    6.626
12 TRX      7.33  -18.68   42.45   0.00000791      0.116      0.097    6.369

and so you can see the colors:


text:
Q: How to correctly handly NSError** pointers? What is the correct way to handle NSError** pointers?
- (BOOL)handleData:(NSDictionary *)data error:(NSError **)error {
    // pass the error pointer to NSJSONSerialization
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:options error:error];

    // Check if NSJSONSerialization had errors
    if (error)  // <-- sometimes this works, sometimes it crashes...
       return false;

    ...

    return true;
}

- (void)someMethod {
    NSError *error = nil;
    BOOL result = [self handleData:dataDict error:&error];

    if (error) {
       // an error occurred
    } else {

    }
}

In this example someMethod passes a NSError reference to handleData:error. This is done by passing a pointer/address instead of the object (...error:&error)
The method handleData:error then passes this pointer to dataWithJSONObject:options:error (now without the &). Now I would like to check an error occurred, but what is the correct way to do this?
if (error)...
// This works if error == nil. However this is not always the case.
// Sometimes error is some address (e.g. 0x600001711f70) and *error == nil
// from the start of the method (passing error to NSJSONSerialization has no
// influence on this

if (*error)...
// This works in cases where error itself is not nil, but it crashes if
// error == nil

Why is error == nil in some cases and error != nil but *error == nil in others?
What is the correct way to pass error between the methods and to check if an error occurred?

A: The place to find the answers is Introduction to Error Handling Programming Guide For Cocoa. The conventions are:

*

*A method may return an NSError object via an NSError ** parameter, such a method should also have a non-void return type and indicate success or failure via its return value. So, using your example, dataWithJSONObject:options:error: will return nil if it encounters an error and may return an error object via its third parameter.

*Any method accepting an NSError ** parameter for error returns should accept either the address of an NSError * variable or NULL. The latter value means the user does not wish to have an error object returned. This means that the method accepting an NSError ** parameter must check the parameter value is not NULL before attempting to assign an error object via it.
So your method handleData:error: must be prepared to accept NULL and needs to test for it. Your code therefore must include something similar to:
// Check if NSJSONSerialization had errors
if (jsonData == nil)
{
   // Error occurred, did it return an error object?
   if (error != NULL && *error != nil)
   {
       // we have an error object
   }
   else
   {
      // we have an error but no error object describing it
   }
}
else
{
   // no JSON error
}

HTH