Programs & Examples On #Headset

AngularJS event on window innerWidth size change

We could do it with jQuery:

$(window).resize(function(){
    alert(window.innerWidth);

    $scope.$apply(function(){
       //do something to update current scope based on the new innerWidth and let angular update the view.
    });
});

Be aware that when you bind an event handler inside scopes that could be recreated (like ng-repeat scopes, directive scopes,..), you should unbind your event handler when the scope is destroyed. If you don't do this, everytime when the scope is recreated (the controller is rerun), there will be 1 more handler added causing unexpected behavior and leaking.

In this case, you may need to identify your attached handler:

  $(window).on("resize.doResize", function (){
      alert(window.innerWidth);

      $scope.$apply(function(){
          //do something to update current scope based on the new innerWidth and let angular update the view.
      });
  });

  $scope.$on("$destroy",function (){
      $(window).off("resize.doResize"); //remove the handler added earlier
  });

In this example, I'm using event namespace from jQuery. You could do it differently according to your requirements.

Improvement: If your event handler takes a bit long time to process, to avoid the problem that the user may keep resizing the window, causing the event handlers to be run many times, we could consider throttling the function. If you use underscore, you can try:

$(window).on("resize.doResize", _.throttle(function (){
    alert(window.innerWidth);

    $scope.$apply(function(){
        //do something to update current scope based on the new innerWidth and let angular update the view.
    });
},100));

or debouncing the function:

$(window).on("resize.doResize", _.debounce(function (){
     alert(window.innerWidth);

     $scope.$apply(function(){
         //do something to update current scope based on the new innerWidth and let angular update the view.
     });
},100));

Difference Between throttling and debouncing a function

Convert a CERT/PEM certificate to a PFX certificate

openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx

How to Diff between local uncommitted changes and origin

To see non-staged (non-added) changes to existing files

git diff

Note that this does not track new files. To see staged, non-commited changes

git diff --cached

How to parse JSON string in Typescript

If you want your JSON to have a validated Typescript type, you will need to do that validation work yourself. This is nothing new. In plain Javascript, you would need to do the same.

Validation

I like to express my validation logic as a set of "transforms". I define a Descriptor as a map of transforms:

type Descriptor<T> = {
  [P in keyof T]: (v: any) => T[P];
};

Then I can make a function that will apply these transforms to arbitrary input:

function pick<T>(v: any, d: Descriptor<T>): T {
  const ret: any = {};
  for (let key in d) {
    try {
      const val = d[key](v[key]);
      if (typeof val !== "undefined") {
        ret[key] = val;
      }
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      throw new Error(`could not pick ${key}: ${msg}`);
    }
  }
  return ret;
}

Now, not only am I validating my JSON input, but I am building up a Typescript type as I go. The above generic types ensure that the result infers the types from your "transforms".

In case the transform throws an error (which is how you would implement validation), I like to wrap it with another error showing which key caused the error.

Usage

In your example, I would use this as follows:

const value = pick(JSON.parse('{"name": "Bob", "error": false}'), {
  name: String,
  error: Boolean,
});

Now value will be typed, since String and Boolean are both "transformers" in the sense they take input and return a typed output.

Furthermore, the value will actually be that type. In other words, if name were actually 123, it will be transformed to "123" so that you have a valid string. This is because we used String at runtime, a built-in function that accepts arbitrary input and returns a string.

You can see this working here. Try the following things to convince yourself:

  • Hover over the const value definition to see that the pop-over shows the correct type.
  • Try changing "Bob" to 123 and re-run the sample. In your console, you will see that the name has been properly converted to the string "123".

What is the iOS 5.0 user agent string?

This site seems to keep a complete list that's still maintained

iPhone, iPod Touch, and iPad from iOS 2.0 - 5.1.1 (to date).

You do need to assemble the full user-agent string out of the information listed in the page's columns.

How to determine day of week by passing specific date?

...
import java.time.LocalDate;
...
//String month = in.next();
int mm = in.nextInt();
//String day = in.next();
int dd = in.nextInt();
//String year = in.next();
int yy = in.nextInt();
in.close();
LocalDate dt = LocalDate.of(yy, mm, dd);
System.out.print(dt.getDayOfWeek());

How to download a file with Node.js (without using third-party libraries)?

I suggest you to use res.download same as follow:

app.get('/download', function(req, res){
  const file = `${__dirname}/folder/abc.csv`;
  res.download(file); // Set disposition and send it.
});

Python threading.timer - repeat function every 'n' seconds

Improving a little on Hans Then's answer, we can just subclass the Timer function. The following becomes our entire "repeat timer" code, and it can be used as a drop-in replacement for threading.Timer with all the same arguments:

from threading import Timer

class RepeatTimer(Timer):
    def run(self):
        while not self.finished.wait(self.interval):
            self.function(*self.args, **self.kwargs)

Usage example:

def dummyfn(msg="foo"):
    print(msg)

timer = RepeatTimer(1, dummyfn)
timer.start()
time.sleep(5)
timer.cancel()

produces the following output:

foo
foo
foo
foo

and

timer = RepeatTimer(1, dummyfn, args=("bar",))
timer.start()
time.sleep(5)
timer.cancel()

produces

bar
bar
bar
bar

How to vertically align a html radio button to it's label?

A lot of these answers say to use vertical-align: middle;, which gets the alignment close but for me it is still off by a few pixels. The method that I used to get true 1 to 1 alignment between the labels and radio inputs is this, with vertical-align: top;:

_x000D_
_x000D_
label, label>input{_x000D_
    font-size: 20px;_x000D_
    display: inline-block;_x000D_
    margin: 0;_x000D_
    line-height: 28px;_x000D_
    height: 28px;_x000D_
    vertical-align: top;_x000D_
}
_x000D_
<h1>How are you?</h1>_x000D_
<fieldset>_x000D_
 <legend>Your response:</legend>_x000D_
 <label for="radChoiceGood">_x000D_
  <input type="radio" id="radChoiceGood" name="radChoices" value="Good">Good_x000D_
 </label>_x000D_
 _x000D_
 <label for="radChoiceExcellent">_x000D_
  <input type="radio" id="radChoiceExcellent" name="radChoices" value="Excellent">Excellent_x000D_
 </label>_x000D_
 _x000D_
 <label for="radChoiceOk">_x000D_
  <input type="radio" id="radChoiceOk" name="radChoices" value="OK">OK_x000D_
 </label>_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

"Missing return statement" within if / for / while

Try with, as if if condition returns false, so it will return empty otherwise nothing to return.

public String myMethod()
{
    if(condition)
    {
       return x;
    }
return ""
}

Because the compiler doesn't know if any of those if blocks will ever be reached, so it's giving you an error.

Remove characters from NSString?

You can try this

- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
    while ([str rangeOfString:@"  "].location != NSNotFound) {
        str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return str;
}

Hope this will help you out.

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

I had the same issue with my Ionic 2 project, all I did to resolved the issues was

  • Open "ionic_project_folder/platforms/android/project.properties"
  • Change target=android-25 to target=android-26
  • Run ionic build --release android

Hope this helps someone!

Why is setState in reactjs Async instead of Sync?

Good article here https://github.com/vasanthk/react-bits/blob/master/patterns/27.passing-function-to-setState.md

// assuming this.state.count === 0
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
// this.state.count === 1, not 3

Solution
this.setState((prevState, props) => ({
  count: prevState.count + props.increment
}));

or pass callback this.setState ({.....},callback)

https://medium.com/javascript-scene/setstate-gate-abc10a9b2d82 https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

If you are running VMWare Workstation , you need to stop the VmWare Workstation server - port 443 as well

SQL recursive query on self referencing table (Oracle)

Using the new nested query syntax

with q(name, id, parent_id, parent_name) as (
    select 
      t1.name, t1.id, 
      null as parent_id, null as parent_name 
    from t1
    where t1.id = 1
  union all
    select 
      t1.name, t1.id, 
      q.id as parent_id, q.name as parent_name 
    from t1, q
    where t1.parent_id = q.id
)
select * from q

gpg decryption fails with no secret key error

I got the same error when trying to decrypt the key from a different user account via su - <otherUser>. (Like jayhendren suggests in his answer)

In my case, this happened because there would normally start a graphical pinentry prompt so I could enter the password to decrypt the key, but the su -ed to user had no access to the (graphical) X-Window-System that was currently running.

The solution was to simply issue in that same console (as the user under which the X Server was currently running):

xhost +local:

Which gives other local users access to the currently running (local) X-Server. After that, the pinentry prompt appeared, I could enter the password to decrypt the key and it worked...

Of course you can also forward X over ssh connections. For this look into ssh's -X parameter (client side) and X11Forwarding yes (server side).

How to add to an existing hash in Ruby

my_hash = {:a => 5}
my_hash[:key] = "value"

How do I horizontally center a span element inside a div

One option is to give the <a> a display of inline-block and then apply text-align: center; on the containing block (remove the float as well):

div { 
    background: red;
    overflow: hidden; 
    text-align: center;
}

span a {
    background: #222;
    color: #fff;
    display: inline-block;
    /* float:left;  remove */
    margin: 10px 10px 0 0;
    padding: 5px 10px
}

http://jsfiddle.net/Adrift/cePe3/

How to modify PATH for Homebrew?

To avoid unnecessary duplication, I added the following to my ~/.bash_profile

case ":$PATH:" in
  *:/usr/local/bin:*) ;;     # do nothing if $PATH already contains /usr/local/bin
  *) PATH=/usr/local/bin:$PATH ;;  # in every other case, add it to the front
esac

Credit: https://superuser.com/a/580611

importing a CSV into phpmyadmin

