text:
Q: Overfitting problems for key points model (detecting wrists, elbows, shoulders, etc.) I'm building a model to detect keypoints of body parts. To do that I'm using the COCO dataset (http://cocodataset.org/#download). I'm trying to understand why I'm running into overfitting issues (training loss converges, but I reach a ceiling really early for testing loss). In the model, I've tried adding layers of dropout (gradually adding more layers with higher probabilities, but I quickly get to a point when training loss stops decreasing which is just as bad. My theory is that the model I use isn't complex enough but I'd like to know if that's the likely reason or if it could be something else. The models I've found online are all extremely deep (30+ layers).
Data
I'm using 10,000 RGB images each of which has a single person in it. They each have different sizes but a max of 640 length and width. As a preprocessing step, I make every image the size 640x640 by filling any extra area (bottom and right of image) with (0,0,0) or black.
Targets
The full dataset has many keypoints but I'm only interested in the right shoulder, right elbow, and right wrist. Each body part has 2 keypoints (X coordinate and Y coordinate) so my target is a list of length 6.
Model
activation_function = 'relu'
batch_size = 16  # ##
epoch_count = 40  # ##
loss_function = 'mean_squared_error'
opt = 'adam'

model = Sequential()
model.add(Conv2D(filters=16, kernel_size=(3, 3), input_shape=inp_shape))
# model.add(Conv2D(filters=16, kernel_size=(3, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=32, kernel_size=(3, 3)))
# model.add(Conv2D(filters=32, kernel_size=(3, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(300, activation=activation_function))
model.add(Dropout(rate=0.1))
model.add(Dense(300, activation=activation_function))
model.add(Dense(num_targets))
model.summary()
model.compile(loss=loss_function, optimizer=opt)
hist = model.fit(x_train, y_train, batch_size=batch_size, epochs=epoch_count,
                 verbose=verbose_level,
                 validation_data=(x_valid, y_valid))

A: Your theory

the model I use isn't complex enough

it's a good theory, the model is pretty simple and given that we don't know exactly how much overfitting are you suffering it seems possible that the overfitting is because of the complexity of the model.

In the model, I've tried adding layers of dropout

Could be a simple but effective way of making the model a little more complex, but furthermore, I'd increase the dropout rate. It seems that you have a dropout of 0.1, try 0.5 for example and compare if the overfitting decreases.
Anyway, I think the best you can try is incrementing the complexity of the model, but in the convolution part, not just adding Dense layers after the Flatten. If it seems difficult to you, I suggest to find some pre-built general architectures for Convolutional Neural Networks for Image Recognition or even more specific builds for similar problems to yours.
Tell us how it goes!

A: In addition to already said in the answers:

*

*You can have several Dropout layers with different probabilities, e.g. after the pooling layers. Early layers often have higher keep probability, since they use fewer filters.

*Image data augmentation is another way towards generalization and in my experience it always improves the result, at least slightly (of course, provided that input transformation is not severe).

*Batch normalization (and its successors, weight normalization and layer normalization) is a modern regularization method that reduces the required dropout intensity, sometimes completely, i.e. you can get rid of dropout layers. In addition, batchnorm improves activations statistics, which often makes the network learn faster. I used it in addition to dropout and it worked pretty well.

*A technique called Scaled Exponential Linear Units (SELU) has been published very recently, which is said to have implicit self-normalizing properties. It's even already implemented in keras.

*The good old L2 or L1 regularizer is still in use. If nothing else helps, consider adding it too. But I'm pretty sure that batchnorm, selu and few dropout layers will be enough.


text:
Q: Add a class depending on leaflet js zoom level Been having an issue with one of my maps that uses leaflet.js.
I have some elements that are present on the map at a zoom level of 6 and higher (as a reference, 1 is world view - so the higher the number the more granular the view).
I need to add a class when the map is at a zoom level greater than 6 to a class to ensure it doesn't appear on the map. I would need to ensure the function is continually loaded every time there is a change. I think this is an event listener?
Trouble is I am not terribly good with javascript and I am struggling to pull the information I need through. I have hit some roadblocks lately and my confidence is knocked.
I have some pseudo code I have written.
    function myFunction() {
if zoom > 4 {
    element.classList.add("disappear");
}
};

var element = document.getElementById("dma-marker-icon leaflet-marker-icon leaflet-zoom-animated leaflet-clickable");
myFunction() // Call listener function at run time
addListener(myFunction) // Attach listener function on state changes

Could you please help me refine this? Thanks so much.

A: There's an event on a leaflet map which fires after the map zoom has changed - zoomend. So if you listen for that event, you can add or remove the class on your target element accordingly. You don't show much of your code so the variable names here will probably not match yours, but ...
myMap.on('zoomend', myFunction);

function myFunction(e) {
   if myMap.getZoom() > 4 {
    element.classList.add("disappear");
 }
 else {
    element.classList.remove("disappear");
 }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: JSF page load is very slow I have a website with some images using the p:graphicsimage tag with the rendered attribute. So the images are only shown if the bean (db query) returns a true.
I also have a login form checking the user against a db. This works fine but my current problem is that the page needs a lot of time for loading the page(arround 25sec).
The bean method of the loginbutton is called ~20sec after pressing the loginbutton but I don't know what the server is doing during this time. Any idea how to check the server states or how to fix that problem?
My beans are ManagedBeans
Thanks in advance!

A: You can debug your method and benchmark the potential areas very old-school like
long startTime = System.currentTimeMillis();
method();
long endTime = System.currentTimeMillis();
System.out.println((endTime - startTime) + "ms")

or use a profiler like yourkit.

A: There are a couple of things you can do to improve performance of your screens

*

*GZIP filter will reduce the initial load time significantly. It compresses the page contents while transferring to client browser. Refer to https://stackoverflow.com/a/35567295/5076414

*You can additionally implement a cacheFilter to bring performance of
your screens at par with JavaScript based UI.  This will cache the static content of your screen such as icons, images, stylesheets, javascripts etc. You can control what to cache and what to exclude. Refer to https://stackoverflow.com/a/35567540/5076414

*For client side UI components, you can use Primefaces which is JQuery
based UI.

How to verify if my screen is using gzip and cache
To see if your contents are already usign gzip and cache, In your Google Chrome Browser -> right click on your screen -> inspect -> click network tab -> refresh your screen.
Click on the images, icons, stylesheets and see if you see following in response header
Cache-Control:max-age=2592000 if the status of element is 304 (coming from cache)
Content-Encoding:gzip if the status of element is 200


text:
Q: Spring STS - unable to resolve properties This question is not related with spring, but with STS tool suite or with spring eclipse IDE. Given following declaration of the class
@Configuration()
@Import({ WebSharedConfig.class, SpringSecurityConfig.class })
@ComponentScan({ "com.finovera.web", "com.finovera.platformServices","com.finovera.authentication" })
@PropertySources(value = { @PropertySource({ "${FINOVERA_PROPERTIES}" }),
@PropertySource(value = { "${STATIC_OVERRIDE_PROPERTIES}", }, ignoreResourceNotFound = true) })
@Scope("singleton")
@EnableTransactionManagement
public class CabinetConfig extends WebMvcConfigurationSupport {
}

I am seeing following exception in STS plugin (org.springframework.ide.eclipse.beans.core)
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.finovera.web.config.CabinetConfig]; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'FINOVERA_PROPERTIES' in string value "${FINOVERA_PROPERTIES}"
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:181)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321)

Error is simple as properties name is passed to JVM when application starts. The application run time code works fine, but STS does not. Lot of functionality missing as main configuration scan fails. Commenting out property sources annotation, everything works fine.
How do I pass property value to STS or convince it to ignore PropertySources annotation?

A: I think this is a limitation in the current implementation. Please file an enhancement request against: https://issuetracker.springsource.com/browse/STS and we can try to fix this for the next release of STS and Spring IDE.


text:
Q: Keep text in BasicTextField on back navigation I have a BasicTextField in my jetpack compose function. When i click(user has input some text into the textfield by now) on a button to navigate to another composable in my NavHost, and from that new view click on back to the composable which i came from which has the textfield, the textfield is empty. I want to keep the text that the user typed in before navigating, but I can't figure it out how. Have looked here but found no answer.
Suggestions?
Here is my code:
@Composable
fun SearchBar(
    modifier: Modifier = Modifier,
    onSearch: (String) -> Unit = {}
) {
    var text by remember {
        mutableStateOf("")
    }

    Box(modifier = modifier) {
        BasicTextField(
            value = text,
            onValueChange = {
                text = it
                onSearch(it)
            },
            maxLines = 1,
            singleLine = true,
            textStyle = TextStyle(color = Color.Black),
            modifier = Modifier
                .fillMaxWidth()
                .shadow(5.dp, CircleShape)
                .background(Color.White, CircleShape)
        )
    }
}

A: remember saves the value over recomposition (i.e., when your state changes, your composable automatically recomposes with the new state).
As per the Restore UI State guide, you can replace remember with rememberSaveable to save your state across:

*

*Configuration changes

*Process death and recreation

*Your composable being put on the NavHost back stack