In phpMyAdmin, click the table, and then click the Import tab at the top of the page.

Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:

Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto

Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.

Now click the Go button, and it should run successfully.

How to include header files in GCC search path?

The -I directive does the job:

gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c 

Remove duplicates in the list using linq

If there is something that is throwing off your Distinct query, you might want to look at MoreLinq and use the DistinctBy operator and select distinct objects by id.

var distinct = items.DistinctBy( i => i.Id );

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

How to remove all characters after a specific character in python?

Split on your separator at most once, and take the first piece:

sep = '...'
stripped = text.split(sep, 1)[0]

You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.

How exactly to use Notification.Builder

Notification Builder is strictly for Android API Level 11 and above (Android 3.0 and up).

Hence, if you are not targeting Honeycomb tablets, you should not be using the Notification Builder but rather follow older notification creation methods like the following example.

How to keep indent for second line in ordered lists via CSS?

The following CSS did the trick:

ul{
    margin-left: 1em;
}

li{
    list-style-position: outside;
    padding-left: 0.5em;
}

How to open a local disk file with JavaScript?

Here's an example using FileReader:

_x000D_
_x000D_
function readSingleFile(e) {
  var file = e.target.files[0];
  if (!file) {
    return;
  }
  var reader = new FileReader();
  reader.onload = function(e) {
    var contents = e.target.result;
    displayContents(contents);
  };
  reader.readAsText(file);
}

function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.textContent = contents;
}

document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);
_x000D_
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>
_x000D_
_x000D_
_x000D_


Specs

http://dev.w3.org/2006/webapi/FileAPI/

Browser compatibility

  • IE 10+
  • Firefox 3.6+
  • Chrome 13+
  • Safari 6.1+

http://caniuse.com/#feat=fileapi

Tar a directory, but don't store full absolute paths in the archive

The following command will create a root directory "." and put all the files from the specified directory into it.

tar -cjf site1.tar.bz2 -C /var/www/site1 .

If you want to put all files in root of the tar file, @chinthaka is right. Just cd in to the directory and do:

tar -cjf target_path/file.tar.gz *

This will put all the files in the cwd to the tar file as root files.

How to access the ith column of a NumPy multidimensional array?

>>> test[:,0]
array([1, 3, 5])

Similarly,

>>> test[1,:]
array([3, 4])

lets you access rows. This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.

Html.DropdownListFor selected value not being set

Your code has some conceptual issues:

First,

@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")

When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a SelectedOrderId as part of your model or something like that, in order to use it in this way:

@Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")

Second,

Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.

Some code I would use if I were you to avoid this issues and write better MVC code:

Viewmodel:

public class MyViewModel{
   public int SelectedOrderId {get; set;}
   public SelectList OrderTemplates {get; set;}

   // Other properties you need in your view
}

Controller:

public ActionResult MyAction(){
   var model = new MyViewModel();
   model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1);
   //Other initialization code

   return View(model);
}

In your View:

@Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template")

How do I automatically play a Youtube video (IFrame API) muted?

Update 2021 to loop and autoplay video on desktop/mobile devices (tested on iPhone X - Safari).

I am using the onPlayerStateChange event and if the video end, I play the video again. Refference to onPlayerStateChange event in YouTube API.

_x000D_
_x000D_
<div id="player"></div>
<script>
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var player;

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '100%',
      width: '100%',
      playerVars: {
        autoplay: 1,
        loop: 1,
        controls: 0,
        showinfo: 0,
        autohide: 1,
        playsinline: 1,
        mute: 1,
        modestbranding: 1,
        vq: 'hd1080'
      },
      videoId: 'ScMzIvxBSi4',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  function onPlayerReady(event) {
    event.target.mute();

    setTimeout(function() {
      event.target.playVideo();
    }, 0);
  }

  function onPlayerStateChange(event) {
    if (event.target.getPlayerState() == 0) {
      setTimeout(function() {
        event.target.playVideo();
      }, 0);
    }
  }
</script>
_x000D_
_x000D_
_x000D_

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

user 'guest' can only connect via localhost

That's true since RabbitMQ 3.3.x. Hence you should upgrade to the same version the client library, or just upgrade Spring AMQP to the latest version (if you use dependency managent system).

Previous version of client used 127.0.0.1 as default value for the host option of ConnectionFactory.

Javascript to set hidden form value on drop down change

Here you can set hidden's value at onchange event of dropdown list :

$('#myDropDown').bind('change', function () {
  $('#myHidden').val('setted value');
});

your hidden and drop down list :

<input type="hidden" id="myHidden" />

<select id="myDropDown">
   <option value="opt 1">Option 1</option>
   <option value="opt 2">Option 2</option>
   <option value="opt 3">Option 3</option>
</ select>

Proper way to restrict text input values (e.g. only numbers)

After did lot of research finally I create a function which full fill the requirement. The function which I created restrict all special character and allow only alphabets and number.. and that function works fine for both either you did copy paste and typing both. Hope it works :)

 public inputValidator(event: any) {
    //console.log(event.target.value);
    const pattern = /^[a-zA-Z0-9]*$/;   
    //let inputChar = String.fromCharCode(event.charCode)
    if (!pattern.test(event.target.value)) {
      event.target.value = event.target.value.replace(/[^a-zA-Z0-9]/g, "");
      // invalid character, prevent input

    }
  }

     <input type="text" [(ngModel)]="abc.abc" (input)="inputValidator($event)" />

How you use -
1) Add above method in your class component of ts file.
2) Call method inputValidator($event) on input event..

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The JAX-WS dependency library “jaxws-rt.jar” is missing.

Go here http://jax-ws.java.net/. Download JAX-WS RI distribution. Unzip it and copy “jaxws-rt.jar” to Tomcat library folder “{$TOMCAT}/lib“. Restart Tomcat.

how to convert 2d list to 2d numpy array?

just use following code

c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

Then it will give you

you can check shape and dimension of matrix by using following code

c.shape

c.ndim

Gradient text color

_x000D_
_x000D_
  .gradient_text_class{_x000D_
      font-size: 72px;_x000D_
      background: linear-gradient(to right, #ffff00 0%, #0000FF 30%);_x000D_
      background-image: linear-gradient(to right, #ffff00 0%, #0000FF 30%);_x000D_
      -webkit-background-clip: text;_x000D_
      -webkit-text-fill-color: transparent;_x000D_
    }
_x000D_
<div class="gradient_text_class">Hello</div>
_x000D_
_x000D_
_x000D_

What are the ways to sum matrix elements in MATLAB?

For very large matrices using sum(sum(A)) can be faster than sum(A(:)):

>> A = rand(20000);
>> tic; B=sum(A(:)); toc; tic; C=sum(sum(A)); toc
Elapsed time is 0.407980 seconds.
Elapsed time is 0.322624 seconds.

Selenium using Python - Geckodriver executable needs to be in PATH

from webdriverdownloader import GeckoDriverDownloader # vs ChromeDriverDownloader vs OperaChromiumDriverDownloader
gdd = GeckoDriverDownloader()
gdd.download_and_install()
#gdd.download_and_install("v0.19.0")

This will get you the path to your gekodriver.exe on Windows.

from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'C:\\Users\\username\\\bin\\geckodriver.exe')
driver.get('https://www.amazon.com/')

Check If array is null or not in php

Right code of two ppl before ^_^

/* return true if values of array are empty
*/
function is_array_empty($arr){
   if(is_array($arr)){
      foreach($arr as $value){
         if(!empty($value)){
            return false;
         }
      }
   }
   return true;
}

CardView background color always white

You can use

app:cardBackgroundColor="@color/red"

or

android:backgroundTint="@color/red"

How to set a JVM TimeZone Properly

On windows 7 and for JDK6, I had to add -Duser.timezone="Europe/Sofia" to the JAVA_TOOL_OPTIONS system variable located under "My computer=>Properties=>Advanced System Settings=>Environment Variables".

If you already have some other property set for JAVA_TOOL_OPTIONS just append a space and then insert your property string.

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

This is my function (based on this) to clean the dataset of nan, Inf, and missing cells (for skewed datasets):

import pandas as pd

def clean_dataset(df):
    assert isinstance(df, pd.DataFrame), "df needs to be a pd.DataFrame"
    df.dropna(inplace=True)
    indices_to_keep = ~df.isin([np.nan, np.inf, -np.inf]).any(1)
    return df[indices_to_keep].astype(np.float64)

What is the precise meaning of "ours" and "theirs" in git?

The 'ours' in Git is referring to the original working branch which has authoritative/canonical part of git history.

The 'theirs' refers to the version that holds the work in order to be rebased (changes to be replayed onto the current branch).

This may appear to be swapped to people who are not aware that doing rebasing (e.g. git rebase) is actually taking your work on hold (which is theirs) in order to replay onto the canonical/main history which is ours, because we're rebasing our changes as third-party work.

The documentation for git-checkout was further clarified in Git >=2.5.1 as per f303016 commit:

--ours --theirs

When checking out paths from the index, check out stage #2 ('ours') or #3 ('theirs') for unmerged paths.

Note that during git rebase and git pull --rebase, 'ours' and 'theirs' may appear swapped; --ours gives the version from the branch the changes are rebased onto, while --theirs gives the version from the branch that holds your work that is being rebased.

This is because rebase is used in a workflow that treats the history at the remote as the shared canonical one, and treats the work done on the branch you are rebasing as the third-party work to be integrated, and you are temporarily assuming the role of the keeper of the canonical history during the rebase. As the keeper of the canonical history, you need to view the history from the remote as ours (i.e. "our shared canonical history"), while what you did on your side branch as theirs (i.e. "one contributor's work on top of it").

For git-merge it's explain in the following way:

ours

This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.

This should not be confused with the ours merge strategy, which does not even look at what the other tree contains at all. It discards everything the other tree did, declaring our history contains all that happened in it.

theirs

This is the opposite of ours.

Further more, here is explained how to use them:

The merge mechanism (git merge and git pull commands) allows the backend merge strategies to be chosen with -s option. Some strategies can also take their own options, which can be passed by giving -X<option> arguments to git merge and/or git pull.


So sometimes it can be confusing, for example:

  • git pull origin master where -Xours is our local, -Xtheirs is theirs (remote) branch
  • git pull origin master -r where -Xours is theirs (remote), -Xtheirs is ours

So the 2nd example is opposite to the 1st one, because we're rebasing our branch on top of the remote one, so our starting point is remote one, and our changes are treated as external.

Similar for git merge strategies (-X ours and -X theirs).

ldconfig error: is not a symbolic link

I ran into this issue with the Oracle 11R2 client. Not sure if the Oracle installer did this or someone did it here before i arrived. It was not 64-bit vs 32-bit, all was 64-bit.

The error was that libexpat.so.1 was not a symbolic link.

It turned out that there were two identical files, libexpat.so.1.5.2 and libexpat.so.1. Removing the offending file and making it a symlink to the 1.5.2 version caused the error to go away.

Makes sense that you'd want the well-known name to be a symlink to the current version. If you do this, it's less likely that you'll end up with a stale library.

How to get an HTML element's style values in javascript?

In jQuery, you can do alert($("#theid").css("width")).

-- if you haven't taken a look at jQuery, I highly recommend it; it makes many simple javascript tasks effortless.

Update

for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.

Test if numpy array contains only zeros

If you're testing for all zeros to avoid a warning on another numpy function then wrapping the line in a try, except block will save having to do the test for zeros before the operation you're interested in i.e.

try: # removes output noise for empty slice 
    mean = np.mean(array)
except:
    mean = 0

What is the difference between map and flatMap and a good use case for each?

Flatmap and Map both transforms the collection.

Difference:

map(func)
Return a new distributed dataset formed by passing each element of the source through a function func.

flatMap(func)
Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).