As well as any other case where your SearchBar could be removed from composition and then re-added (such as if you were using in Accompanist's Pager or in a LazyColumn or LazyRow).
var text by rememberSaveable {
    mutableStateOf("")
}


text:
Q: Debian loses harddisk on bootup 4 times and then boots. Why? Dmesg Dump:
http://paste.debian.net/44975
at time 32.832045
That error is delaying my boot process significantly.
Does anyone know what this is about?
Devices:
Maxtor IDE drive with new cable on primary master on a ASUS TUSL2-C board with Intel 815 Chipset and Pentium III Coppermine Processor.
Intel 82801BA IDE U100 controller.
Software:
Debian Wheezy on newest packages.
Kernel: Linux 3.2.0-4-686-pae #1 SMP Debian 3.2.46-1+deb7u1

A: According to this Ubuntu forums thread (which may or may not apply, but since you're running Debian it's worth a shot), this can be fixed with these steps:
Follow the instructions in the last section of the first post, titled Info about libata.force=... :, to figure out your libata configuration.

libata.force= [LIBATA] Force configurations. The format is comma
  separated list of "[ID:]VAL" where ID is PORT[.DEVICE]. PORT and
  DEVICE are decimal numbers matching port, link or device. Basically,
  it matches the ATA ID string printed on console by libata. If the
  whole ID part is omitted, the last PORT and DEVICE values are used. If
  ID hasn't been specified yet, the configuration applies to all ports,
  links and devices.
If only DEVICE is omitted, the parameter applies to the port and all
  links and devices behind it. DEVICE number of 0 either selects the
  first device or the first fan-out link behind PMP device. It does not
  select the host link. DEVICE number of 15 selects the host link and
  device attached to it.
The VAL specifies the configuration to force. As long as there's no
  ambiguity shortcut notation is allowed. For example, both 1.5 and 1.5G
  would work for 1.5Gbps. The following configurations can be forced.

*

*Cable type: 40c, 80c, short40c, unk, ign or sata. Any ID with matching PORT is used.

*SATA link speed limit: 1.5Gbps or 3.0Gbps.

*Transfer mode: pio[0-7], mwdma[0-4] and udma[0-7]. udma[/][16,25,33,44,66,100,133] notation is also allowed.

Once you've done that, add the line you found to grub.cfg. For example, if the above steps gave you libata.force=1:pio4, add
libata.force=1:pio4

to the kernel line in grub. You can test this by pressing e at the Grub menu and adding the line manually to the kernel line. If it works, edit the grub.cfg file:
sudo nano /etc/default/grub

and edit the contents of this line to add the appropriate command:
GRUB_CMDLINE_LINUX_DEFAULT="libata.force=1:pio4 quiet splash"

Then run sudo update-grub.
I make no promises that this will work, since I don't have a system that's experiencing this error to test it on, but it looks like others have run into a similar problem, so maybe these steps will work for you.


text:
Q: Regex expression in C++ and double backslash I'm reading a text file in the form of
People list
[Jane]
Female
31
...

and for each line I want to loop through and find the line that contains "[...]"
For example, [Jane]
I came up with the regex expression

"(^[\w+]$)"

which I tested that it works using regex101.com.
However, when I try to use that in my code, it fails to match with anything.
Here's my code:
void Jane::JaneProfile() {
    // read each line, for each [title], add the next lines into its array
    std::smatch matches;
    for(int i = 0; i < m_numberOfLines; i++) { // #lines in text file
        std::regex pat ("(^\[\w+\]$)");
        if(regex_search(m_lines.at(i), matches, pat)) {
            std::cout << "smatch " << matches.str(0) << std::endl;
            std::cout << "smatch.size() = " << matches.size() << std::endl;

        } else
            std::cout << "wth" << std::endl;
    }
}

When I run this code, all the lines go to the else loop and nothing matches...
I searched up for answers, but I got confused when I saw that for C++ you have to use double backslashes instead one backslash to escape... But it didn't work for my code even when I used double backslashes...
Where did I go wrong?
By the way, I'm using Qt Creator 3.6.0 Based on (Desktop) Qt 5.5.1 (Clang 6.1 (Apple), 64 bit)
---Edit----
I tried doing:
std::regex pat (R"(^\[\\w+\]$)");

But I get an error saying

Use of undeclared identifier 'R'

I already have #include <regex> but do I need to include something else?

A: Either escape the backslashes or use the raw character version with a prefix that won't appear in the regex:
escaped:
std::regex pat("^\\[\\w+\\]$");

raw character string:
std::regex pat(R"regex(^\[\w+\]$)regex");

working demo (adapted from OPs posted code):
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    auto test_data =
    "People list\n"
    "[Jane]\n"
    "Female\n"
    "31";

    // initialise test data
    std::istringstream source(test_data);
    std::string buffer;
    std::vector<std::string> lines;
    while (std::getline(source, buffer)) {
        lines.push_back(std::move(buffer));
    }

    // test the regex

    // read each line, for each [title], add the next lines into its array
    std::smatch matches;
    for(int i = 0; i < lines.size(); ++i) { // #lines in text file
        static const std::regex pat ("(^\\[\\w+\\]$)");
        if(regex_search(lines.at(i), matches, pat)) {
            std::cout << "smatch " << matches.str() << std::endl;
            std::cout << "smatch.size() = " << matches.size() << std::endl;
        } else
            std::cout << "wth" << std::endl;
    }

    return 0;
}

expected output:
wth
smatch [Jane]
smatch.size() = 2
wth
wth


text:
Q: How to detect fractal / pattern in image with OpenCv or Tensorflow? Consider this image

How to detect the fractal / template that builds up the whole image with OpenCV / Tensorflow?
I'm trying to extract the fractal from that image and output it as a new image.
Thanks in advance


text:
Q: How can I update a status for test case in ALM using REST API I have been tried to connect the ALM by using REST API, and successfully made the connection in ALM. But, I'm not sure how can I modify the entities(Test, TestLab, Requirements) status. I'm using JAVA as my programming language.
Example:
I have a test set which contains multiple test steps. I have to update the status as PASSED by using REST API.
Is anybody have a solution on this? please share some code snippet or ideas.

A: HP ALM help file has all the information you need to get started.
Afte you login to HP ALM (Thin Client), GoTO HELP -> API Reference -> RESTFUl API.
Not sure which scripting language you are using however your requirement could be achieved easily using simple CURL, Java, Python etc...
This would help someone who is new to HP REST API.

*

*To find available HP API end-points,

GET <QCSERVER>/qcbin/rest/resouce-list


text:
Q: how to decide which can be taken as first table and second table? To find the salesorders for all productsID along with productsID and name?
I wrote this cause the sales table also has productsID column.
select A.salesorderID, A.productsID, B.Name
from Production.productsID AS A
LEFT JOIN sales.salesorderID AS B
ON A.productsID = B.proudctsID

But the answer I saw is
select A.productsID, A.Name, B.salesorderID
from Production.productsID AS A
LEFT JOIN sales.salesorderID AS B
ON A.productsID = B.productsID

A: The decision is made based on how you want your output. The purpose of a left join is to join a table that has values you want to see to another table that MIGHT have values you want to see. The order is logical depending on which values you DON'T want to be left out of the query.
So, lets say I have a table of People with a relationship to a table of Pets.
People

ID
Name

1
John

2
Mike

3
Sue

Pets

ID
PersonID
Name

1
1
Foodo

2
2
Barrky

My organization is having a dog walking event and we want to invite all of our people. Simple, right? Done.
    SELECT * FROM People;

ID
Name

1
John

2
Mike

3
Sue

But wait, its a dog walking event, so I want to include the name of these peoples Pets on the invite. No big deal.
SELECT People.*, Pets.Name AS PetName FROM People INNER JOIN Pets on Pets.PersonID = People.ID;

Result:

ID
Name
PetName

1
John
Foodo

2
Mike
Barrky

Bam, now I have invites for all of my people and their pets.
But wait! The director doesn't want to limit this to ONLY people with pets. Anyone is invited! Its a walk-a-thon and after all, not ONLY people with pets can walk and donate money to my cause. So now, I want to get ALL of my people along with their Pet's name if they have one. THIS is how you decide which order the left join should be.
    SELECT People.*, Pet.Name
    FROM People LEFT OUTER JOIN
        Pets ON Pet.PersonID = People.ID;

Now my results are the below.

ID
Name
PetName

1
John
Foodo

2
Mike
Barrky

3
Sue
NULL

A: I'm guessing/assuming that B.Name is not the same as A.Name. A.Name is presumably the name of the Product (as it is coming from the Product table) whereas B.Name is the name of something in the sales order


text:
Q: setOnClickListener Android Button b1 = (Button) findViewById(R.id.button1);

OnClickListener list1 = new OnClickListener() {
    @Override
    public void onClick(View v) {
        startActivity(new Intent(MainActivity.this, Second.class));
    }
};

b1.setOnClickListener(list1);

How come we don't need to instantiate or initialize the View v which is passed to onClick? What object does it refer to?

A: The View v is actually the Button b1 if you press the button
If you press the button, View v will return the Object Button b1

A: android treat every element i.e textfield,button etc as views. here View v will return the object for the button which you are clicking i.e Button b1.

A: b1.setOnClickListener(list1); - This code of yours binds the list1 listener to your button b1's event of onClick.
Whenever there is a click - in this case - a touch, on the button b1, the onClick() method will be called which sends the handle(v) of the view which has triggered it(in your case - button b1).
Hence, the View v will be your handle to the view triggering the OnClickListener.

A: test the following..
protected void onCreate(Bundle savedInstanceState)
{
     Button b1 = (Button) findViewById(R.id.button1);
    b1.setOnClickListerner(this);
    .....
    .....
}

public void onClick(View v)
{
     if(v == b1)
    {
        // do stuff
    }
}

The code above and your code are both the same.  When you press the button, the reference of button object is passed in to onClick().


text:
Q: What's the technology used by the tiles at stackoverflow.com's site list? I'd like to use the tech for stackoverflow.com's site list. The dynamic tile layout is really cool. I wonder how it is built.
After viewing the code, I just find jquery js reference.
Is it built using jquery? If so, what module it uses exactly?


text:
Q: How do you call all list elements in a specific format in Python? I am trying to build an Employee Management System and am having difficulties printing all of the elements entered into a list in a specific format. I can get my last entry to print but if I have multiple list elements, it won't display them on the screen.  What am I doing wrong in my for loop or is there a better way to display them all in the format I have outlined?
employee_info = [ ]

while True: # While loop created to make the script constantly run
    counter = len(employee_info) # Counter created so that the user will know how many entries there are

    print('There are', '(', (int(counter)), ')', 'employees in the system.\n')

    add_new = input('Would you like to add a new employee to the system or view all employee entries in the system?\
    To add an employee, type: "ADD". To view all employees currently in the system, type: "VIEW ALL."\n') #Added option to add an employee or to view all employees currently the system

    if add_new == 'ADD':
        while True: # Loop created to input employees with option to quit
            employee_index = [input('Employee Name\n'), input('Employee SSN\n'), \
            input('Employee Telephone Number ***Entered as (555)555-5555*** \n'), input('Employee Email\n'), input('Employee Salary ***Entered as $xxxx***\n')]
            employee_info.append(employee_index)
            more_employees = input('Would you like to add another employee? Y or N.\n')
            if more_employees == 'Y':
                continue
            elif more_employees == 'N':
                break

    elif add_new == 'VIEW ALL':
        for x in employee_info:

            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')


text:
Q: PosGIS KNN returns different results from QGIS hub spoke function Following example here I have tried to get nearest neighbours where code is;
CREATE TABLE model.hub_spoke_spokes3f AS
SELECT
   hub.id AS hub_id,
   spoke.id,
   spoke.point_geom,
   ST_Distance(hub.geom, spoke.point_geom) AS dist
FROM hub_data.geom_data_unique AS hub
JOIN LATERAL (
SELECT id,
     point_geom
FROM spoke_data.data_set
WHERE ST_DWithin(hub.geom, point_geom, 150000) --geom is 277000, units metres
AND hub.id <> id
ORDER BY hub.geom <-> point_geom
LIMIT 100
) AS spoke
ON TRUE;

I then compared the results with QGIS Hub and spoke function which I was trying to replicate.

As screen shot below the results differ. The lines are created by QGIS but the spokes (smaller dots) are from the query above. Whats causing the difference?

A: Order of the join is crucial here; your query selects the 100 nearest points (with different id) to each hub (and cross-joins them with the respective hub), whereas you rather want to select the one closest hub to each point.
The LATERAL join will execute the right hand (table) expression for each row of the left hand table.
Running
CREATE TABLE model.hub_spoke_spokes3f AS
  SELECT b.id AS hub_id,
         a.id AS spoke_id,
         ST_Distance(a.geom, b.geom) AS dist,
         a.point_geom
         -- ST_MakeLine(b.geom, a.geom) AS spoke_geom
  FROM   spoke_data.data_set AS a
  JOIN LATERAL (
    SELECT q.id,
           q.geom
    FROM   hub_data.geom_data_unique AS q
    ORDER BY
           q.geom <-> a.geom
    LIMIT  1
  ) AS b
  ON true;

will assign the hub_id of the closest hub to each of your points. With the (out-commented) ST_MakeLine you will get the corresponding lines between them.
I used to get just a bit better performance with the ON true construct; since PostgreSQL > 10, this has become equal to <table_a>, LATERAL (<expression>) or <table_a> CROSS JOIN LATERAL (<expression>). Not sure why.

Note that this is slightly different to the 'Join by lines (hub lines) - Hub and Spokes' function, that connects points to hubs with lines (spokes) based on a common attribute. If I get that right, you would then just join both tables on e.g. hub.id = spoke.hub_id.


text:
Q: How can I ensure that an environment variable is set for a user in a bash session? How can ensure that a environment variable is set for a user?  I have
MYVAR=whatever
export MYVAR

in the ~/.bash_profile but a report from the user suggests that it hasn't worked for them.  What could have happened?

A: Some excerpts from the bash manpage:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
...
When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of /etc/bash.bashrc and ~/.bashrc.

Could this explain why it "hasn't work for them"?

A: Use the PAM module called pam_env to set enviroment variables on login. If you use this solution, the environment variables will be available to GUI programs launched directly from the "Window Manager" (e.g. GNOME, KDE) too, not only to programs launched from a terminal. Also, the user can use another shell, not only Bash. Maybe this article from O'Reilly can help you.

A: It should probably be set in ~/.bashrc if it's not the login shell, for example if they are running a terminal in Gnome.
Also, you list the file as ./bash_profile but that gives no indication of where that file is (it says it's in the current directory). I assume you mean /etc/bash_profile. That file is only used for login shells or non-interactive ones.

A: From within your code, you could do:
if [ x"$MYVAR" = "x" ]
    then
    echo "it didn't work"
    exit 1
fi
echo "it did work: $MYVAR"

if you're setting it from something like the user's own .bash_login or .bashrc, are they sudo'ing out of their environment?
Exporting a variable will only work if the subsequent use of that variable is dependent to the export; i.e., export during their login process should work for anything they run, unless they su/sudo, in which case they're actually leaving that environment and then executing whatever they're doing.

A: jjujuma
First ensure that the user is using bash.  He/She might be using csh.  If you want it set for just that user and they are using bash/sh then you need to put it in the .bashrc file. If csh/tcsh you need to put it in the .cshrc/.tcshrc.   If you want it set globally for all users /etc/profile and /etc/csh.cshrc for bash/tcsh respectfully will get you up and going!
HTH


text:
Q: An affine subset of the product of Grassmanians Recall the Grassmanian $G(2,4)$ is cut out in $\mathbb{P}^5$ by the equation $a_{12}a_{34}-a_{13}a_{24}+a_{14}a_{23}=0$.
Let $X$ be the subset of $G(2,4)\times G(2,4)\subset\mathbb{P}^5\times\mathbb{P}^5$ which is the complement of $V((a_{12}b_{34}-a_{13}b_{24}+a_{14}b_{23})+(b_{12}a_{34}-b_{13}a_{24}+b_{14}a_{23}))$, where the $a$ and $b$ are coordinates on the first and second $\mathbb{P}^5$ factors respectively.

How to show $X$ is affine?

My feeling is this can probably done in a coordinate-free way, too?
Thank you.

A: It has nothing to do with the Grassmanian. Consider the Segre embedding
$$\begin{split} \mathbb P^5\times \mathbb P^5 &\to \mathbb P^{35}, \\([X_0, \cdots X_5],[Y_0, \cdots, Y_5])&\mapsto [X_0Y_0, X_0Y_1, \cdots, X_iY_j\cdots X_5Y_5]
\end{split}$$
then $(a_{12}b_{34}-a_{13}b_{24}+a_{14}b_{23})+(b_{12}a_{34}-b_{13}a_{24}+b_{14}a_{23})$ is a pullback of a linear function on $\mathbb P^{35}$. Thus under the embedding, $\mathbb P^5\times \mathbb P^5\setminus V$ lies in an affine space of $\mathbb P^{35}$, thus is affine. Thus $G(2, 4)\times G(2, 4)\setminus V$ is also affine.


text:
Q: How to get my app to fill the full height on mobile? As you can see in the screenshot that I took on my iPhone below, the app has a bunch of white space at bottom of the page. This is only happening on mobile. How can I make the page fill the entire screen?

css:
.landing-bg2 {
    background: asset-url("startupstock1.jpg") no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

}

html:
    <div class="landing-bg2 size">
   .....contents of webpage
    </div>

Edit!
I'm able to use the following:
.landing-bg2 {
    background: asset-url("startupstock1.jpg") no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
  min-height: 100%;
  min-width: 1024px;

  /* Set up proportionate scaling */
  width: 100%;
  height: auto;

  /* Set up positioning */
  position: fixed;
  top: 0;
  left: 0;
}

However, I'm then only limited to one BG, if I'd like to have another BG below as your scroll down they just both overlap since they're fixed.. so still looking for a solution.

A: trying move the background to body tag:
body{
    background: asset-url("startupstock1.jpg") no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}


text:
Q: "invalid column name" error when retrieving data from SQL database? I have a database with 3 columns on it: FIRST_NAME, LAST_NAME, and IMAGE. I always get the error "invalid column name 'the name from the first column'." I am supposed to write the first name and click a button to show the last name and the image. I am using C#, this is my current code:
        private void button_show_Click(object sender, EventArgs e)
    {
        try
        {
            string sql = "select LAST_NAME,IMAGE from Table_1 where FIRST_NAME=" + this.firstname_textbox.Text + "";
            if (conn.State != ConnectionState.Open)
                conn.Open();
            command = new SqlCommand(sql, conn);
            SqlDataReader reader = command.ExecuteReader();
            reader.Read();
            if (reader.HasRows)
            {
                lastname_textbox.Text = reader[0].ToString();
                byte[] img = (byte[])(reader[1]);
                if (img == null)
                pictureBox1.Image = null;
                else
                {
                    MemoryStream ms = new MemoryStream(img);
                    pictureBox1.Image = Image.FromStream(ms);
                }

            }
            else
            {
                MessageBox.Show("This Name Does Not Exist");
            }
            conn.Close();
        }
        catch(Exception ex)
        {
            conn.Close();
            MessageBox.Show(ex.Message);
        }
    }
}

Thanks.

A: You have an unquoted string in your WHERE clause.
string sql = "select LAST_NAME,IMAGE from Table_1 where FIRST_NAME=" + this.firstname_textbox.Text + "";

should be:
string sql = "select LAST_NAME,IMAGE from Table_1 where FIRST_NAME='" + this.firstname_textbox.Text + "'";

You should also know that using string concatenation for SQL query parameters is bad practice as it creates a SQL Injection vulnerability. For example, imagine the result if this.firstname_textbox.Text was:
';DELETE FROM Table_1 WHERE '1' = '1

This would result in the variable "sql" being this:
select LAST_NAME,IMAGE from Table_1 where FIRST_NAME='';DELETE FROM Table_1 WHERE '1' = '1'