The transformation function:
map: One element in -> one element out.
flatMap: One element in -> 0 or more elements out (a collection).

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

You should only use &rsquo; if your intention is to make either a closed single quotation mark or an apostrophe. Both of these punctuation marks are curved in shape in most fonts. If your intent is to make a foot mark, go the other route. A foot mark is always a straight vertical mark.

It’s a matter of typography. One way is correct; the other is not.

How to set username and password for SmtpClient object in .NET?

SmtpClient MyMail = new SmtpClient();
MailMessage MyMsg = new MailMessage();
MyMail.Host = "mail.eraygan.com";
MyMsg.Priority = MailPriority.High;
MyMsg.To.Add(new MailAddress(Mail));
MyMsg.Subject = Subject;
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.From = new MailAddress("username", "displayname");
MyMsg.BodyEncoding = Encoding.UTF8;
MyMsg.Body = Body;
MyMail.UseDefaultCredentials = false;
NetworkCredential MyCredentials = new NetworkCredential("username", "password");
MyMail.Credentials = MyCredentials;
MyMail.Send(MyMsg);

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

C99 quotes

This answer aims to quote and explain the relevant parts of the C99 N1256 standard draft.

Definition of declarator

The term declarator will come up a lot, so let's understand it.

From the language grammar, we find that the following underline characters are declarators:

int f(int x, int y);
    ^^^^^^^^^^^^^^^

int f(int x, int y) { return x + y; }
    ^^^^^^^^^^^^^^^

int f();
    ^^^

int f(x, y) int x; int y; { return x + y; }
    ^^^^^^^

Declarators are part of both function declarations and definitions.

There are 2 types of declarators:

  • parameter type list
  • identifier list

Parameter type list

Declarations look like:

int f(int x, int y);

Definitions look like:

int f(int x, int y) { return x + y; }

It is called parameter type list because we must give the type of each parameter.

Identifier list

Definitions look like:

int f(x, y)
    int x;
    int y;
{ return x + y; }

Declarations look like:

int g();

We cannot declare a function with a non-empty identifier list:

int g(x, y);

because 6.7.5.3 "Function declarators (including prototypes)" says:

3 An identifier list in a function declarator that is not part of a definition of that function shall be empty.

It is called identifier list because we only give the identifiers x and y on f(x, y), types come after.

This is an older method, and shouldn't be used anymore. 6.11.6 Function declarators says:

1 The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.

and the Introduction explains what is an obsolescent feature:

Certain features are obsolescent, which means that they may be considered for withdrawal in future revisions of this International Standard. They are retained because of their widespread use, but their use in new implementations (for implementation features) or new programs (for language [6.11] or library features [7.26]) is discouraged

f() vs f(void) for declarations

When you write just:

void f();

it is necessarily an identifier list declaration, because 6.7.5 "Declarators" says defines the grammar as:

direct-declarator:
    [...]
    direct-declarator ( parameter-type-list )
    direct-declarator ( identifier-list_opt )

so only the identifier-list version can be empty because it is optional (_opt).

direct-declarator is the only grammar node that defines the parenthesis (...) part of the declarator.

So how do we disambiguate and use the better parameter type list without parameters? 6.7.5.3 Function declarators (including prototypes) says:

10 The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters.

So:

void f(void);

is the way.

This is a magic syntax explicitly allowed, since we cannot use a void type argument in any other way:

void f(void v);
void f(int i, void);
void f(void, int);

What can happen if I use an f() declaration?

Maybe the code will compile just fine: 6.7.5.3 Function declarators (including prototypes):

14 The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.

So you can get away with:

void f();
void f(int x) {}

Other times, UB can creep up (and if you are lucky the compiler will tell you), and you will have a hard time figuring out why:

void f();
void f(float x) {}

See: Why does an empty declaration work for definitions with int arguments but not for float arguments?

f() and f(void) for definitions

f() {}

vs

f(void) {}

are similar, but not identical.

6.7.5.3 Function declarators (including prototypes) says:

14 An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters.

which looks similar to the description of f(void).

But still... it seems that:

int f() { return 0; }
int main(void) { f(1); }

is conforming undefined behavior, while:

int f(void) { return 0; }
int main(void) { f(1); }

is non conforming as discussed at: Why does gcc allow arguments to be passed to a function defined to be with no arguments?

TODO understand exactly why. Has to do with being a prototype or not. Define prototype.

Use Fieldset Legend with bootstrap

That's because Bootstrap by default sets the width of the legend element to 100%. You can fix this by changing your legend.scheduler-border to also use:

legend.scheduler-border {
    width:inherit; /* Or auto */
    padding:0 10px; /* To give a bit of padding on the left and right */
    border-bottom:none;
}

JSFiddle example.

You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.

You may also want to add margin-bottom:0; to it as well to reduce the gap between the legend and the divider.

Easiest way to flip a boolean value?

I prefer John T's solution, but if you want to go all code-golfy, your statement logically reduces to this:

//if key is down, toggle the boolean, else leave it alone.
flipVal = ((wParam==VK_F11) && !flipVal) || (!(wParam==VK_F11) && flipVal);
if(wParam==VK_F11) Break;

//if key is down, toggle the boolean, else leave it alone.
otherVal = ((wParam==VK_F12) && !otherVal) || (!(wParam==VK_F12) && otherVal);
if(wParam==VK_F12) Break;

How can I read large text files in Python, line by line, without loading it into memory?

Here's what you do if you dont have newlines in the file:

with open('large_text.txt') as f:
  while True:
    c = f.read(1024)
    if not c:
      break
    print(c)

No matching bean of type ... found for dependency

I had the same issue but in my case, implemented class was accidently become 'abstract' as a result autowiring was failing.

Pinging servers in Python

My version of a ping function:

  • Works on Python 3.5 and later, on Windows and Linux (should work on Mac, but can't test it).
  • On Windows, returns False if the ping command fails with "Destination Host Unreachable".
  • And does not show any output, either as a pop-up window or in command line.
import platform, subprocess

def ping(host_or_ip, packets=1, timeout=1000):
    ''' Calls system "ping" command, returns True if ping succeeds.
    Required parameter: host_or_ip (str, address of host to ping)
    Optional parameters: packets (int, number of retries), timeout (int, ms to wait for response)
    Does not show any output, either as popup window or in command line.
    Python 3.5+, Windows and Linux compatible (Mac not tested, should work)
    '''
    # The ping command is the same for Windows and Linux, except for the "number of packets" flag.
    if platform.system().lower() == 'windows':
        command = ['ping', '-n', str(packets), '-w', str(timeout), host_or_ip]
        # run parameters: capture output, discard error messages, do not show window
        result = subprocess.run(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, creationflags=0x08000000)
        # 0x0800000 is a windows-only Popen flag to specify that a new process will not create a window.
        # On Python 3.7+, you can use a subprocess constant:
        #   result = subprocess.run(command, capture_output=True, creationflags=subprocess.CREATE_NO_WINDOW)
        # On windows 7+, ping returns 0 (ok) when host is not reachable; to be sure host is responding,
        # we search the text "TTL=" on the command output. If it's there, the ping really had a response.
        return result.returncode == 0 and b'TTL=' in result.stdout
    else:
        command = ['ping', '-c', str(packets), '-w', str(timeout), host_or_ip]
        # run parameters: discard output and error messages
        result = subprocess.run(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return result.returncode == 0

Feel free to use it as you will.

Android on-screen keyboard auto popping up

Include this where the imports are on top:

import android.view.WindowManager;

Add this code on OnCreate part:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ....
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}

How to read all rows from huge table?

I think your question is similar to this thread: JDBC Pagination which contains solutions for your need.

In particular, for PostgreSQL, you can use the LIMIT and OFFSET keywords in your request: http://www.petefreitag.com/item/451.cfm

PS: In Java code, I suggest you to use PreparedStatement instead of simple Statements: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Proxy setting for R

On Windows 7 I solved this by going into my environment settings (try this link for how) and adding user variables http_proxy and https_proxy with my proxy details.

How to decode a Base64 string?

I had issues with spaces showing in between my output and there was no answer online at all to fix this issue. I literally spend many hours trying to find a solution and found one from playing around with the code to the point that I almost did not even know what I typed in at the time that I got it to work. Here is my fix for the issue: [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String($base64string)|?{$_}))

How to use ternary operator in razor (specifically on HTML attributes)?

You can also use this method:

<input type="text" class="@(@mvccondition ? "true-class" : "false-class")">

Try this .. Good luck Thanks.

Setting a PHP $_SESSION['var'] using jQuery

It works on firefox, if you change onClick() to click() in javascript part.

_x000D_
_x000D_
$("img.foo").click(function()_x000D_
{_x000D_
    // Get the src of the image_x000D_
    var src = $(this).attr("src");_x000D_
_x000D_
    // Send Ajax request to backend.php, with src set as "img" in the POST data_x000D_
    $.post("/backend.php", {"img": src});_x000D_
});
_x000D_
_x000D_
_x000D_

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

Liam's link looks great, but also check out pandas.Timedelta - looks like it plays nicely with NumPy's and Python's time deltas.

https://pandas.pydata.org/pandas-docs/stable/timedeltas.html

pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)

how to move elasticsearch data from one server to another

You can take a snapshot of the complete status of your cluster (including all data indices) and restore them (using the restore API) in the new cluster or server.

How to use count and group by at the same select statement

I know this is an old post, in SQL Server:

select  isnull(town,'TOTAL') Town, count(*) cnt
from    user
group by town WITH ROLLUP

Town         cnt
Copenhagen   58
NewYork      58
Athens       58
TOTAL        174

Use Device Login on Smart TV / Console

i've been researching for that too but unfortunately the facebook device auth is still on experimental and they didn't give new keys (partner) to use the device auth.

You can find the working example here: http://oauth-device-demo.appspot.com/ Just look at the website source and you can have the appID that works with it.

The other one is twitter PIN oauth it's working and publicly available (i'm using it) https://dev.twitter.com/docs/auth/pin-based-authorization

adding onclick event to dynamically added button?

Remove the () from your expressions that are not working will get the desired results you need.

but.setAttribute("onclick",callJavascriptFunction);
but.onclick= callJavascriptFunction;
document.getElementById("but").onclick=callJavascriptFunction;

PHP validation/regex for URL

I've used this one with good success - I don't remember where I got it from

$pattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";

Simple way to read single record from MySQL

$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price FROM products WHERE id = 1");

How do I view executed queries within SQL Server Management Studio?

Use the Activity Monitor. It's the last toolbar in the top bar. It will show you a list of "Recent Expensive Queries". You can double-click them to see the execution plan, etc.

Converting File to MultiPartFile

This is a solution without creating manually a file on disc :

MultipartFile fichier = new MockMultipartFile("fileThatDoesNotExists.txt",
            "fileThatDoesNotExists.txt",
            "text/plain",
            "This is a dummy file content".getBytes(StandardCharsets.UTF_8));

Batch file to perform start, run, %TEMP% and delete all

del won't trigger any dialogs or message boxes. You have a few problems, though:

  1. start will just open Explorer which would be useless. You need cd to change the working directory of your batch file (the /D is there so it also works when run from a different drive):

    cd /D %temp%
    
  2. You may want to delete directories as well:

    for /d %%D in (*) do rd /s /q "%%D"
    
  3. You need to skip the question for del and remove read-only files too:

    del /f /q *
    

so you arrive at:

@echo off
cd /D %temp%
for /d %%D in (*) do rd /s /q "%%D"
del /f /q *

MongoDB relationships: embed or reference?

In general, embed is good if you have one-to-one or one-to-many relationships between entities, and reference is good if you have many-to-many relationships.

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

To expand this question into the realm of use outside of Excel s own VBA, the ActiveWindow property must be addressed as a child of the Excel.Application object.

Example for creating an Excel workbook from Access:

Using the Excel.Application object in another Office application's VBA project will require you to add Microsoft Excel 15.0 Object library (or equivalent for your own version).

Option Explicit

Sub xls_Build__Report()
    Dim xlApp As Excel.Application, ws As Worksheet, wb As Workbook
    Dim fn As String

    Set xlApp = CreateObject("Excel.Application")
    xlApp.DisplayAlerts = False
    xlApp.Visible = True

    Set wb = xlApp.Workbooks.Add
    With wb
        .Sheets(1).Name = "Report"
        With .Sheets("Report")

            'report generation here

        End With

        'This is where the Freeze Pane is dealt with
        'Freezes top row
        With xlApp.ActiveWindow
            .SplitColumn = 0
            .SplitRow = 1
            .FreezePanes = True
        End With

        fn = CurrentProject.Path & "\Reports\Report_" & Format(Date, "yyyymmdd") & ".xlsx"
        If CBool(Len(Dir(fn, vbNormal))) Then Kill fn
        .SaveAs FileName:=fn, FileFormat:=xlOpenXMLWorkbook
    End With

Close_and_Quit:
    wb.Close False
    xlApp.Quit
End Sub

The core process is really just a reiteration of previously submitted answers but I thought it was important to demonstrate how to deal with ActiveWindow when you are not within Excel's own VBA. While the code here is VBA, it should be directly transcribable to other languages and platforms.

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

Max retries exceeded with URL in requests

I got similar problem but the following code worked for me.

url = <some REST url>    
page = requests.get(url, verify=False)

"verify=False" disables SSL verification. Try and catch can be added as usual.

How to stretch div height to fill parent div - CSS

I'd solve it with a javascript solution (jQUery) if the sizes can vary.

window.setTimeout(function () {
    $(document).ready(function () {
        var ResizeTarget = $('#B');

        ResizeTarget.resize(function () {
            var target = $('#B2');
            target.css('height', ResizeTarget.height());
        }).trigger('resize');
    }); 
}, 500);

Git: add vs push vs commit

add tells git to start tracking a file.

commit commits your current changes on your local repository

push pushes you local repo upstream.

How to add image for button in android?

Rather humorously, considering your tags, just use the ImageButton widget.

configure Git to accept a particular self-signed server certificate for a particular https remote

On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755

How to place div in top right hand corner of page

Try css:

.topcorner{
    position:absolute;
    top:10px;
    right: 10px;
 }

you can play with the top and right properties.

If you want to float the div even when you scroll down, just change position:absolute; to position:fixed;.

Hope it helps.

How to hide a mobile browser's address bar?

create host file = manifest.json

html tag head

<link rel="manifest" href="/manifest.json">

file

manifest.json

{
"name": "news",
"short_name": "news",
"description": "des news application day",
"categories": [
"news",
"business"
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone",
"orientation": "natural",
"lang": "fa",
"dir": "rtl",
"start_url": "/?application=true",
"gcm_sender_id": "482941778795",
"DO_NOT_CHANGE_GCM_SENDER_ID": "Do not change the GCM Sender ID",
"icons": [
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"related_applications": [
{
"platform": "play",
"url": "https://play.google.com/store/apps/details?id=ir.divar"
}
],
"prefer_related_applications": true
}

Detect encoding and make everything UTF-8

Detecting the encoding is hard.

mb_detect_encoding works by guessing, based on a number of candidates that you pass it. In some encodings, certain byte-sequences are invalid, an therefore it can distinguish between various candidates. Unfortunately, there are a lot of encodings, where the same bytes are valid (but different). In these cases, there is no way to determine the encoding; You can implement your own logic to make guesses in these cases. For example, data coming from a Japanese site might be more likely to have a Japanese encoding.

As long as you only deal with Western European languages, the three major encodings to consider are utf-8, iso-8859-1 and cp-1252. Since these are defaults for many platforms, they are also the most likely to be reported wrongly about. Eg. if people use different encodings, they are likely to be frank about it, since else their software would break very often. Therefore, a good strategy is to trust the provider, unless the encoding is reported as one of those three. You should still doublecheck that it is indeed valid, using mb_check_encoding (note that valid is not the same as being - the same input may be valid for many encodings). If it is one of those, you can then use mb_detect_encoding to distinguish between them. Luckily that is fairly deterministic; You just need to use the proper detect-sequence, which is UTF-8,ISO-8859-1,WINDOWS-1252.

Once you've detected the encoding you need to convert it to your internal representation (UTF-8 is the only sane choice). The function utf8_encode transforms ISO-8859-1 to UTF-8, so it can only used for that particular input type. For other encodings, use mb_convert_encoding.

Unable to copy a file from obj\Debug to bin\Debug

Well i have the same problem, my way to fix it was to stop and disable the "application experience" service in Windows.

How to test for $null array in PowerShell

You can reorder the operands:

$null -eq $foo

Note that -eq in PowerShell is not an equivalence relation.

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

How to bind a List<string> to a DataGridView control?

This is common issue, another way is to use DataTable object

DataTable dt = new DataTable();
dt.Columns.Add("column name");

dt.Rows.Add(new object[] { "Item 1" });
dt.Rows.Add(new object[] { "Item 2" });
dt.Rows.Add(new object[] { "Item 3" });

This problem is described in detail here: http://www.psworld.pl/Programming/BindingListOfString

Error when testing on iOS simulator: Couldn't register with the bootstrap server

I faced this kind of issue once in my case here's what i did

  1. Delete the app from simulator.
  2. Delete the derived data folder.
  3. Perform a clean action in the project by selecting the product menu - clean
  4. Reset the simulator.
  5. Quit Xcode.
  6. Try running the project now if its working fine else go to step 7
  7. Repeat all steps from 1 to 5 and then restart your machine.

In most of the cases i got it running at step 6 extreme cases i had to restart my machine.

How do I "Add Existing Item" an entire directory structure in Visual Studio?

It's annoying that Visual Studio doesn't support this natively, but CMake could generate the Visual Studio project as a work around.

Other than that, just use Qt Creator. It can then export a Visual Studio project.

Is there any way to wait for AJAX response and halt execution?

The simple answer is to turn off async. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.

Instead of writing this:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });
}