To avoid this problem, use parameterized queries (https://msdn.microsoft.com/en-us/library/vstudio/bb738521%28v=vs.100%29.aspx)


text:
Q: Can I control broken iPad from computer? My iPad's touch screen was broken about 1 year ago. I've dropped bottle on the screen and now the touch screen not working. I've sent it to service but the service hadn't repaired it, but the iPad is still working without touch.
Is it possible to control the iPad from my PC? if it's possible, I'd like to install an app called Duet Display to use my iPad as a second monitor.

A: My iPad Mini has the similar broken screen, why not go to the third party service to change a new screen, which works well.
You can transfer files between iPad and computer, however it can't work as the second monitor.


text:
Q: Google Maps Geocoding API: How to get city/region names *consistently* in English or local language? When I make the following request (note the language=en part!) with latitude & longitude for Warsaw, Poland,
https://maps.googleapis.com/maps/api/geocode/json?latlng=52.23,21.01&language=en
I get a result list which includes the following:
Result 3 (neighborhood):

    {
            "address_components" : [
               {
                  "long_name" : "Śródmieście Północne",
                  "short_name" : "Śródmieście Północne",
                  "types" : [ "neighborhood", "political" ]
               },
               {
                  "long_name" : "Śródmieście",
                  "short_name" : "Śródmieście",
                  "types" : [ "sublocality_level_1", "sublocality", "political" ]
               },
               {
                  "long_name" : "Warszawa",   <-- city in Polish
                  "short_name" : "Warszawa",
                  "types" : [ "locality", "political" ]
               },
               {
                  "long_name" : "Warszawa",
                  "short_name" : "Warszawa",
                  "types" : [ "administrative_area_level_3", "political" ]
               },
               {
                  "long_name" : "Warszawa",
                  "short_name" : "Warszawa",
                  "types" : [ "administrative_area_level_2", "political" ]
               },
               {
                  "long_name" : "mazowieckie",  <-- region in Polish
                  "short_name" : "mazowieckie",
                  "types" : [ "administrative_area_level_1", "political" ]
               },
               {
                  "long_name" : "Poland",
                  "short_name" : "PL",
                  "types" : [ "country", "political" ]
               }
            ],
         [...]
         "place_id" : "ChIJjaxkh4rMHkcR1lza9qbbnrU",
         "types" : [ "neighborhood", "political" ]
    }

Result 4 (sublocality_level_1):

      {
         "address_components" : [
            {
               "long_name" : "Śródmieście",
               "short_name" : "Śródmieście",
               "types" : [ "sublocality_level_1", "sublocality", "political" ]
            },
            {
               "long_name" : "Warsaw",   <-- city in English
               "short_name" : "Warsaw",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Warszawa",
               "short_name" : "Warszawa",
               "types" : [ "administrative_area_level_3", "political" ]
            },
            {
               "long_name" : "Warszawa",
               "short_name" : "Warszawa",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Masovian Voivodeship",  <-- region in English
               "short_name" : "Masovian Voivodeship",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "Poland",
               "short_name" : "PL",
               "types" : [ "country", "political" ]
            }
         ],
         [...]
         "place_id" : "ChIJ8e41PvbMHkcRit4n8qe36Ns",
         "types" : [ "sublocality_level_1", "sublocality", "political" ]
      },

The main problem with this is the inconsistency for the same address components (locality, administrative_area_level_1) - sometimes English (as requested), sometimes the local language. Without some other ID to know that these refer to the same administrative reality, I can't be sure of that, unless I used another source of English & local geo names and did some pattern matching.
Is there a way to get around this problem? Or could someone suggest a reverse geocoding service not having such issues?
Many thanks!

A: I ran into the same problem. I wrote an if/else group to grab location data in order of preference.
foreach ($data->results[0]->address_components as $stuff) {
    // city
    if ($stuff->types[0] == 'locality') {
        $zip->locality_short = $stuff->short_name;
        $zip->locality_long = $stuff->long_name;
    } elseif ($stuff->types[0] == 'sublocality_level_1') {
        $zip->locality_short = $stuff->short_name;
        $zip->locality_long = $stuff->long_name;
    } elseif ($stuff->types[0] == 'neighborhood') {
        $zip->locality_short = $stuff->short_name;
        $zip->locality_long = $stuff->long_name;
    }
    // state
    if ($stuff->types[0] == 'administrative_area_level_1') {
        $zip->location_short = $stuff->short_name;
        $zip->location_long = $stuff->long_name;
    }
    // country
    if ($stuff->types[0] == 'country') {
        $zip->country_short = $stuff->short_name;
        $zip->country_long = $stuff->long_name;
    }
}


text:
Q: alchemy API doesnt accept my local file Here is my request:
> curl -i -H "Accept: application/json" -H "Content-Type:
> application/json" -X GET
> http://access.alchemyapi.com/calls/image/ImageGetRankedImageKeywords?apikey=<key>&image=file%3A%2F%2Ftmp%2Fimage.jpg&imagePostMode=not-raw&outputMode=json

Following http://www.alchemyapi.com/api/image-tagging/image.html
Response:

HTTP/1.1 200 OK Server: nginx Date: Wed, 13 May 2015 04:27:56 GMT
  Content-Type: application/xml; charset=utf-8 Content-Length: 440
  Connection: keep-alive Cache-Control: no-cache
  X-AlchemyAPI-CurrentVersion: 12.15 X-AlchemyAPI-Error-Msg:
  content-is-empty X-AlchemyAPI-Key:  X-AlchemyAPI-Params:
  sentiment=0&knowledgeGraph=0&detectedLanguage=unknown&submitLanguage=detect
  X-AlchemyAPI-Status: ERROR X-AlchemyAPI-Total-Transactions: 4
  Access-Control-Allow-Origin: *

      ERROR
      content-is-empty
      By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of
  Use: http://www.alchemyapi.com/company/terms.html

      4

Why?
The image exists:
$ ls -l /tmp/trash1.jpg
-rw-r-----@ 1 xx  staff  47846 May 12 15:49 /tmp/image.jpg
$

A: Their support helped me.
Essentially i need to POST the image directly.
Can't use the "image" parameter and filling it with the name of the local file. That parameter actually needs to contain the contents of the image file instead. So instead need to use imagePostMode=raw, and just add the file as the post body, which I would recommend. Something like this:
wget -qO- --post-file YOUR_IMAGE.png "http://access.alchemyapi.com/calls/image/ImageGetRankedImageKeywords?apikey=API_KEY&imagePostMode=raw"


text:
Q: Systemd calendar interval, "Failed to parse calendar specification" I'm on Ubuntu 16.04.  When I try to use the time syntax show here (Mon..Fri) I get an error.  It seems I have to use 'Mon-Fri'.
$ sudo systemctl status mytouch.timer
● mytouch.timer - Runs mytouch every hour
   Loaded: error (Reason: Invalid argument)
   Active: inactive (dead) since Thu 2018-12-13 16:16:35 UTC; 1h 11min ago

Dec 13 17:15:20 ip-10-0-0-123 systemd[1]: [/etc/systemd/system/mytouch.timer:5] Failed to parse calendar specification, ignoring: Mon..Fri 22:30
Dec 13 17:15:20 ip-10-0-0-123 systemd[1]: mytouch.timer: Timer unit lacks value setting. Refusing.

Also, I had problems putting the time zone after the date, such as: 2003-03-05 05:40:00 UTC.
Finally, I have seen the suggestion to use systemd-analyze calendar but that produces this error:
$ systemd-analyze calendar Mon,Wed,Fri,Sat\ \*-\*-\*\ 11:00:00
Unknown operation 'calendar'.

Where do I find documentation for the version of systemd I'm running.

A: for ubuntu 16.04, the time syntax is http://manpages.ubuntu.com/manpages/xenial/man7/systemd.time.7.html, which is slightly different with the 'standard'.
for systemd-analyze, the ubuntu 16.04 version is also different. below is the output of
systemd-analyze -h
Commands:
  time                    Print time spent in the kernel
  blame                   Print list of running units ordered by time to init
  critical-chain          Print a tree of the time critical chain of units
  plot                    Output SVG graphic showing service initialization
  dot                     Output dependency graph in dot(1) format
  set-log-level LEVEL     Set logging threshold for manager
  set-log-target TARGET   Set logging target for manager
  dump                    Output state serialization of service manager
  verify FILE...          Check unit files for correctness

A: Edited on 2021/08/10 thanks to @jcomeau_ictx's comment I realized that I had wrongly read the question and provided a misguided answer with a a buggy command as well.
The doted command is indeed partially supported on older versions and you have to use - instead.
I do not have access to older versions anymore, so I can't verify what works and what doesn't anymore (.. can be used to list days for example).
However, you can still use the systemctl list-timers command to see where you stand.
As kindly mentioned by @echo, the systemd-analyze calendar is not available on the 16.04.
I could use it only starting the 18.04 Ubuntu and I don't think there is an equivalent command on older versions.
Good luck.


text:
Q: how to set Data context of command in itemcontrols in wpf how to set Data context of command in itemcontrols in wpf
<controls:ImageButton x:Name="CardEditButton" DataContext="{Binding ElementName=AutofillTab, Path=DataContext}"                                                                                ImagePath="Media\Core\WhiteEditButton.png"  Height="24" Width="24"                                                                                Command="{Binding EditCommand}"  Margin="0 0 40 0" HorizontalAlignment="Right" VerticalAlignment="Center">
</controls:ImageButton>

this command not working when add in itemcontrolTemplate
                    <ItemsControl ItemsSource="{Binding Cards, UpdateSourceTrigger=PropertyChanged}" MinHeight="200" x:Name="CardsItemsControl">
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <Button Width="265" VerticalAlignment="Bottom" Height="40"  HorizontalAlignment="Center"  Cursor="Hand"
                                    Background="{Binding Model.Color,Converter={StaticResource CardColorToBrushConverter}}" Margin="16 12 16 0"
                                    Foreground="White"
                                    Content="{Binding Name}"
                                    x:Name="ItemButton" MouseLeave="ItemButton_MouseLeave" MouseEnter="ItemButton_MouseEnter">

                                    <Button.Template>
                                        <ControlTemplate  TargetType="Button">
                                            <Grid ClipToBounds="True" Name="TemplateGrid"  >
                                                <Rectangle Name="Rect" Width="{TemplateBinding Width}" Fill="{TemplateBinding Background}" RadiusX="8" RadiusY="8" Height="40"  />

                                                <StackPanel Orientation="Horizontal">
                                                    <controls:AutoGrid Columns="Auto,*" >
                                                        <TextBlock Text="{TemplateBinding Content}" FontSize="16" Grid.Column="1" FontWeight="Bold" TextTrimming="CharacterEllipsis"
                                                                VerticalAlignment="Center" Foreground="{TemplateBinding Foreground}" Margin="8 8 0 8"></TextBlock>

                                                    </controls:AutoGrid>
                                                </StackPanel>
                                                <controls:ImageButton x:Name="ExtendButton" Visibility="Hidden"  ImagePath="Media\Core\InfoButton.png" ImageHeight="24" ImageWidth="24"  Click="Item_OnClick"  Margin="0 0 8 0" HorizontalAlignment="Right" VerticalAlignment="Center">

                                                </controls:ImageButton>
                                                <controls:ImageButton x:Name="CardEditButton" DataContext="{Binding ElementName=AutofillTab, Path=DataContext}"
                                                                                ImagePath="Media\Core\WhiteEditButton.png"  Height="24" Width="24"
                                                                                Command="{Binding EditCommand}"  Margin="0 0 40 0" HorizontalAlignment="Right" VerticalAlignment="Center">
                                                </controls:ImageButton>

                                            </Grid>

                                        </ControlTemplate>

                                    </Button.Template>

                                </Button>

                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>

A: Instead of trying to bind the DataContext of the button, use a RelativeSource binding on the Command property and look for an ancestor that has the DataContext you need. In this case I'm guessing it might be the ItemsControl.
<controls:ImageButton x:Name="CardEditButton"
    ...
    Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}},
        Path=DataContext.EditCommand}" />


text:
Q: Are there any tools to monitor IIS requests on a 64 bit server? Are there any tools available to monitor all current IIS requests on a server? I have some requests that are hanging, and I'd like to be able to identify which requests are hung, and then kill those specific requests, without affecting the rest of the requests, or the server itself.
I know that the IIS toolkit has a tool called "Requests Viewer" that does most of what I need, but it doesn't work on a 64 bit server.
Does anyone know of a tool that will do this?

A: Did you try the x64 Trace Diagnostics tools? I haven't run IIS Request Viewer before, but it certainly appears that it would work on x64....
Edit: Trace Diagnostics specifically calls out "Windows Server 2003 Service Pack 2 x64 Edition" as a supported OS. Perhaps you have some other issue? Are you sure you're on x64 (yeah - I know, it's an odd question, but sometimes you have to ask...it could be ia-64 (Itanium))

A: You might be able to install a proxy before IIS that logs the requests.


text:
Q: Assembly FPU Stack Breaking; Resulting in -1.#IND I'm newish to assembly in general, and especially to usage of the FPU.
I'm writing an assignment for school that calculates the Standard Deviation of an array of random numbers.
The array is loaded and the mean calculation works fine.  The entire process works for an array of 7 values or smaller, but returns -1.#IND (This means NaN?) for an array size of 8 or more elements.
Something is happening within the loop that sums the (mean - element)^2 values.  I'm not sure what's happening, but I'm assuming the FPU stack is breaking in some way.
If anyone can point me in the right direction, I'd be thoroughly pleased.
fla = REAL8
; STD DEVIATION
stdDev:
        call    meanCalcFunc            ; fmean = loaded

        mov     ebx, offset array1      ; Location of Element into EBX
        mov     ecx, [esp+4]            ; ECX = num of elements in array
        mov     mem1, 0                 ; Mem1 = 0
        fld     mem1                    ; ST = 0
        fstp    fla                     ; fla = ST = 0

mainFunc:
        mov     eax, [ebx]              ; Array Element into EAX
        mov     mem1, eax               ; Array Element into mem1
        fld     fmean                   ; ST = mean of array

        fisub   mem1                    ; mean - element -> ST

        fld     ST                      ; Now ST and ST(1) = difference of mean - element
        fmulp   ST(1), ST               ; Difference^2 in ST(1)

        fld     ST(1)                   ; Copy Difference^2 to ST

        fadd    fla                     ; FLA += Difference^2
        fstp    fla

        add     ebx, 4                  ; Move to next element in array
        loop    mainFunc

        fld     fla                     ; ST = Sum of squares

        mov     ecx, [esp+4]            ; Num of elements to ECX
        mov     mem1, ecx               ; Num of elements to mem1

        fidiv   mem1                    ; ST = Sum of squares / num of elements

        fst     fla

        fsqrt                           ; ST = final result

        fstp    fla                     ; flb = final result

        INVOKE _gcvt, fla, 8, ADDR outstring
        output  devlbl, outstring

        ret

A: Your loop contains an unbalanced number of loads and pops, so each loop iteration leaves one more item on the x87 stack.  When the stack overflows, you get the result you are observing.  Don't do that.
instruction        elements on stack
-------------------------------------------
mainFunc:          k
fld     fmean      k + 1
fisub   mem1       k + 1
fld     ST         k + 2
fmulp   ST(1), ST  k + 1
fld     ST(1)      k + 2
fadd    fla        k + 2
fstp    fla        k + 1
loop    mainFunc   k + 1


text:
Q: Go, Golang : external package import with GOROOT Go, Golang : does not make sense that I have to have files before import
I am trying to go to next step but keep getting errors

*

*I have the package that I want to import ready.

*All I need to do is to import the external package from github and be able to use it on any code.

So this is what I did.
mkdir $HOME/go
export GOPATH=$HOME/go
go get github.com/user/project

This runs successfully. I downloaded it onto here with source code files from github
/Users/user/go/src/github.com/user/project/project.go

So to use this package that I just import I do
go run /Users/user/Desktop/code.go

But I am getting the following errors
 MacBook-Air:~ user$ go run /Users/user/Desktop/code.go
 Desktop/code.go:32:8: cannot find package "project" in any of:
        /usr/local/go/src/pkg/project (from $GOROOT)
        /Users/user/go/src/project (from $GOPATH)

What should I do? AM I missing something? Thanks in advance and please help me. I wrote a lot of code but being very frustrated not being able to distribute it because of this.

A: The error message says at line 32 in your code.go it can't find package "goling".
Assuming that is a local package you want to use, you need to make sure it is in your GOPATH.
If you set GOPATH then you should develop your code within it, so moving the "goling" directory into /Users/user/go/src is the right thing to do.
Alternatively "goling" could be a typo, so check the imports in code.go. If you want to import an project from github the import should say
import "github.com/user/project"

And you then use the parts of project with a prefix of project.
If that doesn't help you get it working, then post the imports section of code.go.

A: It looks like you've got the external package in the same folder as your main package which uses it. In go, all packages must be in separate directories. It looks like the github project itself is actually doing that. If you separate the packages into different directories it should work properly.


text:
Q: Zyan Communication Framework - Public key changed since the message was encrypted I'm trying to setup a simple RPC client/server communication using the Zyan Communication Framework using a TCP duplex channel, but I keep getting the same error when the client tries to connect to the server "Public key changed since the message was encrypted".
I have explicitly set encryption to false in both client and server, so I can't see a reason for that error.
For demonstration purposes, I have setup a sample demonstrating the problem
Versions:

*

*NET version 4.5.2

*Zyan 2.6.2

using System;
using System.Threading;
using Zyan.Communication;
using Zyan.Communication.Protocols.Tcp;

namespace StackOverflowMinimalSample
{
    public interface ISampleService
    {
        string GetGreeting();
    }

    public class SampleService : ISampleService
    {
        public string GetGreeting()
        {
            return "Hello World";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int port = 5252;
            Thread serverThread = new Thread(() =>
            {
                var protocol = new TcpDuplexServerProtocolSetup(port){Encryption = false};
                using (var tcpHost = new ZyanComponentHost("TCPCommunication", protocol))
                {
                    tcpHost.RegisterComponent<ISampleService, SampleService>();

                    Console.WriteLine("Press [Enter] to exit");
                    Console.ReadLine();
                }

            })
            {IsBackground = true};
            serverThread.Start();

            Thread clientThread = new Thread(() =>
            {
                // Sleep for a while to give time to the server
                Thread.Sleep(5000);

                var protocol = new TcpDuplexClientProtocolSetup(encryption: false);
                var url = protocol.FormatUrl("127.0.0.1", port, "TCPCommunication");

                try
                {
                    using (var connection = new ZyanConnection(url))
                    {
                        ISampleService proxy = connection.CreateProxy<ISampleService>();
                        string serverMessage = proxy.GetGreeting();

                        Console.WriteLine("Server message: " + serverMessage);
                    }
                }
                catch (Exception e)
                {
                    // This will throw here.
                    Console.WriteLine("Exception caught: " + e.Message);
                }

            })
            {IsBackground = true};
            clientThread.Start();

            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();
        }
    }
}

A: https://zyan.codeplex.com/discussions/453233
"you're using duplex TCP channel to connect within the same AppDomain. TcpEx channel doesn't support this by design.
Please use either IpcBinary channel or NullChannel to connect within the same application domain."


text:
Q: Jquery script works in JSfiddle but not on html page I created a JSFiddle which works as intended.
//Jquery script
function icon_hover()
{
    $("#gcp-icon").hover( function(){
       $("#gcp-icon-hover").slideDown();
 },
 function(){
    $("#gcp-icon-hover").slideUp();
});
}

icon_hover();

   //CSS
.site_logo{
    width: 250px;
    height: 250px;
    background-color: rgba(0, 0, 0, 0.75);
}
.site_logo_hover{
    width: 250px;
    height: 250px;
    background-color:#000000;
    opacity:0.6;
    display:none;
}