function foo () {
    var response = functABC();
    some_result = bar(response);
    // and other stuff and
    return some_result;
}

You should write it like this:

function functABC(callback){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: callback
    });
}

function foo (callback) {
    functABC(function(data){
        var response = data;
        some_result = bar(response);
        // and other stuff and
        callback(some_result);
    })
}

That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.


A quick explanation of why I say it's wrong to turn off async:

Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.

How to insert logo with the title of a HTML page?

Are you referring to the favicon?

Upload a 16x16px ico to your site, and link it in your head section.

<link rel="shortcut icon" href="/favicon.ico" />

There are a multitude of sites that help you convert images into .ico format too. This is just the first one I saw on Google. http://www.favicon.cc/

How to put wildcard entry into /etc/hosts?

use dnsmasq

pretending you're using a debian-based dist(ubuntu,mint..), check if it's installed with

(sudo) systemctl status dnsmasq

If it is just disabled start it with

(sudo) systemctl start dnsmasq

If you have to install it, write

(sudo) apt-get install dnsmasq

To define domains to resolve edit /etc/dnsmasq.conf like this

address=/example.com/127.0.0.1

to resolve *.example.com

! You need to reload dnsmasq to take effect for the changes !

systemctl reload dnsmasq

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

List directory in Go

Even simpler, use path/filepath:

package main    

import (
    "fmt"
    "log"
    "path/filepath"
)

func main() {
    files, err := filepath.Glob("*")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(files) // contains a list of all files in the current directory
}

Easy way to convert Iterable to Collection

While at it, do not forget that all collections are finite, while Iterable has no promises whatsoever. If something is Iterable you can get an Iterator and that is it.

for (piece : sthIterable){
..........
}

will be expanded to:

Iterator it = sthIterable.iterator();
while (it.hasNext()){
    piece = it.next();
..........
}

it.hasNext() is not required to ever return false. Thus in the general case you cannot expect to be able to convert every Iterable to a Collection. For example you can iterate over all positive natural numbers, iterate over something with cycles in it that produces the same results over and over again, etc.

Otherwise: Atrey's answer is quite fine.

Replace negative values in an numpy array

Try numpy.clip:

>>> import numpy
>>> a = numpy.arange(-10, 10)
>>> a
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])
>>> a.clip(0, 10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

You can clip only the bottom half with clip(0).

>>> a = numpy.array([1, 2, 3, -4, 5])
>>> a.clip(0)
array([1, 2, 3, 0, 5])

You can clip only the top half with clip(max=n). (This is much better than my previous suggestion, which involved passing NaN to the first parameter and using out to coerce the type.):

>>> a.clip(max=2)
array([ 1,  2,  2, -4,  2])

Another interesting approach is to use where:

>>> numpy.where(a <= 2, a, 2)
array([ 1,  2,  2, -4,  2])

Finally, consider aix's answer. I prefer clip for simple operations because it's self-documenting, but his answer is preferable for more complex operations.

How to pass multiple parameters in thread in VB

Pass multiple parameter for VB.NET 3.5

 Public Class MyWork

    Public Structure thread_Data            
        Dim TCPIPAddr As String
        Dim TCPIPPort As Integer            
    End Structure

    Dim STthread_Data As thread_Data
    STthread_Data.TCPIPAddr = "192.168.2.2"
    STthread_Data.TCPIPPort = 80  

    Dim multiThread As Thread = New Thread(AddressOf testthread)
    multiThread.SetApartmentState(ApartmentState.MTA)
    multiThread.Start(STthread_Data)     

    Private Function testthread(ByVal STthread_Data As thread_Data) 
        Dim IPaddr as string = STthread_Data.TCPIPAddr
        Dim IPport as integer = STthread_Data.TCPIPPort
        'Your work'        
    End Function

End Class

How to generate different random numbers in a loop in C++?

The way the function rand() works is that every time you call it, it generates a random number. In your code, you've called it once and stored it into the variable random_x. To get your desired random numbers instead of storing it into a variable, just call the function like this:

for (int t=0;t<10;t++)
{
    cout << "\nRandom X = " << rand() % 100;
}

android image button

You can just set the onClick of an ImageView and also set it to be clickable, Or set the drawableBottom property of a regular button.

    ImageView iv = (ImageView)findViewById(R.id.ImageView01);
   iv.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    // TODO Auto-generated method stub

   }
   });

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host: git.eclipse.org
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

'str' object does not support item assignment in Python

Hi you should try the string split method:

i = "Hello world"
output = i.split()

j = 'is not enough'

print 'The', output[1], j

How to create directory automatically on SD card

With API 8 and greater, the location of the SD card has changed. @fiXedd's answer is good, but for safer code, you should use Environment.getExternalStorageState() to check if the media is available. Then you can use getExternalFilesDir() to navigate to the directory you want (assuming you're using API 8 or greater).

You can read more in the SDK documentation.

Run a single migration file

You can just run the code directly out of the ruby file:

rails console
>> require "db/migrate/20090408054532_add_foos.rb"
>> AddFoos.new.up

Note: Very old versions of rails may require AddFoos.up rather than AddFoos.new.up.

An alternative way (without IRB) which relies on the fact that require returns an array of class names:

script/runner 'require("db/migrate/20090408054532_add_foos.rb").first.constantize.up'

Note that if you do this, it won't update the schema_migrations table, but it seems like that's what you want anyway.

Additionally, if it can't find the file you may need to use require("./db/..." or try require_relative depending on your working directory

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

Another solution:

public class CountryInfoResponse {
  private List<Object> geonames;
}

Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.

MySQL InnoDB not releasing disk space after deleting data rows from table

If you don't use innodb_file_per_table, reclaiming disk space is possible, but quite tedious, and requires a significant amount of downtime.

The How To is pretty in-depth - but I pasted the relevant part below.

Be sure to also retain a copy of your schema in your dump.

Currently, you cannot remove a data file from the system tablespace. To decrease the system tablespace size, use this procedure:

Use mysqldump to dump all your InnoDB tables.

Stop the server.

Remove all the existing tablespace files, including the ibdata and ib_log files. If you want to keep a backup copy of the information, then copy all the ib* files to another location before the removing the files in your MySQL installation.

Remove any .frm files for InnoDB tables.

Configure a new tablespace.

Restart the server.

Import the dump files.

How to do URL decoding in Java?

%3A and %2F are URL encoded characters. Use this java code to convert them back into : and /

String decoded = java.net.URLDecoder.decode(url, "UTF-8");

Optional Parameters in Go?

I am a little late, but if you like fluent interface you might design your setters for chained calls like this:

type myType struct {
  s string
  a, b int
}

func New(s string, err *error) *myType {
  if s == "" {
    *err = errors.New(
      "Mandatory argument `s` must not be empty!")
  }
  return &myType{s: s}
}

func (this *myType) setA (a int, err *error) *myType {
  if *err == nil {
    if a == 42 {
      *err = errors.New("42 is not the answer!")
    } else {
      this.a = a
    }
  }
  return this
}

func (this *myType) setB (b int, _ *error) *myType {
  this.b = b
  return this
}

And then call it like this:

func main() {
  var err error = nil
  instance :=
    New("hello", &err).
    setA(1, &err).
    setB(2, &err)

  if err != nil {
    fmt.Println("Failed: ", err)
  } else {
    fmt.Println(instance)
  }
}

This is similar to the Functional options idiom presented on @Ripounet answer and enjoys the same benefits but has some drawbacks:

  1. If an error occurs it will not abort immediately, thus, it would be slightly less efficient if you expect your constructor to report errors often.
  2. You'll have to spend a line declaring an err variable and zeroing it.

There is, however, a possible small advantage, this type of function calls should be easier for the compiler to inline but I am really not a specialist.

Looping through all the properties of object php

Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)

How to combine two vectors into a data frame

Alt simplification of https://stackoverflow.com/users/1969435/gx1sptdtda above:

cond <-c(1,2,3)
rating <-c(100,200,300)
df <- data.frame(cond, rating)
df
  cond rating
1    1    100
2    2    200
3    3    300

How do I get out of 'screen' without typing 'exit'?

  • Ctrl + A and then Ctrl+D. Doing this will detach you from the screen session which you can later resume by doing screen -r.

  • You can also do: Ctrl+A then type :. This will put you in screen command mode. Type the command detach to be detached from the running screen session.

What's the difference between 'int?' and 'int' in C#?

int? is shorthand for Nullable<int>.

This may be the post you were looking for.

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

[Uu]

Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

r'(?<![a-zA-Z])[uU](?![a-zA-Z])'

Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

Of course, you can remove the spaces around you from the replacement string.

If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'

And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

r'(?<!\w)[uU](?!\w)'

Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)

or

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)

depending on your preference.

I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

Install a Python package into a different directory using pip?

To pip install a library exactly where I wanted it, I navigated to the location I wanted the directory with the terminal then used

pip install mylibraryName -t . 

the logic of which I took from this page: https://cloud.google.com/appengine/docs/python/googlecloudstorageclient/download

What does "Content-type: application/json; charset=utf-8" really mean?

Dart http's implementation process the bytes thanks to that "charset=utf-8", so i'm sure several implementations out there supports this, to avoid the "latin-1" fallback charset when reading the bytes from the response. In my case, I totally lose format on the response body string, so I have to do the bytes encoding manually to utf8, or add that header "inner" parameter on my server's API response.

Firefox 'Cross-Origin Request Blocked' despite headers

I've found solution after 2 days :(.

Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials

Choice between vector::resize() and vector::reserve()

The two functions do vastly different things!

The resize() method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect the size(), iteration will go over all those elements, push_back will insert after them and you can directly access them using the operator[].

The reserve() method only allocates memory, but leaves it uninitialized. It only affects capacity(), but size() will be unchanged. There is no value for the objects, because nothing is added to the vector. If you then insert the elements, no reallocation will happen, because it was done in advance, but that's the only effect.

So it depends on what you want. If you want an array of 1000 default items, use resize(). If you want an array to which you expect to insert 1000 items and want to avoid a couple of allocations, use reserve().

EDIT: Blastfurnace's comment made me read the question again and realize, that in your case the correct answer is don't preallocate manually. Just keep inserting the elements at the end as you need. The vector will automatically reallocate as needed and will do it more efficiently than the manual way mentioned. The only case where reserve() makes sense is when you have reasonably precise estimate of the total size you'll need easily available in advance.

EDIT2: Ad question edit: If you have initial estimate, then reserve() that estimate. If it turns out to be not enough, just let the vector do it's thing.

What does Visual Studio mean by normalize inconsistent line endings?

Some lines end with \n.

Some other lines end with \r\n.

Visual Studio suggests you to make all lines end the same.

How do I properly 'printf' an integer and a string in C?

scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.

Call a Javascript function every 5 seconds continuously

Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/

Plus:

  • has nice fade in / fade out animation
  • will pause on :hover
  • will prevent running multiple actions (finish run animation before starting second)
  • will prevent going broken when in the tab ( browser stops scripts in the tabs)

Tested and working!

Check if selected dropdown value is empty using jQuery

You need to use .change() event as well as using # to target element by id:

$('#EventStartTimeMin').change(function() {
    if($(this).val()===""){ 
        console.log('empty');    
    }
});

Fiddle Demo

Set Google Maps Container DIV width and height 100%

If that div is the only thing on your page, set:

body, html {
  height: 100%;
  width: 100%;
}

Is it possible to force row level locking in SQL Server?

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

Combining two sorted lists in Python

If you want to do it in a manner more consistent with learning what goes on in the iteration try this

def merge_arrays(a, b):
    l= []

    while len(a) > 0 and len(b)>0:
        if a[0] < b[0]: l.append(a.pop(0))    
        else:l.append(b.pop(0))

    l.extend(a+b)
    print( l )

PHP split alternative?

Had the same issue, but my code must work on both PHP 5 & PHP 7..

Here is my piece of code, which solved this.. Input a date in dmY format with one of delimiters "/ . -"

<?php
function DateToEN($date){
  if ($date!=""){
    list($d, $m, $y) = function_exists("split") ?  split("[/.-]", $date) : preg_split("/[\/\.\-]+/", $date);
    return $y."-".$m."-".$d;
  }else{
    return false;
  }
}
?>

Convert LocalDateTime to LocalDateTime in UTC

Question?

Looking at the answers and the question, it seems the question has been modified significantly. So to answer the current question:

Convert LocalDateTime to LocalDateTime in UTC.

Timezone?

LocalDateTime does not store any information about the time-zone, it just basically holds the values of year, month, day, hour, minute, second, and smaller units. So an important question is: What is the timezone of the original LocalDateTime? It might as well be UTC already, therefore no conversion has to be made.

System Default Timezone

Considering that you asked the question anyway, you probably meant that the original time is in your system-default timezone and you want to convert it to UTC. Because usually a LocalDateTime object is created by using LocalDateTime.now() which returns the current time in the system-default timezone. In this case, the conversion would be the following:

LocalDateTime convertToUtc(LocalDateTime time) {
    return time.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

An example of the conversion process:

2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+1 // [atZone] converted to ZonedDateTime (system timezone is Madrid)
2019-02-25 10:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 10:39 // [toLocalDateTime] losing the timezone information

Explicit Timezone

In any other case, when you explicitly specify the timezone of the time to convert, the conversion would be the following:

LocalDateTime convertToUtc(LocalDateTime time, ZoneId zone) {
    return time.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

An example of the conversion process:

2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+2 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2019-02-25 09:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 09:39 // [toLocalDateTime] losing the timezone information

The atZone() Method

The result of the atZone() method depends on the time passed as its argument, because it considers all the rules of the timezone, including Daylight Saving Time (DST). In the examples, the time was 25th February, in Europe this means winter time (no DST).

If we were to use a different date, let's say 25th August from last year, the result would be different, considering DST:

2018-08-25 11:39 // [time] original LocalDateTime without a timezone
2018-08-25 11:39 GMT+3 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2018-08-25 08:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2018-08-25 08:39 // [toLocalDateTime] losing the timezone information

The GMT time does not change. Therefore the offsets in the other timezones are adjusted. In this example, the summer time of Estonia is GMT+3, and winter time GMT+2.

Also, if you specify a time within the transition of changing clocks back one hour. E.g. October 28th, 2018 03:30 for Estonia, this can mean two different times:

2018-10-28 03:30 GMT+3 // summer time [UTC 2018-10-28 00:30]
2018-10-28 04:00 GMT+3 // clocks are turned back 1 hour [UTC 2018-10-28 01:00]
2018-10-28 03:00 GMT+2 // same as above [UTC 2018-10-28 01:00]
2018-10-28 03:30 GMT+2 // winter time [UTC 2018-10-28 01:30]

Without specifying the offset manually (GMT+2 or GMT+3), the time 03:30 for the timezone Europe/Tallinn can mean two different UTC times, and two different offsets.

Summary

As you can see, the end result depends on the timezone of the time passed as an argument. Because the timezone cannot be extracted from the LocalDateTime object, you have to know yourself which timezone it is coming from in order to convert it to UTC.

Best Way to read rss feed in .net Using C#

You're looking for the SyndicationFeed class, which does exactly that.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

Here is an online converter with an article after explaining all the algorithms for color conversion.

You probably would prefer a ready-made C version but it should not be long to apply and it could help other people trying to do the same in another language or with another color space.

Bootstrap alert in a fixed floating div at the top of page

If you want an alert that is fixed to the top and you are using bootstrap navbar navbar-fixed-top the following style class will overlay they alert on top of the nav:

.alert-fixed {
    position:fixed; 
    top: 0px; 
    left: 0px; 
    width: 100%;
    z-index:9999; 
    border-radius:0px
}

This worked well for me to provide alerts even when the user is scrolled down in the page.

Add multiple items to already initialized arraylist in java

If you are looking to avoid multiple code lines to save space, maybe this syntax could be useful:

        java.util.ArrayList lisFieldNames = new ArrayList() {
            {
                add("value1"); 
                add("value2");
            }
        };

Removing new lines, you can show it compressed as:

        java.util.ArrayList lisFieldNames = new ArrayList() {
            {
                add("value1"); add("value2"); (...);
            }
        };

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.

More details here.

Button text toggle in jquery

Use an if/else statement.. or ternary if you understand it

$(".pushme").click(function () {
    var $el = $(this);
    $el.text($el.text() == "DON'T PUSH ME" ? "PUSH ME": "DON'T PUSH ME");
});

http://jsfiddle.net/dFZyv/

Duplicate symbols for architecture x86_64 under Xcode

In my case, I named an Entity of my Core Data Model the same as an Object. So: I defined an object "Event.h" and at the same time I had this entity called "Event". I ended up renaming the entity.

How to copy folders to docker image from Dockerfile?

COPY . <destination>

Which would be in your case:

COPY . /

How to use classes from .jar files?

You need to add the jar file in the classpath. To compile your java class:

javac -cp .;jwitter.jar MyClass.java

To run your code (provided that MyClass contains a main method):

java -cp .;jwitter.jar MyClass

You can have the jar file anywhere. The above work if the jar file is in the same directory as your java file.

Storing query results into a variable and modifying it inside a Stored Procedure

Or you can use one SQL-command instead of create and call stored procedure

INSERT INTO [order_cart](orId,caId)
OUTPUT inserted.*
SELECT
   (SELECT MAX(orId) FROM [order]) as orId,
   (SELECT MAX(caId) FROM [cart]) as caId;

How to perform update operations on columns of type JSONB in Postgres 9.4

This question was asked in the context of postgres 9.4, however new viewers coming to this question should be aware that in postgres 9.5, sub-document Create/Update/Delete operations on JSONB fields are natively supported by the database, without the need for extension functions.

See: JSONB modifying operators and functions

How many bytes in a JavaScript string?

Note that if you're targeting node.js you can use Buffer.from(string).length:

var str = "\u2620"; // => "?"
str.length; // => 1 (character)
Buffer.from(str).length // => 3 (bytes)

"Unknown class <MyClass> in Interface Builder file" error at runtime

In my case I got this error because I'd tried to save some work by creating a new project and then deleting several of the source files and copying over the source files of the same name from the working project. I also copied my MainStoryBoard file which was looking for my RootViewController. However, when I had deleted the original RootViewController and then added in the RootViewController from the previous product, evidently the Add Files operation failed to "check" the target box as suggested above. By merely visting all of the newley imported ".m" files and making sure that the target membership box was checked, all was well. I think what was happening was that the storyboard file was looking for a class that had been "excluded" from the link because the target membership was unchecked. Making sure the required files for the target are so designated in the target membership in the file inspector did the trick. Thanks Pat! (see above)

Blocks and yields in Ruby

Yields, to put it simply, allow the method you create to take and call blocks. The yield keyword specifically is the spot where the 'stuff' in the block will be performed.

remove attribute display:none; so the item will be visible

You should remove "style" attribute instead of "display" property :

$("span").removeAttr("style");

How do I connect to this localhost from another computer on the same network?

If you are on Windows, use ipconfig to get the local IPv4 address, and then specify that under your Apache configuration file: httpd.conf, like:

Listen: 10.20.30.40:80

Restart your Apache server and test it from other computer on the network.

WCF error - There was no endpoint listening at

Different case but may help someone,

In my case Window firewall was enabled on Server,

Two thinks can be done,

1) Disable windows firewall (your on risk but it will get thing work)

2) Add port in inbound rule.