#gcp-icon
{
    background: url(http://i.imgur.com/soDjoS4.png) no-repeat center center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

.hover_title{
    color: white;
    width: 220px;
    margin-left: auto;
    margin-right: auto;
    padding-top: 80px;
    font-weight: 600;
    font-size: 11pt;
    font-family: verdana;
}

.hover_text{
    color: white;
    width: 245px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 25px;
    font-family: verdana;
    font-size:9pt;
}

.click_me{
    color: white;
    width: 160px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 8px;
    font-weight: 600;
    font-size: 10pt;
    font-family: verdana;
}

Grace Cook Photography

Simple, subtle, clean and good looking

Click for more details

However, as the title suggests, when this is copied and pasted into a html page and opened in a web browser see this, this doesn't work as intended.
I have tried debugging. The Javascript is valid and all dependencies(eg. Jquey.js etc.) are available.

A: The problem might be, in jsfiddle the script was executed on dom ready (fiddle not working outside the dom ready handler).... but in your page it doesn't look like that
In jsfiddle the second dropdown in the LHS panel selects the place where the script will be added, by default it is added as a window.onload handler.
So move the invocation of icon_hover to a dom ready handler
jQuery(function(){
    icon_hover();
})

Demo: Fiddle

A: you should use always ready event when  you are working on webpage...
$(function(){
icon_hover();

});

A: Put your startup method bindings inside.document ready.
$(document).ready(function(){//your code here.});

Also check for any duplicate html elements having same Id.

A: $( document ).ready( function() {
    $("#gcp-icon").hover(
        function () {
            $( "#gcp-icon-hover" ).slideDown();
        },
        function () {
            $( "#gcp-icon-hover" ).slideUp();
        }
    )
})

A: If you check carefully on jsfiddle... When you select your JS library (jQuery 1.10.1 in your case) underneath this option jsFiddle automatically selects for you onLoad.
What this does is it puts all your javascript code within a
$(window).load(function()
{
    //yourcode from jsfiddle goes in here
}

This will load your js code when the windows loads.

A: $(document).ready(function(){icon_hover();});


text:
Q: Getting an unknown provider error with a specific module when minifying When I build my code together, I'm getting an error instantiating the main module because it has a dependency on the below module, which is also getting an error instantiating.  As far as I can tell I'm doing everything right to minsafe the module, but am I missing something?
angular.module('exceptionOverride').config(function($provide) {
    $provide.decorator('$exceptionHandler', ['$delegate', '$injector',function($delegate,$injector) {
        return function(exception, cause) {
            var $rootScope = $injector.get('$rootScope');
            var loggerService = $injector.get('loggerService');
            $delegate(exception, cause);
            exception.message = $rootScope.currentState + ': ' + exception.message;

            //send the exception off to the logging service
            loggerService.log(exception);
        };
    }]);
});

I can add code for other modules if you think it's needed.

A: You also have to do the config function: (notice the ['$provide', function($provide){ ...)
angular.module('exceptionOverride').config(['$provide', function($provide) {
    $provide.decorator('$exceptionHandler', ['$delegate', '$injector',function($delegate,$injector) {
        return function(exception, cause) {
            var $rootScope = $injector.get('$rootScope');
            var loggerService = $injector.get('loggerService');
            $delegate(exception, cause);
            exception.message = $rootScope.currentState + ': ' + exception.message;

            //send the exception off to the logging service
            loggerService.log(exception);
        };
    }]);
}]);


text:
Q: Windows Azure: System.UnauthorizedAccessException: Access to the path 'E:\approot\ I have an xml file in my project that is supposed to be for used for read operations. And it works the project works fine when i run it on my local machine, however it throws System.UnauthorizedAccessException: Access to the path 'E:\approot\... when i deploy the worker role.
I have checked that the file exists in that directory.
How can i fix this issue?
Thank you.

A: You need to run role in elevated mode...by adding
< Runtime executionContext ="elevated" /> in csdef.


text:
Q: Does D3 have a "link analysis" type graph? I'm looking for a link analysis-type tree representation, where the nodes can be arbitrarily linked to other multiple nodes, and the visual representation (grouping, formatting) of those nodes can be controlled (google images for "Analyst's Notebook" for excellent examples of these kinds of link-node layouts.  This would be for very large network analysis.
Here's one example (content not my use case).  Note how a node might be connected to multiple nodes.


text:
Q: How can I split R/Stan code chunks across two slides (quarto + revealjs)? I have some large code chunks that exceed the length of one slide.  I want the code to easily split across two slides.  This comes up when I want to display a large function that I can't easily split across two R code chunks. I also regularly print my slides to pdf for later annotation, so the scrollable code isn't helpful.
Is there any straightfoward way to do this?
I tried adding something like knitr::asis_output("\n\n---\n\n") into an R code chunk to manually add the slide break, following Inserting a slide break within a code chunk in rmarkdown
but this didn't work.


text:
Q: Can I use a cross reference in the caption figures? I tried to find solutions, but I was unable to find
I need to report in chapter 11, a figure contained in chapter 7 and I want them to have the same image number.
I tried using the \tag{\ref{}} but I get an error:
Package amsmath Error: \tag not allowed here. \tag

for example:
\documentclass[a4paper]{article}

\usepackage[italian]{babel}
\usepackage{amsmath}
 \usepackage{caption}
\usepackage{graphicx}

Chapter7
\begin{figure}[!htb] %[htpb]
    \centering
    \includegraphics[width=3cm]{example-image-a}
    \captionof{figure}{\small chapter7} %% NUMBER FIGURE 1 <<---
    \label{fig:test1}
\end{figure}

Chaper11
\begin{figure}[!htb] %[htpb]
    \centering
    \includegraphics[width=3cm]{example-image-a}
    \captionof{figure}{\small chapter11} %% NUMBER FIGURE 1 ?? <<--
   %\label{fig:test1}
    \tag{\ref{fig:test1}} <<==== ERROR
\end{figure}

I would like the same image with the same label to appear again in the second image, as is done with \tag{\ref{equation..}}the equations
------- UPDATE PROBLEM --------------
I encountered a new problem with caption inside the minipage, compared to the following code:
\begin{minipage}[t]{0.25\textwidth}
    \centering\raisebox{\dimexpr \topskip-\height}{%
        \includegraphics[width=\textwidth]{example-image-a}}
    \caption*{\figurename\ref{fig:test1}: test sx} %<<== **ERROR**
\end{minipage}\hfill
\begin{minipage}[t]{0.65\textwidth}
    \begin{itemize}
        \item prova
        \item prova
        \item prova
    \end{itemize}
\end{minipage}

the error created by compiling the file is:
Package caption Error: \caption outside float. \caption

Do you have any suggestions, please?

A: The \tag command should be used solely for the purpose of creating equation "numbers". I put the word "numbers" in quotation marks since the argument of \tag need not be a number.
Since you're loading the caption package, you could use its \caption* macro to achieve your typesetting objective.
And, since you're using figure environments, there's no need to resort to \captionof; just use \caption (and \caption*, where needed).

\documentclass[a4paper]{article}
\usepackage[italian]{babel}
\usepackage[font=small]{caption}
\usepackage{graphicx}

\begin{document}

\begin{figure}[!htb]
    \centering
    \includegraphics[width=3cm]{example-image-a}
    \caption{chapter7} %% NUMBER FIGURE 1 <<---
    \label{fig:test1}
\end{figure}

\hrule

\begin{figure}[!htb]
    \centering
    \includegraphics[width=3cm]{example-image-a}
    \caption*{\figurename\ \ref{fig:test1}: chapter11}
\end{figure}
\end{document}


text:
Q: Where can I ask a question about upgrading Windows 7 computers to Windows 10 over the network? Where can I ask the following question?

I work in an IT department and we are searching for a way to update all of our Windows 7 computers to Windows 10 without bringing them in and PXE booting them one by one. Is there an easy to do this without doing them one at a time?

A: There are quite a few sites all related to Computer issues so it can be hard to find the right site.
I suggest https://serverfault.com/ which lists the topics as:

Q&A for system and network administrators

And their help centre expands on this:

What topics can I ask about here?
Server Fault is for questions
about managing information technology systems in a business
environment.
If your question is about:

*

*managing the hardware or software of servers, workstations, storage or

*networks tools used for administering, monitoring, or automating these

*deployment to and management of third-party provided information
technology platforms

and is not about:

*

*consumer workstations or networking (which belong on our sister site,
Super User)

*working with a service provider's management interface,
such as cPanel product, service, or learning material recommendations

*product licensing inquiries or legal advice career, salary, personnel,

*employment, or formal education unauthorized use or misuse of IT
systems

then you're in the right place to ask your question!


text:
Q: Rails3 validation okay in console fails in test_helper My validation contains a pluck(:id) statement. The validation works in console but fails in test_helper. If I replace that function with the array the function would return, all tests pass in console and in test_helper.
Here are the details:
I run Rails 3.2.13 on Kubuntu 12.04.
Set up two models in a virgin project:

user - rails g model user role_id:integer
role - rails g model role role_name:string

app/models/user.rb
class User < ActiveRecord::Base
 attr_accessible :role_id

 #validates :role_id, inclusion: { in: [1, 2, 3] }  # validation using the result array.
 validates :role_id, inclusion: { in: Role.pluck(:id) }  # validation using the pluck(:id) function.

end

app/models/role.rb is as generated.
Added three Roles using the console. id's are [1, 2, 3].
Checked validation in console.
u = User.new(role_id: 1)
u.valid?
=> true
u.role_id = 5 # value out-of-range
u.valid?
=> false
u.role_id = 2 # value in range
u.valid?
=> true

So, this validation seems to work as intended.
u.save

worked, too.
Then, added a test:
test/unit/user_test.rb
require 'test-helper'
class UserTest < ActiveSupport::TestCase
 test "role_id must be valid" do
   @u = User.new(role_id: 1)
   assert(@u.valid?,"Invalid role")
 end
end

Ran test with
rake test

Test failed, although role_id is correct as confirmed by console result.
If I replace the validation in app/models/user.rb with the commented one above
validates :role_id, inclusion: { in: [1, 2, 3] }

and comment out the other validation, test passes and console passes. Same effect with rspec. I repeated this several times now, always the same effect. Found a lot of interesting stuff on this site and played around with proc, lambda, blocks, custom validations, no success.
I guess I learned a lot, but start getting frustrated now. Could anybody direct me to my mistake(s)?
Thanks a lot.

A: Tests run in a different environment and DB (the test environment/DB, not coincidentally).
You need to have some test data, like roles.
There are multiple options including things like Factory Girl, DB seeding, etc.
You can create the same failure in the console by starting in the test enironment:
RAILS_ENV=test rails c


text:
Q: Add values for keys that contains similar string in python I have dict as
values={'P-ETH-900':Decimal(122),'P-ETH-700':Decimal(455),'P-BTC-900':Decimal(12),'P-BTC-700':Decimal(55)}

I want to add the decimals that has condition like
eth=Decimal(0)
for i,j in values.items():
   if 'ETH' in i:
      eth=eth+j

So basically, for each similar items , need to sum up the decimal values.
output:
{'ETH':'577','BTC':'67'}

A: Use a dictionary comprehension that calls sum():
result = {currency: sum(v for k, v in values.items() if currency in k) for currency in ['ETH', 'BTC']}

Or you can use a defaultdict to extract the currency from the keys, assuming it's always the second component.
from collections import defaultdict

result = defaultdict(int)

for key, value in values.items():
    result[key.split('-')[1]] += value


text:
Q: How to show string in variable funtion PHP I am  have a code like this:
function sampleName(string $name)
{
    echo ", good morning $name" . PHP_EOL;
}

function showName(string $name, $filter): string
{
    return  "Hello" . $filter($name) . PHP_EOL;
}

showName("John", "sampleName") . PHP_EOL;

And the result is :
, good morning John

How to show the Hello when i am call showName() function?

A: Return values from SampleName Function and print return value of ShowName function.
function sampleName(string $name)
{
    return ", good morning $name" . PHP_EOL;
}

function showName(string $name, $filter) : string
{
    return "Hello" . $filter($name) . PHP_EOL;
}

echo showName("John", "sampleName") . PHP_EOL;

Output : Hello, good morning John

A: The showName function return's which is why the Hello part does not show.
You could either echo instead of return in the function or echo your call to the function, ie echo showName('John', 'sampleName');


text:
Q: awk select input files from list basic Awk question, but I can't seem to find an answer anywhere:
I have a folder of 50000 txt files, from which I would like to run AWK searches on a subset.  I've saved the filenames I want to limit the search to in a separate document. This would greatly speed up the search, which at the moment looks like this:
awk -F "searchTerm" '{print NF-1}' data/output/*>> output.txt

Many thanks

A: Suppose that your file containing the subset that you want to search is called subset.txt and its content has this format (each file on a separate line):
file1.txt
file2.txt
file3.txt
...
fileN.txt

Then this will do the trick:
awk -F "searchTerm" '{print NF-1}' $(<subset.txt) >> output.txt

Explanation:

*

*$(<subset.txt) will supply the subset list of files to awk as input. (See Jonathan Leffler's comment below)

I should also point out that -F "searchTerm" is actually setting the Field Separator (limiter used by awk on each line) to searchTerm. If you want to print the Number of Fields - 1 on each line that contains "searchTerm", do:
awk '/searchTerm/ {print NF-1}' $(cat subset.txt) >> output.txt

A: I think this will work for you.
awk '/searchTerm/{print $(NF-1)}' data/output/*>> output.txt

A: if you have your lists in a file called filelist.txt you could just use the stdout from a cat command.
 awk -F "searchTerm" '{print NF-1}' `cat data/output/filelist.txt` >> output.txt`


text:
Q: cannot deploy Rails 4.1.0 application to Heroku I just tried to deploy my Rails 4.1.0 app to Heroku, but I get this error:
Gem::LoadError: Specified 'sqlite3' for database adapter, but the gem is not loaded.

...

error: failed to push some refs to 'git@heroku.com:somedomain.git'

For the moment I don't use any database in production.
In my Gemfile, I made the sqlite3 gem only work for development mode like this:
gem 'sqlite3', group: :development

But this doesn't solve the issue.
Does anybody know how I can deploy my Rails 4.1.0 app to Heroku without specifying a database for production?
Thanks for your help,
Anthony

A: Its better to use pg gem for heroku.
Your config/database.yml should look this way
production:
  adapter: postgresql
  encoding: unicode
  database: appname_production
  pool: 5
  username: user
  password:

Gemfile
gem 'pg'
This works for heroku in a some of my apps.


text:
Q: Create a class modules with parent and child classes in VBA I am a novice user of class module.
I don't understand the concept of a class module well.
I want to configure a class module similar to the basic objects of Excel like Worksheet or Cells or ETC..
So I want to control it by creating a parent object and creating its child objects.
Child Class - Defect
Option Explicit

Private pDefectSymptom As String
Private pDefectLevel As Integer

Property Get DefectSymptom() As String
    DefectSymptom = pDefectSymptom
End Property

Property Let DefectSymptom(ByVal vDefectSymptom As String)
    pDefectSymptom = vDefectSymptom
End Property

Property Get DefectLevel() As Integer
    DefectLevel = pDefectLevel

End Property

Property Let DefectLevel(ByVal vDefectLevel As Integer)
    pDefectLevel = vDefectLevel

End Property

Function Delete()
    '???
End Function

Property Get Parent() As Object
    '???
End Property

Parent Class - Defects
Private Defects As New Collection

Function Add(DefectSymptom As String, Optional DefectLevel As Integer) As Defect

    Dim NewDefect As Defect

    Set NewDefect = New Defect

    NewDefect.DefectSymptom = DefectSymptom
    NewDefect.DefectLevel = DefectLevel

    Defects.Add NewDefect

    'Add = NewDefect  'Error! Like the open command of workbook, I want to return an object or just command
End Function

Property Get Count() As Long
    Count = Defects.Count
End Property

Property Get Item(Index As Long) As Defect
    Item = Defects(Index) 'Error! I don't know what raise Error.
End Property

My question are.

*

*How to add Command like Open Command of workbook. Return or just command.

*Why Raise Error Item Property? how to fix that?

*Hiding Private variable. Because office office objects seem to be hidden.
enter image description here

*If you have time, please help with Delete command and Parent command.

A:
How to add Command like Open Command of workbook. Return or just
command.

You just need to return the newly created object in the function. Keep in mind since we're dealing with objects, we need to Set the object's reference.
Public Function Add(DefectSymptom As String, Optional DefectLevel As Integer) As Defect

    Dim NewDefect As Defect
    Set NewDefect = New Defect

    NewDefect.DefectSymptom = DefectSymptom
    NewDefect.DefectLevel = DefectLevel

    Defects.Add NewDefect

    Set Add = NewDefect  '<- here
End Function

Why Raise Error Item Property? how to fix that?

Same as the above, you need to Set the object's reference.
Property Get Item(Index As Long) As Defect
    Set Item = Defects(Index)
End Property

To delete, simply supply the index to the function. However, this method must reside where the collection is (parent) since a Defect object cannot delete itself.
Function Delete(ByVal Index As Long)
    Defects.Remove Index
End Function

Lastly, to hold a reference to the parent, each child must hold a reference to it in a private variable. Then you need to set the parent when creating a new item using the keyword Me.
So in the Defect class, create a private field.
Private mParent As Defects

Property Set Parent(ByVal objDefects As Defects)
    Set mParent = objDefects
End Property

Property Get Parent() As Defects
    Set Parent = mParent
End Property

With this done, amend the Add() method to store the reference.
Public Function Add(DefectSymptom As String, Optional DefectLevel As Integer) As Defect

    Dim NewDefect As Defect
    Set NewDefect = New Defect

    NewDefect.DefectSymptom = DefectSymptom
    NewDefect.DefectLevel = DefectLevel
    Set NewDefect.Parent = Me '<- here

    Defects.Add NewDefect

    Set Add = NewDefect  '<- here
End Function

Not sure this is a good idea though. I tend to avoid circular references altogether, since a child can hold the parent in memory by holding a reference to it. You will need to make sure to clear the reference to the Parent when deleting the item.
Lastly, you should avoid creating the Defects collection like this. Instead, you should make use of the class constructor and destructor.
This method is called automatically when a new class is created:
Private Sub Class_Initialize()
    Set Defects = New VBA.Collection
End Sub

This method is called just before the class is destroyed from memory.
Private Sub Class_Terminate()
    Set Defects = Nothing
End Sub


text:
Q: How to switch words in an easy manner (in VIM)? I'm not good enough at vim to determine whether this was possible or not (which is why I came to superuser and not good) ~ is there a way in vim to easily switch two words?
for example in def function(param1, param2) is there a quick/easy way to change that to def function(param2, param1)???

A: That long solution is ugly. Suppose your cursor is at the left the first letter of the first word, that is 'p'. Do this: dwlpldw%p.
This fits in your special case. How about dealing with daily editing? Try dwwP, or dWWP. :D
Tips: Don't always write long regular expression, if you don't need to do this often. Otherwise your vimrc booms. All vim users shall be familiar with its builtin cursor movement.

A: +1 for @Heptite's answer.
For more completeness, here is what I have in my .vimrc:
" push current line up or down
nnoremap <leader><Up> ddkP
nnoremap <leader><Down> ddp

" exchange character under cursor with the next character without moving the cursor
nnoremap gc xph

" exchange word under cursor with the next word without moving the cursor
nnoremap gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<CR><C-o><C-l>

" push word under cursor to the left
nnoremap <leader><Left> "_yiw?\w\+\_W\+\%#<CR>:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<CR><C-o><C-l>

" push word under cursor to the right
nnoremap <leader><Right> "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<CR><C-o>/\w\+\_W\+<CR><C-l>

Source: the vim wiki.
I see my (and the wiki's) gw is slightly different from Heptite's one. I'm not sure which one is better.

A: I don't remember where I originally got this, but it's been in my ~/.vimrc for at least a few years:
" Swap the word the cursor is on with the next word (which can be on a
" newline, and punctuation is "skipped"):
nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<CR><C-o>:noh<CR>

After you have this defined, all you need to do is put your cursor somewhere on "param1" in normal mode and type: gw

A: Swap mappings for Latin languages
The swap mappings from the Vim wiki will not operate correctly on words with accented characters.
These mappings are adapted to work with (European) ISO/IEC_8859-1 Latin-1 Supplement characters. This is done by substituting all instances of \w in the Vim wiki code with [0-9A-Za-zÀ-ÖØ-öø-ÿ_\-] and all instances of \_W with \_[^0-9A-Za-zÀ-ÖØ-öø-ÿ_\-].
Clearing of search highlighting
Furthermore, the search highlighting is cleared where needed.
This is achieved by adding :nohlsearch<return> at the end of each mapping where it is required.
Here is the end result:
" Use gc to swap the current CHARACTER with the next, WITHOUT changing the cursor position.
nnoremap <silent> gc xph

" Use gw to swap the current WORD with the next, WITHOUT changing the cursor position.
nnoremap <silent> gw "_yiw:s/\(\%#[0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)\(\_[^0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)\([0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)/\3\2\1/<CR><c-o><c-l>:nohlsearch<return>

" Disable Alt+[menukey] menu keys (i.e. Alt+h for help)
set winaltkeys=no

" Use Alt + ← or Alt + h to swap the current WORD with the previous, keeping the cursor on the current word. This feels like "PUSHING" the word to the left.
nnoremap <silent> <A-Left> "_yiw?[0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\_[^0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\%#<CR>:s/\(\%#[0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)\(\_[^0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)\([0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)/\3\2\1/<CR><c-o><c-l>:nohlsearch<return>
nnoremap <silent> <A-h>    "_yiw?[0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\_[^0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\%#<CR>:s/\(\%#[0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)\(\_[^0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)\([0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)/\3\2\1/<CR><c-o><c-l>:nohlsearch<return>
" <A-h> corresponds to è

" Use Alt + → or Alt + l to swap the current WORD with the next, keeping the cursor on the current word. This feels like "PUSHING" the word to the right.
nnoremap <silent> <A-Right> "_yiw:s/\(\%#[0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)\(\_[^0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)\([0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)/\3\2\1/<CR><c-o>/[0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\_[^0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+<CR><c-l>:nohlsearch<return>
nnoremap <silent> <A-l>     "_yiw:s/\(\%#[0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)\(\_[^0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)\([0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\)/\3\2\1/<CR><c-o>/[0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+\_[^0-9A-Za-zÀ-ÖØ-öø-ÿ_\-\`]\+<CR><c-l>:nohlsearch<return>
" <A-l> corresponds to ì

" Use g{ to swap the current PARAGRAPH with the next.
nnoremap g{ {dap}p{

A: I wrote up repeatable mappings using a combination of vim-exchange, Repeatable (which depends on repeat.vim), and argtextobj.
" Swap function arguments, move the argument under the cursor to the left or to
" the right.
Repeatable map <leader>al cxiaf,cxia
Repeatable map <leader>ah cxiaF,hcxia

The advantage in using the exchange and repeatable plugins for these mappings are:

*

*Doing one undo u will undo the swap (they're atomic changes)

*You can use the . to keep moving the argument left/right.

I know I know, it seems like a whole lot of plugins for a simple operation, but think what else those plugins give you:

*

*argtextobj gives you the ia and aa textobj for deleting (dia and daa), and yanking (yia).

*vim-repeat and Repeatable for making any of your mappings repeatable with ..

*vim-exchange gives you repeatable, atomic exchanging of text.

A: Eclim plugin provides a good one. All credits to them :)
:SwapWords

.. and if you don't want to install the whole plugin, here is their function extracted:
" Swap words:
" taken from Eclim
" https://github.com/ervandew/eclim

function! SwapWords() " {{{
  " Initially based on http://www.vim.org/tips/tip.php?tip_id=329

  " save the last search pattern
  let save_search = @/

  normal! "_yiw
  let pos = getpos('.')
  keepjumps s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/
  call setpos('.', pos)

  " restore the last search pattern
  let @/ = save_search

  silent! call repeat#set(":call SwapWords()\<cr>", v:count)
endfunction " }}}

command! SwapWords :call SwapWords()


text:
Q: codeigniter: how do you declare sendsms( '919918xxxxxx', 'test message from spring edge' ); sendsms( '919918xxxxxx', 'test message from spring edge' ); how do you declare this function in codeigniter?

A: Codeigniter have a good functionality Helpers. Helper functions are available in all controllers(if auto-load). You can use codeigniter helper to declare this function.
Open a file in Application/Heplers/sendsms_helper.php
 /*Start sendsms_helper.php file */

    function sendsms($number, $message_body, $return = '0'){
        $sender = 'SEDEMO';  //Use sender name here
        $smsGatewayUrl = 'SMS_GATEWAY_URL_HERE';
        $apikey = '62q3z3hs49xxxxxx'; // Use API key here

        $textmessage = urlencode($textmessage);
        $api_element = '/api/web/send/';
        $api_params = $api_element.'?apikey='.$apikey.'&sender='.$sender.'&to='.$mobileno.
'&message='.$textmessage;
        $smsgatewaydata = $smsGatewayUrl.$api_params;
        $url = $smsgatewaydata;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);

        if($return == '1'){
            return $output;
        }
    }

/*     * End sendsms_helper.php file     */

How to use in controller:

*

*Load sendsms helper in controller using $this->load->helper('sendsms_helper');

*Call sendsms function Ex. sendsms( '919918xxxxxx', 'test message from spring edge' );


text:
Q: How to Result two field with a case query in neo4j? As question, I want to return a result with two field using case, example:
CASE WHEN {userid} = {myuserid} THEN true, true AS can_edit, can_delete

A: If you're already working with booleans, then there's no need for CASE at all.
...
WITH {userid} = {myuserid} as can_edit
WITH can_edit, can_edit as can_delete
...

You could repeat the same comparison again if you really want, though.
As to the question about using CASE for multiple values, you could always use a list or a object to hold the two booleans at the same time.
Something like:
...
CASE WHEN {userid} = {myuserid} THEN {can_edit:true, can_delete:true} END AS permissions


text:
Q: Rename files with its directory name I have some directories with files like:
folder1/filename.jpg
folder2/filename.pdf
folder3/filename.jpg

And I want to rename all files inside all directories with its corresponding directory name (but keeping its extension), like:
folder1/filename.jpg to folder1/folder1.jpg
folder2/filename.pdf to folder2/folder2.pdf
folder3/filename.jpg to folder3/folder3.jpg

Edit: also, I want to copy all renamed files to another directory (like "allfiles").
I found a similar question in Perl language.
How could I achieve it with PHP?

A: Here you have a way to do that:
<?php

// Array with all subdirectories in directory
$dirArray = array_filter(glob('/path/to/directory/*'), 'is_dir');

// $dir is the path to the subdirectory
foreach ($dirArray as $dir) {

    // $dirName has the future name of files in that subdirectory
    $dirName = basename($dir);

    // Take all the elements in the subdirectory (except '.' and '..')
    $filesArray = array_diff(scandir($dir), array('.', '..'));

    $i = 0;
    foreach ($filesArray as $file) {
        // Take the file extension for the rename method
        $fileExtension = pathinfo($file, PATHINFO_EXTENSION);

        $oldName = $dir . "/" . $file;
        $newName = $dir . "/" . $dirName . "-" . $i . "." . $fileExtension;

        rename($oldName, $newName);
        $i++;
    }
}

If you are sure you will have only one file in each subdirectory you can use this line to $newName:
$newName = $dir . "/" . $dirName . "." . $fileExtension;


text:
Q: UPDATE + сложение Подскажите как сделать апдейт что бы значение в ячейке не перезатиралось, а добавлялось (если возможно без предварительной выборки сложения а только потом записи обратно). Инфы что то не найду по этому вопросу. Это вообще реально? если да то может кто-то знает как сделать.

A: UPDATE `users` SET `logged_in` = `logged_in` + 1 WHERE `users.id` = 1

Вариант рабочий и только что протестирован

A: UPDATE `table`
SET `field` = CONCAT(field, 'literal');


text:
Q: Show error on pressing back/forward button I have a login page,when the logged in user presses the back button ,the page should show error rather than showing login page and same should be applied on the forward button.

A: window.onbeforeunload event will fire when the user leaves the page.
var prevURL = document.referrer;

window.onbeforeunload = function() {
  if(prevURL == 'provide your login page URL here') {
    return "Error message";  // alert
    //or do whatever you want
  }
};

Note that this event will fire when the user leaves the page for anyway.


text:
Q: Arithmetic derivative I am surprised that Mathworld Wolfram did not list "Arithmetic Derivative" but Wiki has
http://en.wikipedia.org/wiki/Arithmetic_derivative
You can use Arithmetic Derivative to formulate Goldbach's conjecture, twin prime and prime triples in an alternative way.
E. J. Barbeau, "Remark on an arithmetic derivative", Canad. Math. Bull. 4 (1961), 117
http://www.maa.org/mathland/mathtrek_03_22_04.html
Ufnarovski and Åhlander (2003)
http://www.cs.uwaterloo.ca/journals/JIS/VOL6/Ufnarovski/ufnarovski.pdf
Why didn't Weisstein's Mathworld  mention arithmetic derivative at all?
@Benvitale


text:
Q: Catalan Numbers Questions Show that the number of paths from $(0,0)$ to $(n,n)$ that touch the line $y=x$ only at the points $(0,0)$ and $(n,n)$ is $C_{n - 1}.$
Show that the number of paths from $(0,0)$ to $(n,n)$ that touch the line $y=x$ at the points $(0,0),$ $(n,n),$ and exactly one other point in between, is $C_{n - 1}.$
I've tried drawing out all distinct paths for small values of n, but I haven't noticed much of a pattern. Any help please...?

A: HINTS:

*

*A path from $\langle 0,0\rangle$ to $\langle n,n\rangle$ that touches the line $y=x$ only at its endpoints must start with a step to $\langle 1,0\rangle$ and end with a step from $\langle n,n-1\rangle$, and between those points it can touch but must not cross the line $y=x-1$.

*A path that hits the line $y=x$ exactly once between the endpoints is the concatenation of two paths that don't hit the line between their endpoints; use the first result and a basic Catalan number recurrence.


text:
Q: Referring to correctly-styled algpseudocode procedure name in document Given an algorithm written in algpseudocode:
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}
  \caption{Part 1}
  \begin{algorithmic}[1]
    \Procedure {FooProc}{$G$}
      \State ...
    \EndProcedure
  \end{algorithmic}
\end{algorithm}
\end{document}

How can I now refer to FooProc in my document (outside of the algorithm environment) such that it has the same typeset as in inside the algorithm environment?

A: That is the document default small caps font so \textsc{FooProc}
Better would be to use the package defined command \textproc{Fooproc} which will do the same thing, but ensure that if you customise the fonts used in the psuedo-code, the reference will use the same font.


text:
Q: Show Hide checkboxes THE SCENARIO:
In the html example showed on the link below, i have multiple checkboxes which when you click it must show or hide:
THE EXAMPLE:
Based on link below, when you open the specific page, it must show the folowing checkboxes:
All, District, Area, Category, Restaurant, Shop, Houses
If you click for example on District it will show you just District1, and if you click District1 it will show you District2 and the opposite if you uncheck. But in the same time when you click District1 for example it will show you if you have just Restaurants and Shops.
I added the link from jsfiddle with the html code.
THE QUESTION:
Can someone do the javascript? Because i do not know javascript
Thank you in advance,
The example

A: $('.district').hide();
$("#district").on('change',function () {
    if(this.checked)
    {
        $('.district').show();
    }
    else
    {
        $('.district').hide();
    }
});

Check This Edit


text:
Q: Why doesn't it show me the items added in the array? Why doesn't it show me the items added in the array? (I want to keep this array layout).
Could someone tell me how should I complete the array to register the elements correctly?
It always returns zero.
Sample Code:
import UIKit

class FilterCategory: Equatable{

    static func == (lhs: FilterCategory, rhs: FilterCategory) -> Bool {
        return lhs.id == rhs.id
    }

    var id : Int = 0
    var name: String = ""
    var image: UIImage = UIImage()

    init(id: Int, name: String, image: UIImage) {
        self.id = id
        self.name = name
        self.image = image
    }
}

class demo : UIViewController {

    var images = [FilterCategory]()
    var thumbnailImagesList = [Int: [UIImage?]]()

    override func viewDidLoad() {
        super.viewDidLoad()

        images.append(FilterCategory.init(id: 1, name: "1.1", image: UIImage()))
        images.append(FilterCategory.init(id: 1, name: "1.2", image: UIImage()))
        images.append(FilterCategory.init(id: 2, name: "2.1", image: UIImage()))
        images.append(FilterCategory.init(id: 2, name: "2.2", image: UIImage()))

        var index = 0

        for img in images {
            self.thumbnailImagesList[img.id]?[index] = UIImage()
            index = index+1
        }

        print(thumbnailImagesList.count)
    }
}

A: The dictionary is empty from start but you are treating it like it contains values, use the below code instead that will either add the image object to a new or existing array depending on if the key (img.id) exists or not in the dictionary
for img in images {
    self.thumbnailImagesList[img.id, default:[]].append(UIImage())
}

A question is why you are creating new image objects everywhere in your code, maybe you meant
for img in images {
    self.thumbnailImagesList[img.id, default:[]].append(img.image)
}


text:
Q: TableViewCell ImageView shows always different data I have a chat and want to display the users profile pictures.
Everything will be displayed correctly but not the profile pictures of the users.
Everytime, when I reload my view, I get other pictures.
I load the Profileimage in with the following lines:
func showProfilImage(uid: String, completion: @escaping (UIImage) -> Void) {
    UserApi.shared.observeUser(uid: uid) { (user) in
        guard let url = URL(string: user.profilImageUrl!) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard error == nil, let data = data, let image = UIImage(data: data) else { return }
                DispatchQueue.main.async {
                    let finishedImage = image.withRenderingMode(.alwaysOriginal)
                    completion(finishedImage)
                }
                }.resume()
    }
}

Then I call showProfilImage in cellForRowAt with the following lines:
self.showProfilImage(uid: self.items[indexPath.row].user.uid!) { (image) in
    cell.profilePic.image = image
}

UPDATE
Now i implemented sdWebImage and make a completion with the URL:
func showProfilImage(uid: String, completion: @escaping (URL) -> Void) {
    UserApi.shared.observeUser(uid: uid) { (user) in
        guard let url = URL(string: user.profilImageUrl!) else { return }
        completion(url)
    }
}

Here I call my showProfilImage:
self.showProfilImage(uid: self.items[indexPath.row].user.uid!) { (url) in
            cell.profilePic.image = nil
            cell.profilePic.sd_setImage(with: url, completed: { (_, _, _, _) in
            })
        }

A: Your current code has dequeuing and no cashing problems and the right for that is to use SDWebImage
cell.profilePic.sd_setImage(with: URL(string:urlStr), placeholderImage: UIImage(named: "placeholder.png"))

also something like
UserApi.shared.observeUser(uid: uid) { (user) in

would be once say in viewDidLoad

A: If you're fetching the image correctly for each user
then you problem might be laying in scrolling and dequeuing the cell
to solve such issue inside the UITableViewCell custom class use this function to clear out the UIImageView each time a dequeue happens.
override func prepareForReuse() {
        super.prepareForReuse()
        self.imageView.image = nil  //setting the image to nil  when get dequeued to reuse
    }

Read more about this function Here

A: UITableView reuses its views that means when you load an image one time and cell goes out of screen UITableView will bring the cell back to screen for different data source but the image that previously loaded will still presented on the UIImageView
add this line of code
cell.profilePic.image = nil
self.showProfilImage(uid: self.items[indexPath.row].user.uid!) { (image) in
        cell.profilePic.image = image
    }


text:
Q: Change back button of navigation controller I have this code :
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
        let controller = SectionsController()
        self.navigationController?.pushViewController(controller, animated: true)
}

In my class :
class HomeController: UITabBarController,UITableViewDataSource,UITableViewDelegate, AddingProtocoleDelegate

And i want to change the back button title to "Back"
I've tried this in the sectionController viewDidLoad :
        self.navigationItem.backBarButtonItem?.title = "Back"
        self.navigationController?.navigationBar.backItem?.title = "Back"
        self.navigationController?.navigationItem.title = "Back"
        let backButton = UIBarButtonItem(
            title: "Back",
            style: UIBarButtonItemStyle.plain,
            target: nil,
            action: nil
        );
        self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton;

But any solutions didn't work.
Help please.

A: use this self.navigationItem.leftBarButtonItem = backButton

A: The back button belongs to the previous view controller, not the one currently presented on screen. Try this and see if it works for you.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let backItem = UIBarButtonItem()
backItem.title = "Back"
navigationItem.backBarButtonItem = backItem
}

Swift 3:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let backItem = UIBarButtonItem()
backItem.title = "Back"
navigationItem.backBarButtonItem = backItem
}