Thanks .

How can I use grep to find a word inside a folder?

grep -nr string my_directory

Additional notes: this satisfies the syntax grep [options] string filename because in Unix-like systems, a directory is a kind of file (there is a term "regular file" to specifically refer to entities that are called just "files" in Windows).

grep -nr string reads the content to search from the standard input, that is why it just waits there for input from you, and stops doing so when you press ^C (it would stop on ^D as well, which is the key combination for end-of-file).

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

Answer is adding this 2 lines of code to Global.asax.cs Application_Start method

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = 
    Newtonsoft.Json.PreserveReferencesHandling.All;

Reference: Handling Circular Object References

UITableView example for Swift

//    UITableViewCell set Identify "Cell"
//    UITableView Name is  tableReport

UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet weak var tableReport: UITableView!  

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 5;
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            cell.textLabel?.text = "Report Name"
            return cell;
        }
}

Convert RGB values to Integer

I think the code is something like:

int rgb = red;
rgb = (rgb << 8) + green;
rgb = (rgb << 8) + blue;

Also, I believe you can get the individual values using:

int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

Catalina Update / Desktop Permissions

I come across this once a year on macOS. I usually use apache2 for hosting a folder on my desktop.

If you are trying to give access to the desktop folder you need to follow this to allow httpd to have access to all folders: https://apple.stackexchange.com/a/373139/353465

Regular expression - starting and ending with a character string

Example: ajshdjashdjashdlasdlhdlSTARTasdasdsdaasdENDaknsdklansdlknaldknaaklsdn

1) START\w*END return: STARTasdasdsdaasdEND - will give you words between START and END

2) START\d*END return: START12121212END - will give you numbers between START and END

3) START\d*_\d*END return: START1212_1212END - will give you numbers between START and END having _

How to return multiple values in one column (T-SQL)?

You can use a function with COALESCE.

CREATE FUNCTION [dbo].[GetAliasesById]
(
    @userID int
)
RETURNS varchar(max)
AS
BEGIN
    declare @output varchar(max)
    select @output = COALESCE(@output + ', ', '') + alias
    from UserAliases
    where userid = @userID

    return @output
END

GO

SELECT UserID, dbo.GetAliasesByID(UserID)
FROM UserAliases
GROUP BY UserID

GO

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

if it is a link then $(this).unbind("click"); would re-enable the link clicking and the default behavior would be restored.

I have created a demo JS fiddle to demonstrate how this works:

Here is the code of the JS fiddle:

HTML:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<a href="http://jquery.com">Default click action is prevented, only on the third click it would be enabled</a>
<div id="log"></div>

Javascript:

<script>
var counter = 1;
$(document).ready(function(){
$( "a" ).click(function( event ) {
  event.preventDefault();

  $( "<div>" )
    .append( "default " + event.type + " prevented "+counter )
    .appendTo( "#log" );

    if(counter == 2)
    {
        $( "<div>" )
    .append( "now enable click" )
    .appendTo( "#log" );

    $(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
    }
    else
    {
        $( "<div>" )
    .append( "still disabled" )
    .appendTo( "#log" );
    }
    counter++;
});
});
</script>

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

How to call a function in shell Scripting?

#!/bin/bash  
# functiontest.sh a sample to call the function in the shell script  

choice="true"  
function process_install  
{  
  commands...
}  

function process_exit  
{
  commands...  
}  

function main  
{  
  if [[ "$choice" == "true" ]]; then  
      process_install
  elif [[ "$choice" == "false" ]]; then  
      process_exit  
  fi  
}  

main "$@"  

it will start from the main function

Start an external application from a Google Chrome Extension?

Question has a good pagerank on google, so for anyone who's looking for answer to this question this might be helpful.

There is an extension in google chrome marketspace to do exactly that: https://chrome.google.com/webstore/detail/hccmhjmmfdfncbfpogafcbpaebclgjcp

where does MySQL store database files?

For WampServer, click on its tray icon and then in the popup cascading menu select

MySQL | MySQL settings | datadir

MySQL Data Directory

How to check currently internet connection is available or not in android

This function works fine...

public void checkConnection()
    {
        ConnectivityManager connectivityManager=(ConnectivityManager)

                this.getSystemService(Context.CONNECTIVITY_SERVICE);


  NetworkInfo wifi=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);


 NetworkInfo  network=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);


        if (wifi.isConnected())
        {
           //Internet available

        }
        else if(network.isConnected())
        {
             //Internet available


        }
        else
        {
             //Internet is not available
        }
    }

Add the permission to AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Laravel Eloquent - Get one Row

You can do this too

Before you use this you must declare the DB facade in the controller Simply put this line for that

use Illuminate\Support\Facades\DB;

Now you can get a row using this

$getUserByEmail = DB::table('users')->where('email', $email)->first();

or by this too

$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['[email protected]']);

This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.

Hope this helps.

How to display a range input slider vertically

You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:

_x000D_
_x000D_
input[type="range"] {_x000D_
   position: absolute;_x000D_
   top: 40%;_x000D_
   transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
_x000D_
_x000D_


or the 3d transform equivalent:

input[type="range"] {
   transform: rotateZ(270deg);
}

You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.

How to merge specific files from Git branches

Are all the modifications to file.py in branch2 in their own commits, separate from modifications to other files? If so, you can simply cherry-pick the changes over:

git checkout branch1
git cherry-pick <commit-with-changes-to-file.py>

Otherwise, merge does not operate over individual paths...you might as well just create a git diff patch of file.py changes from branch2 and git apply them to branch1:

git checkout branch2
git diff <base-commit-before-changes-to-file.py> -- file.py > my.patch
git checkout branch1
git apply my.patch

Table column sizing

Disclaimer: This answer may be a bit old. Since the bootstrap 4 beta. Bootstrap has changed since then.

The table column size class has been changed from this

<th class="col-sm-3">3 columns wide</th>

to

<th class="col-3">3 columns wide</th>

error: Unable to find vcvarsall.bat

I wanted to run pysph on Windows 10 under Python 2.7 and got vcvarsall.bat was not found (from distutils)

My solution was the following:

Install Microsoft Visual C++ for Python 2.7 (like @Michael suggested)

On Windows 10 it was installed into (my username is Andreas):

C:\Users\Andreas\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0

Set environment variable VS90COMNTOOLS to the installation path of Visual C++ for Python 2.7 (see above path).

If it still doesn't work, then modifiy in the module

C:/Python27/lib/distutils

the file msvc9compiler.py. Find in it the function find_vcvarsall and do following modification.

Replace the line:

productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC")

with

productdir = os.path.join(toolsdir)

This is where vcvarsall.bat resides in my case (check, where vcvarsall.bat is in your installation).

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

If someone is using AFHTTPSessionManager then one can do like this to solve the issue,

I subclassed AFHTTPSessionManager where I'm doing like this,

NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:self.responseSerializer.acceptableContentTypes];
[contentTypes addObject:@"text/html"];
self.responseSerializer.acceptableContentTypes = contentTypes;

Table with table-layout: fixed; and how to make one column wider

You could just give the first cell (therefore column) a width and have the rest default to auto

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  width: 150px;_x000D_
}_x000D_
td+td {_x000D_
  width: auto;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>150px</td>_x000D_
    <td>equal</td>_x000D_
    <td>equal</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_


or alternatively the "proper way" to get column widths might be to use the col element itself

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
.wide {_x000D_
  width: 150px;_x000D_
}
_x000D_
<table>_x000D_
  <col span="1" class="wide">_x000D_
    <tr>_x000D_
      <td>150px</td>_x000D_
      <td>equal</td>_x000D_
      <td>equal</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Clear icon inside input text

I have written a simple component using jQuery and bootstrap. Give it a try: https://github.com/mahpour/bootstrap-input-clear-button

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

Append key/value pair to hash with << in Ruby

I had to do a similar thing but I needed to add values with same keys. When I use merge or update I can't push values with same keys. So I had to use array of hashes.

    my_hash_static = {:header =>{:company => 'xx', :usercode => 'xx', :password => 'xx',
                      :type=> 'n:n', :msgheader => from}, :body=>[]}
    my_hash_dynamic = {:mp=>{:msg=>message, :no=>phones} }        
    my_hash_full = my_hash_static[:body].push my_hash_dynamic

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
                .SpecialCells(xlCellTypeConstants).ClearContents
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

How can I have grep not print out 'No such file or directory' errors?

Errors like that are usually sent to the "standard error" stream, which you can pipe to a file or just make disappear on most commands:

grep pattern * -R -n 2>/dev/null

how much memory can be accessed by a 32 bit machine?

basically 32bit architecture can address 4GB as you expected. There are some techniques which allows processor to address more data like AWE or PAE.

Cross-Origin Read Blocking (CORB)

In a Chrome extension, you can use

chrome.webRequest.onHeadersReceived.addListener

to rewrite the server response headers. You can either replace an existing header or add an additional header. This is the header you want:

Access-Control-Allow-Origin: *

https://developers.chrome.com/extensions/webRequest#event-onHeadersReceived

I was stuck on CORB issues, and this fixed it for me.

No route matches "/users/sign_out" devise rails 3

If you are using Rails 3.1 make sure your application.html.erb sign out looks like:

<%= link_to "Sign out", destroy_user_session_path, :method => :delete %>

And that your javascript include line looks like the following

<%= javascript_include_tag 'application' %>

My guess is that some gems overwrite the new structure of the default.js location.

Removing elements with Array.map in JavaScript

That's not what map does. You really want Array.filter. Or if you really want to remove the elements from the original list, you're going to need to do it imperatively with a for loop.

How to return a specific element of an array?

Make sure return type of you method is same what you want to return. Eg: `

  public int get(int[] r)
  {
     return r[0];
  }

`

Note : return type is int, not int[], so it is able to return int.

In general, prototype can be

public Type get(Type[] array, int index)
{
    return array[index];
}

Check if array is empty or null

As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.

var album_text = [];

$("input[name='album_text[]']").each(function() {
    var value = $(this).val();
    if (value) {
        album_text.push(value);
    }
});
if (album_text.length === 0) {
    $('#error_message').html("Error");
}

else {
  //send data
}

Some notes on what you were doing and what I changed.

  1. $(this) is always a valid jQuery object so there's no reason to ever check if ($(this)). It may not have any DOM objects inside it, but you can check that with $(this).length if you need to, but that is not necessary here because the .each() loop wouldn't run if there were no items so $(this) inside your .each() loop will always be something.
  2. It's inefficient to use $(this) multiple times in the same function. Much better to get it once into a local variable and then use it from that local variable.
  3. It's recommended to initialize arrays with [] rather than new Array().
  4. if (value) when value is expected to be a string will both protect from value == null, value == undefined and value == "" so you don't have to do if (value && (value != "")). You can just do: if (value) to check for all three empty conditions.
  5. if (album_text.length === 0) will tell you if the array is empty as long as it is a valid, initialized array (which it is here).

What are you trying to do with this selector $("input[name='album_text[]']")?

Node.js: printing to console without a trailing newline?

You can use process.stdout.write():

process.stdout.write("hello: ");

See the docs for details.

How to import/include a CSS file using PHP code and not HTML code?

I don't know why you would need this but to do this, you could edit your css file:-

<style type="text/css">
body{
...;
...;
}
</style>

You have just added here and saved it as main.php. You can continue with main.css but it is better as .php since it does not remain a css file after you do that edit


Then edit your HTML file like this. NOTE: Make the include statement inside the tag

<html>
<head>
 <title>Sample</title>
 <?php inculde('css/main.css');>
</head>
<body>
...
...
</body>
</html>

Angular JS - angular.forEach - How to get key of the object?

The first parameter to the iterator in forEach is the value and second is the key of the object.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});

In your example, the outer forEach is actually:

angular.forEach($scope.filters, function(filterObj , filterKey)

Random word generator- Python

There is a package random_word could implement this request very conveniently:

 $ pip install random-word

from random_word import RandomWords
r = RandomWords()

# Return a single random word
r.get_random_word()
# Return list of Random words
r.get_random_words()
# Return Word of the day
r.word_of_the_day()

Viewing all `git diffs` with vimdiff

For people who want to use another diff tool not listed in git, say with nvim. here is what I ended up using:

git config --global alias.d difftool -x <tool name>

In my case, I set <tool name> to nvim -d and invoke the diff command with

git d <file>

How do I parse JSON with Objective-C?

NSString* path  = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"json"];

//????????????,????NSUTF8StringEncoding ????,
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

//??????????
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *jsonError;
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];


for (int i=0; i<[allKeys count]; i++) {
    NSDictionary *arrayResult = [allKeys objectAtIndex:i];
    NSLog(@"name=%@",[arrayResult objectForKey:@"storyboardName"]);

}

file:

 [
  {
  "ID":1,
  "idSort" : 0,
  "deleted":0,
  "storyboardName" : "MLMember",
  "dispalyTitle" : "76.360779",
  "rightLevel" : "10.010490",
  "showTabBar" : 1,
  "openWeb" : 0,
  "webUrl":""
  },
  {
  "ID":1,
  "idSort" : 0,
  "deleted":0,
  "storyboardName" : "0.00",
  "dispalyTitle" : "76.360779",
  "rightLevel" : "10.010490",
  "showTabBar" : 1,
  "openWeb" : 0,
  "webUrl":""
  }
  ]

Replacing .NET WebBrowser control with a better browser, like Chrome?

I know this isn't a 'replacement' WebBrowser control, but I was having some awful rendering issues whilst showing a page that was using BootStrap 3+ for layout etc, and then I found a post that suggested I use the following. Apparently, it's specific to IE and tells it to use the latest variation found on the client machine for rendering (so it won't use IE7, which I believe is the default).

So just put:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

somewhere in the head part of your document.

Obviously, if it's not your document, this won't help - though I personally consider it to be a security hole if you're reading pages not created by yourself through the WebBrowser control - why not just use a web browser!

IllegalArgumentException or NullPointerException for a null parameter?

If it's a setter method and null is being passed to it, I think it would make more sense to throw an IllegalArgumentException. A NullPointerException seems to make more sense in the case where you're attempting to actually use the null.

So, if you're using it and it's null, NullPointer. If it's being passed in and it's null, IllegalArgument.

How to iterate through a list of objects in C++

You're close.

std::list<Student>::iterator it;
for (it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

Note that you can define it inside the for loop:

for (std::list<Student>::iterator it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

And if you are using C++11 then you can use a range-based for loop instead:

for (auto const& i : data) {
    std::cout << i.name;
}

Here auto automatically deduces the correct type. You could have written Student const& i instead.

Deleting an object in java?

Your C++ is showing.

There is no delete in java, and all objects are created on the heap. The JVM has a garbage collector that relies on reference counts.

Once there are no more references to an object, it becomes available for collection by the garbage collector.

myObject = null may not do it; for example:

Foo myObject = new Foo(); // 1 reference
Foo myOtherObject = myObject; // 2 references
myObject = null; // 1 reference

All this does is set the reference myObject to null, it does not affect the object myObject once pointed to except to simply decrement the reference count by 1. Since myOtherObject still refers to that object, it is not yet available to be collected.

Xcode Product -> Archive disabled

You've changed your scheme destination to a simulator instead of Generic iOS Device.

That's why it is greyed out.

Change from a simulator to Generic iOS Device

React - changing an uncontrolled input

Simply create a fallback to '' if the this.state.name is null.

<input name="name" type="text" value={this.state.name || ''} onChange={this.onFieldChange('name').bind(this)}/>

This also works with the useState variables.

Google.com and clients1.google.com/generate_204

In the event that Chrome detects SSL connection timeouts, certificate errors, or other network issues that might be caused by a captive portal (a hotel's WiFi network, for instance), Chrome will make a cookieless request to http://www.gstatic.com/generate_204 and check the response code. If that request is redirected, Chrome will open the redirect target in a new tab on the assumption that it's a login page. Requests to the captive portal detection page are not logged.

Source: Google Chrome Privacy Whitepaper

How do I start a process from C#?

You can use the System.Diagnostics.Process.Start method to start a process. You can even pass a URL as a string and it'll kick off the default browser.

Android Studio - Unable to find valid certification path to requested target

"Unable to find valid certification path to requested target"

If you are getting this message, you probably are behind a Proxy on your company, which probably is signing all request certificates with your company root CA certificate, this certificate is trusted only inside your company, so Android Studio cannot validate any certificate signed with your company certificate as valid, so, you need to tell Android Studio to trust your company certificate, you do that by adding your company certificate to Android Studio truststore.

(I'm doing this on macOS, but should be similar on Linux or Windows)

  • First, you need to save your company root CA certificate as a file: you can ask this certificate to your IT department, or download it yourself, here is how. Open your browser and open this url, for example, https://jcenter.bintray.com/ or https://search.maven.org/, click on the lock icon and then click on Show certificate

enter image description here

On the popup window, to save the root certificate as a file, make sure to select the top level of the certificates chain (the root cert) and drag the certificate image to a folder/directory on your disk drive. It should be saved as a file as, for example: my-root-ca-cert.cer, or my-root-ca-cert.pem

enter image description here

  • Second, let's add this certificate to the accepted Server Certificates of Android Studio:

On Android Studio open Preferences -> Tools -> Server Certificates, on the box Accepted certificates click the plus icon (+), search the certificate you saved previously and click Apply and OK

enter image description here

  • Third, you need to add the certificate to the Android Studio JDK truststore (Gradle use this JDK to build the project, so it's important):

In Android Studio open File -> Project Structure -> SDK Location -> JDK Location

enter image description here

Copy the path of JDK Location, and open the Terminal, and change your directory to that path, for example, execute:

cd /Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/

(don't forget to scape the whitespace, "\ ")

Now, to import the certificate to the truststore, execute:

./bin/keytool -importcert -file /path/to/your/certificate/my-root-ca-cert.cer -keystore ./jre/lib/security/cacerts -storepass changeit -noprompt
  • Finally, restart Android Studio, or better click File -> Invalidate Caches / Restart

Done, you should be able to build your project now.

Git SSH error: "Connect to host: Bad file number"

Maybe your firewall or a blocker application (PeerBlock etc.) is blocking your port

Can I position an element fixed relative to parent?

first, set position: fixed and left: 50%, and second — now your start is a center and you can set new position with margin.